IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_UsersRoles]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_UsersRoles]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_U_Users]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_U_Users]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_U_UserFieldsClone]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_U_UserFieldsClone]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_U_UserFields]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_U_UserFields]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_Transcription]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_Transcription]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_SH_Appointments]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_SH_Appointments]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_ROI_Main]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_ROI_Main]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_RH_SyncRecords]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_RH_SyncRecords]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_RH_ClientInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_RH_ClientInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_REC_Notes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_REC_Notes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_OMHRS_SecAA]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_OMHRS_SecAA]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_NU_Users]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_NU_Users]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_NU_LookUps]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_NU_LookUps]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_NU_CrossReference]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_NU_CrossReference]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_TR_DocumentType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_TR_DocumentType]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_ROI_SentItemTypes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_ROI_SentItemTypes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_ROI_RequestTypes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_ROI_RequestTypes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_ROI_Requesters]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_ROI_Requesters]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_ROI_Contacts]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_ROI_Contacts]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_ROI_AuthTypes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_ROI_AuthTypes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_ResidenceCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_ResidenceCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_RequestPriority]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_RequestPriority]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_Reports]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_Reports]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_Provider]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_Provider]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_Project]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_Project]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_PostalCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_PostalCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_PatientService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_PatientService]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_OR_GeneralLink]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_OR_GeneralLink]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_MISCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_MISCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_MDAS_Group]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_MDAS_Group]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_LoanLocationType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_LoanLocationType]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_Institution10]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_Institution10]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_ICD9Interv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_ICD9Interv]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_ICD9Diag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_ICD9Diag]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_ICD9CMInterv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_ICD9CMInterv]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_ICD9CMDiag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_ICD9CMDiag]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_ICD10Interv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_ICD10Interv]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_ICD10DiagCCRS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_ICD10DiagCCRS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_ICD10Diag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_ICD10Diag]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_GeneralAssoc]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_GeneralAssoc]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_General_NoCIHI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_General_NoCIHI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_General]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_General]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_DirectBillFeeCodes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_DirectBillFeeCodes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_DeficiencyStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_DeficiencyStatus]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_DeficiencyCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_DeficiencyCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_ClinicalPathway]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_ClinicalPathway]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_CJRR_StickerCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_CJRR_StickerCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_ChartLocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_ChartLocation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_CCM_NHPIP_Code]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_CCM_NHPIP_Code]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_CCM_BodyRegion]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_CCM_BodyRegion]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_CC_RT_PROTOCOL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_CC_RT_PROTOCOL]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LU_Borrower]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LU_Borrower]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LLU_ProviderSpecialty]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LLU_ProviderSpecialty]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_LLU_ProviderServices]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_LLU_ProviderServices]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_H_RegionProfile]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_H_RegionProfile]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_H_InstProfPostSubmit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_H_InstProfPostSubmit]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_H_InstitutionProfile]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_H_InstitutionProfile]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_H_HospitalProfile]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_H_HospitalProfile]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_DefRollBackByProvider]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_DefRollBackByProvider]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_Def_Status]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_Def_Status]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_Def_SlipMain]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_Def_SlipMain]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_DAS_Header]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_DAS_Header]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_CtrlDetail_All]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_CtrlDetail_All]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_CtrlDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_CtrlDetail]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_CRS_SyncRecords]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_CRS_SyncRecords]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_CRS_SyncDemoChange]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_CRS_SyncDemoChange]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_CRS_Demographic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_CRS_Demographic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_CR_ReconHeader]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_CR_ReconHeader]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_CR_ErrorsHeader]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_CR_ErrorsHeader]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_CR_ErrorClaimHD]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_CR_ErrorClaimHD]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_CR_Demographic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_CR_Demographic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_CMV_ClinicalPathway]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_CMV_ClinicalPathway]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_CM_CPIFromVisit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_CM_CPIFromVisit]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_CM_CPIFromAmcare]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_CM_CPIFromAmcare]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_CM_CPIFromAbstract]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_CM_CPIFromAbstract]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_CM_CPI_Volume]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_CM_CPI_Volume]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_CM_CPI_Transcription]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_CM_CPI_Transcription]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_CM_CPI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_CM_CPI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_CL_PullListID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_CL_PullListID]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_CJRR_Abstract]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_CJRR_Abstract]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_CC_NDFPFromDisease]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_CC_NDFPFromDisease]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_CC_Demographic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_CC_Demographic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_AB_Main]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_AB_Main]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_AB_AbstractQueue]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_AB_AbstractQueue]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[U_AB_Abstract]') AND type in (N'P', N'PC'))
DROP PROCEDURE [U_AB_Abstract]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[TMP_LookUpNeoplasm_B]') AND type in (N'P', N'PC'))
DROP PROCEDURE [TMP_LookUpNeoplasm_B]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[TMP_LookUpDrugs_B]') AND type in (N'P', N'PC'))
DROP PROCEDURE [TMP_LookUpDrugs_B]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[TMP_CreatePrototypeNeoplasmFrench]') AND type in (N'P', N'PC'))
DROP PROCEDURE [TMP_CreatePrototypeNeoplasmFrench]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[TMP_CreatePrototypeNeoplasmEnglish]') AND type in (N'P', N'PC'))
DROP PROCEDURE [TMP_CreatePrototypeNeoplasmEnglish]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[TMP_CreatePrototypeDrugsFrench]') AND type in (N'P', N'PC'))
DROP PROCEDURE [TMP_CreatePrototypeDrugsFrench]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[TMP_CreatePrototypeDrugsEnglish]') AND type in (N'P', N'PC'))
DROP PROCEDURE [TMP_CreatePrototypeDrugsEnglish]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[TEST_ParentChildRelation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [TEST_ParentChildRelation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_TerminateSubmission]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_TerminateSubmission]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_RPC_Billing_Terminate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_RPC_Billing_Terminate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_RPC_Billing_Initialize]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_RPC_Billing_Initialize]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_RPC_Billing_GetBatchHeader]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_RPC_Billing_GetBatchHeader]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_Rehab_InitializeSubmission]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_Rehab_InitializeSubmission]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_Rehab_Checking_Period]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_Rehab_Checking_Period]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_PurgeDeletes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_PurgeDeletes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_Prep_Rehab_TransferDeath_ICD10]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_Prep_Rehab_TransferDeath_ICD10]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_Prep_DAD_Rehab_TransferDeath]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_Prep_DAD_Rehab_TransferDeath]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_Prep_DAD_9andCM_DoctorTransfers]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_Prep_DAD_9andCM_DoctorTransfers]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_Prep_DAD_9andCM_DiagnosisTransfers_new]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_Prep_DAD_9andCM_DiagnosisTransfers_new]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_Prep_DAD_9andCM_DiagnosisTransfers]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_Prep_DAD_9andCM_DiagnosisTransfers]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_Prep_AmcareECodes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_Prep_AmcareECodes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_Prep_AmcareDeletes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_Prep_AmcareDeletes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_Prep_AmCare9cm_Alberta]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_Prep_AmCare9cm_Alberta]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_OMHRS_SaveRecord]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_OMHRS_SaveRecord]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_OMHRS_SaveMED_Deletion]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_OMHRS_SaveMED_Deletion]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_OMHRS_MergeRecord]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_OMHRS_MergeRecord]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_OMHRS_MED_Delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_OMHRS_MED_Delete]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_OMHRS_MED_Correct]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_OMHRS_MED_Correct]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_OMHRS_Initialize]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_OMHRS_Initialize]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_OMHRS_GetDeletionCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_OMHRS_GetDeletionCount]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_OMHRS_ControlRecord]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_OMHRS_ControlRecord]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_OMHRS_CIHIError_Results]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_OMHRS_CIHIError_Results]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_OMHRS_CIHIError_ProcessError]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_OMHRS_CIHIError_ProcessError]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_OMHRS_CIHIError_GetAbstractID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_OMHRS_CIHIError_GetAbstractID]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_NACRS_ReasonForVisit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_NACRS_ReasonForVisit]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_NACRS_Project_Level1]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_NACRS_Project_Level1]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_ManageTempTables]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_ManageTempTables]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_MADE_Initialize]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_MADE_Initialize]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_InitializeSubmission]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_InitializeSubmission]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_Initialize_NACRS_CJRR]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_Initialize_NACRS_CJRR]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_IAR_MH_SaveRecord]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_IAR_MH_SaveRecord]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_IAR_MH_SaveMED_Deletion]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_IAR_MH_SaveMED_Deletion]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_IAR_MH_MergeRecord]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_IAR_MH_MergeRecord]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_IAR_MH_MED_Delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_IAR_MH_MED_Delete]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_IAR_MH_MED_Correct]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_IAR_MH_MED_Correct]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_IAR_MH_Initialize]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_IAR_MH_Initialize]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_IAR_ControlRecord]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_IAR_ControlRecord]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_GetTempTableList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_GetTempTableList]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_GetSubmissionSpecificTasks]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_GetSubmissionSpecificTasks]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_GetStructureID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_GetStructureID]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_GetStructureFile]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_GetStructureFile]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_GetRecords]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_GetRecords]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_GetParameterList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_GetParameterList]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_GetFileName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_GetFileName]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_GetFacilityFileStructure]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_GetFacilityFileStructure]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_GetBatchHeader]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_GetBatchHeader]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_DADSeparateSubmission]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_DADSeparateSubmission]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_CreateTempTable]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_CreateTempTable]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_CJRR_Initialize]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_CJRR_Initialize]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_CJRR_ControlRecord]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_CJRR_ControlRecord]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_CIHIError_Results]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_CIHIError_Results]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_CIHIError_ProcessError]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_CIHIError_ProcessError]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_CIHIError_GetAbstractID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_CIHIError_GetAbstractID]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_CIHI_Batch_Terminate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_CIHI_Batch_Terminate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_CIHI_Batch_Initialize]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_CIHI_Batch_Initialize]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_CheckUnSubmitedAdmissionIAR]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_CheckUnSubmitedAdmissionIAR]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_CheckUnSubmitedAdmission]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_CheckUnSubmitedAdmission]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_CheckRehabDeletion]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_CheckRehabDeletion]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_CheckLevel3Submission]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_CheckLevel3Submission]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_CheckLevel1Submission]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_CheckLevel1Submission]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_CheckForNacrsClosure]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_CheckForNacrsClosure]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_CheckForDADICD10Deletions]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_CheckForDADICD10Deletions]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_CheckBatchYear]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_CheckBatchYear]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_CCRS_MED_SaveRecord]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_CCRS_MED_SaveRecord]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_CCRS_MED_Delete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_CCRS_MED_Delete]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_CCRS_MED_CheckSequence]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_CCRS_MED_CheckSequence]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_CCRS_ControlRecord]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_CCRS_ControlRecord]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[SU_CCR_Initialize]') AND type in (N'P', N'PC'))
DROP PROCEDURE [SU_CCR_Initialize]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[Rpt_InpatientSummary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [Rpt_InpatientSummary]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_Transcription]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_Transcription]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_SP_MacKenzie_Project340]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_SP_MacKenzie_Project340]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_ROI_Main]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_ROI_Main]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_ROI_Invoice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_ROI_Invoice]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_RH_ClientInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_RH_ClientInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_RehabSubmissionLog]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_RehabSubmissionLog]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_OMHRS_SecAA]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_OMHRS_SecAA]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_LookupDetailByApplication]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_LookupDetailByApplication]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_LookupDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_LookupDetail]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_HSMR_Report]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_HSMR_Report]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_DefSlip]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_DefSlip]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_DataDictionary_French]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_DataDictionary_French]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_DataDictionary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_DataDictionary]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_CRS_Demographic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_CRS_Demographic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_CR_Demographic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_CR_Demographic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_ControlFile]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_ControlFile]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_CM_CPI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_CM_CPI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_CJRR_Abstract]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_CJRR_Abstract]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_Check_RecordLock]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_Check_RecordLock]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_CC_RecordInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_CC_RecordInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_Calculate_CodingDuration]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_Calculate_CodingDuration]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_AB_Main]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_AB_Main]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[R_AB_Abstract]') AND type in (N'P', N'PC'))
DROP PROCEDURE [R_AB_Abstract]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_WinRecsLogout]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_WinRecsLogout]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateVolumeDigitalIndicator]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateVolumeDigitalIndicator]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateUserPassword]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateUserPassword]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateTransNum]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateTransNum]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateSortOrder]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateSortOrder]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateProviderDeficiencyLetter]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateProviderDeficiencyLetter]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdatePasswordChangeDates]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdatePasswordChangeDates]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateOMHRS_X1_ForCorrection]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateOMHRS_X1_ForCorrection]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateOMHRS_X1]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateOMHRS_X1]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateInstitutionEncNum]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateInstitutionEncNum]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateDeficiencyLetter]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateDeficiencyLetter]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateCustomVerifyAbstract]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateCustomVerifyAbstract]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateCPIDeathDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateCPIDeathDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateCompleteVerifyRehab]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateCompleteVerifyRehab]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateCompleteVerifyOMHRS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateCompleteVerifyOMHRS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateCompleteVerifyClinic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateCompleteVerifyClinic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateCompleteVerifyCJRR]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateCompleteVerifyCJRR]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateCompleteVerifyCCRS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateCompleteVerifyCCRS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateCompleteVerifyAbstractLevel1]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateCompleteVerifyAbstractLevel1]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateCompleteVerifyAbstract]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateCompleteVerifyAbstract]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateClinicSubmitted]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateClinicSubmitted]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateClinicEncNum]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateClinicEncNum]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateClearAmcareSubmit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateClearAmcareSubmit]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateCIHIReturnStatus_Level1]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateCIHIReturnStatus_Level1]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateCIHIReturnStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateCIHIReturnStatus]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateChartNum]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateChartNum]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateBillingSequence]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateBillingSequence]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateBillingNum]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateBillingNum]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateAbstractVolume]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateAbstractVolume]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateAbstractNumber]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateAbstractNumber]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateAbstractForCorrection_UndoAuto]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateAbstractForCorrection_UndoAuto]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateAbstractForCorrection_Undo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateAbstractForCorrection_Undo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UpdateAbstractForCorrection]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UpdateAbstractForCorrection]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UnSeenAppointment]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UnSeenAppointment]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UniqueUser]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UniqueUser]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UniqueSchedule]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UniqueSchedule]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UniqueROI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UniqueROI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UniqueRehab]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UniqueRehab]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UniqueOMHRS_Episode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UniqueOMHRS_Episode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UniqueOMHRS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UniqueOMHRS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UniqueCPI_Volume]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UniqueCPI_Volume]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UniqueCPI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UniqueCPI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UniqueCJRR]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UniqueCJRR]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UniqueCancerCare]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UniqueCancerCare]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UniqueAmcare10]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UniqueAmcare10]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UniqueAmcare]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UniqueAmcare]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_UniqueAbstracting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_UniqueAbstracting]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_SHD_Insert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_SHD_Insert]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_SHD_GetDiagnosis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_SHD_GetDiagnosis]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_SetOMHRSIsCurrent]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_SetOMHRSIsCurrent]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_SetCCRSIsCurrent]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_SetCCRSIsCurrent]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_RollBackDeficiencyLevel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_RollBackDeficiencyLevel]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_ResetProviderStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_ResetProviderStatus]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_ResetProviderCurrentLevel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_ResetProviderCurrentLevel]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_RehabRecordLink]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_RehabRecordLink]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_Rehab_KeyFieldUpdated_Rollback]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_Rehab_KeyFieldUpdated_Rollback]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_Rehab_KeyFieldUpdated_Checking]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_Rehab_KeyFieldUpdated_Checking]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_Rehab_KeyFieldUpdated]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_Rehab_KeyFieldUpdated]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_OMHRSCIHIErrorList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_OMHRSCIHIErrorList]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_NCoderProb]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_NCoderProb]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_NCoder]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_NCoder]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_MultipleNDFP]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_MultipleNDFP]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_MultipleContactsClinic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_MultipleContactsClinic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_MultipleContacts]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_MultipleContacts]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LUPopulate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LUPopulate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpVolume]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpVolume]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpVisit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpVisit]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpUsers]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpUsers]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpTophoCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpTophoCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpStandard]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpStandard]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpSpecialProjectQuestion]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpSpecialProjectQuestion]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpROI_Item]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpROI_Item]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpReports]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpReports]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpReference]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpReference]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpProvider]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpProvider]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpNU_Codes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpNU_Codes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpNoCIHIFull]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpNoCIHIFull]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpNoCIHI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpNoCIHI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpNCoderXRef]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpNCoderXRef]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpMaintenance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpMaintenance]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpMaintassociateNoCIHI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpMaintassociateNoCIHI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpMaintassociate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpMaintassociate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpLinkFull]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpLinkFull]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpLink]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpLink]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpICD2]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpICD2]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpICD_NRS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpICD_NRS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpICD_CCRS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpICD_CCRS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpICD]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpICD]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookupDPGON]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookupDPGON]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookupDPG]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookupDPG]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpDetails]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpCodeFileMaint]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpCodeFileMaint]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpCodeFile]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpCodeFile]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpCIHIAssociate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpCIHIAssociate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpCIHI_CF]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpCIHI_CF]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpCIHI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpCIHI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpCharts_NoAccess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpCharts_NoAccess]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpCharts_Merge_RegionalID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpCharts_Merge_RegionalID]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpCharts_Merge]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpCharts_Merge]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpCharts_CPI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpCharts_CPI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpCharts]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpCharts]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpChart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpChart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpCCMVisit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpCCMVisit]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpBorrowFull]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpBorrowFull]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpBorrow]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpBorrow]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpBatchYear]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpBatchYear]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpBatchInstNumber]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpBatchInstNumber]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpBasicOptions]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpBasicOptions]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpAutoRequestor]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpAutoRequestor]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpAutoBorrower]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpAutoBorrower]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpAttribAssociate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpAttribAssociate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpAssociateNoCIHI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpAssociateNoCIHI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpAssociate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpAssociate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LookUpApp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LookUpApp]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_LogIn_DefCalc]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_LogIn_DefCalc]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryVolume]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryVolume]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryVisitAmcare]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryVisitAmcare]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryVisit2]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryVisit2]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryVisit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryVisit]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryUpdate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistorySched]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistorySched]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryROI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryROI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryReHab]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryReHab]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryRecordVH]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryRecordVH]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryRecord]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryRecord]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryPatient]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryPatient]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryOMHRS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryOMHRS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryMultiContact]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryMultiContact]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryMaint]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryMaint]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryLookUp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryLookUp]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryDeficiency]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryDeficiency]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryDef]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryDef]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryClinic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryClinic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryCJRR]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryCJRR]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryCCRS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryCCRS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryCareMap]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryCareMap]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryCancerCare]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryCancerCare]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_HistoryActivity]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_HistoryActivity]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetVolumePermLocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetVolumePermLocation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetUserProperties]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetUserProperties]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetTranscriptTemplateName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetTranscriptTemplateName]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetSingleDisplayField]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetSingleDisplayField]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetROIReportPath]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetROIReportPath]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetRequestLocationCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetRequestLocationCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetRequestLocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetRequestLocation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetPullListLoanNotes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetPullListLoanNotes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetProviderDeficiencyHeader]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetProviderDeficiencyHeader]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetProviderDefDetailForTran]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetProviderDefDetailForTran]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetProviderAuthent]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetProviderAuthent]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetProvdAppntDuration]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetProvdAppntDuration]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetPreviousTransaction]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetPreviousTransaction]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetPreviousLocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetPreviousLocation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetPermanentLocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetPermanentLocation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetPatientID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetPatientID]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetOMHRSIsCurrentList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetOMHRSIsCurrentList]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetNextVolumeID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetNextVolumeID]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetNextRequestID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetNextRequestID]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetNextPullListID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetNextPullListID]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetNextEncounterSequence]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetNextEncounterSequence]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetNextCCRSUniqueID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetNextCCRSUniqueID]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetLocationTypeDays]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetLocationTypeDays]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetLocationLoanDays]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetLocationLoanDays]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetLinkVolume]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetLinkVolume]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetInterfaceErrors]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetInterfaceErrors]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetHospitalDisplayCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetHospitalDisplayCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetFieldByKey]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetFieldByKey]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetFieldAudit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetFieldAudit]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetFacilityFileInformation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetFacilityFileInformation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetDeleteStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetDeleteStatus]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetDeficiencyVisit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetDeficiencyVisit]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetDeficiencyCodeFromTemplate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetDeficiencyCodeFromTemplate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetDADAbstractCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetDADAbstractCount]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetCurrentLocationCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetCurrentLocationCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetCurrentLocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetCurrentLocation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetCPIDeathIndicator]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetCPIDeathIndicator]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetCPIDeathDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetCPIDeathDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetCorrectionStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetCorrectionStatus]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetCorrectionCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetCorrectionCount]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetClinicOBECClaims]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetClinicOBECClaims]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetCIHIValue]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetCIHIValue]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetCIHIPeriodDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetCIHIPeriodDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetCIHIPeriodByDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetCIHIPeriodByDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetCCRSIsCurrentList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetCCRSIsCurrentList]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetBorrowerLocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetBorrowerLocation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetBillingAbstract]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetBillingAbstract]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetBasicOptionText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetBasicOptionText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_GetAbstVolumeID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_GetAbstVolumeID]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_Get_PriorityFromLocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_Get_PriorityFromLocation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_Get_PriorityFromBorrower]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_Get_PriorityFromBorrower]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_Get_HighPriorityFromLocAndBorrow]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_Get_HighPriorityFromLocAndBorrow]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FindPreviousMerge]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FindPreviousMerge]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchWRExpiry]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchWRExpiry]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchVolumeDefaults]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchVolumeDefaults]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchUserScreenValues]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchUserScreenValues]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchUserScreenEdit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchUserScreenEdit]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchUserInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchUserInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchTransSharedDefaults]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchTransSharedDefaults]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchSerivceBillInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchSerivceBillInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchROISentItemPriceTax]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchROISentItemPriceTax]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchROIContact]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchROIContact]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchRequestInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchRequestInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchRequesterType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchRequesterType]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchRehabDefaults]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchRehabDefaults]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchRehabAssessmentType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchRehabAssessmentType]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchProviderResidentFlag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchProviderResidentFlag]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchProject]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchProject]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchPrevAmcareSubmit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchPrevAmcareSubmit]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchPatientIDByVolumeID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchPatientIDByVolumeID]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchOMHRSDefaults]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchOMHRSDefaults]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchNTUser]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchNTUser]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchMergeRegionalInformation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchMergeRegionalInformation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchMergeInformation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchMergeInformation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchMergeDuplicateVisit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchMergeDuplicateVisit]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchMergedAbstract]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchMergedAbstract]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchLUCodeByValidCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchLUCodeByValidCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchLUCodeBySystemCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchLUCodeBySystemCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchLUCIHICodeBySystemCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchLUCIHICodeBySystemCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchLogIn]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchLogIn]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchLocatorVolume]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchLocatorVolume]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchLastDBUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchLastDBUpdate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchInterventionSurgical]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchInterventionSurgical]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchInterventionSDS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchInterventionSDS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchInterventionOperative]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchInterventionOperative]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchInstitution]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchInstitution]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchICDTypeDates]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchICDTypeDates]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchICDInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchICDInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchHospital]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchHospital]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchFullVisit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchFullVisit]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchEnCoderICD]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchEnCoderICD]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchDeficiencyType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchDeficiencyType]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchDeficiencyRollback]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchDeficiencyRollback]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchDeficiencyProvStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchDeficiencyProvStatus]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchDeficiencyLinkCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchDeficiencyLinkCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchDeficiencyLevels]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchDeficiencyLevels]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchDeficiencyLettersForReport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchDeficiencyLettersForReport]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchDeficiencyLettersByProvider]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchDeficiencyLettersByProvider]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchDeficiencyLetters]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchDeficiencyLetters]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchDeficiencyHeaderByProviders]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchDeficiencyHeaderByProviders]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchDefaultResidenceCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchDefaultResidenceCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchDefaultProvSpec]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchDefaultProvSpec]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchDefaultProvServ]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchDefaultProvServ]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchDefaultProvMIS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchDefaultProvMIS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchDefaultProvBillSpec]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchDefaultProvBillSpec]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchCtrlDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchCtrlDetail]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchChartSubmitAbstracts]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchChartSubmitAbstracts]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchChartFamily]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchChartFamily]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchCharLockInformation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchCharLockInformation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchCCRSDefaults]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchCCRSDefaults]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchCareTypeByInstNo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchCareTypeByInstNo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_FetchAssessDefaults]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_FetchAssessDefaults]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_ELOSCalculate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_ELOSCalculate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_DADCIHIErrorList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_DADCIHIErrorList]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CPIMerge_Relocate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CPIMerge_Relocate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CPIMerge_RegionalPatientID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CPIMerge_RegionalPatientID]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CPIMerge_RecordFlag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CPIMerge_RecordFlag]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CPIMerge_GetVisitForRelocate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CPIMerge_GetVisitForRelocate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CPIMerge_GetRelocateVisit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CPIMerge_GetRelocateVisit]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CPIMerge_Check]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CPIMerge_Check]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CPIMerge]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CPIMerge]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CPI_ROILegalComments_Save]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CPI_ROILegalComments_Save]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CPI_ROILegalComments_Fetch]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CPI_ROILegalComments_Fetch]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CMG2006_T]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CMG2006_T]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CMG2005_T]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CMG2005_T]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CMG2004_T]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CMG2004_T]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CMG2003_T]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CMG2003_T]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CMG2002_T]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CMG2002_T]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CMG2002_9]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CMG2002_9]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CMG2001_T]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CMG2001_T]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CMG2001_9]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CMG2001_9]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CMG2000_9]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CMG2000_9]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CM_MergeLogDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CM_MergeLogDetail]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CM_MergeLog_UNDO]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CM_MergeLog_UNDO]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CM_MergeLog]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CM_MergeLog]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CloseLoginSession]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CloseLoginSession]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckVIPStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckVIPStatus]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckUserIsRole]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckUserIsRole]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckUniqueProvider]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckUniqueProvider]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckUniqueMISCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckUniqueMISCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckRehabRecordExists]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckRehabRecordExists]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckRehabDischValue]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckRehabDischValue]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckRehabAdmitValue]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckRehabAdmitValue]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckProjectQuestion]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckProjectQuestion]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckPreviouPassword]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckPreviouPassword]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckNUCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckNUCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckNTAuthority]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckNTAuthority]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckMergeParent]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckMergeParent]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckLUDisplayCodeCF]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckLUDisplayCodeCF]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckLUDisplayCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckLUDisplayCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckLUCIHICodeCF]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckLUCIHICodeCF]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckLUCIHICode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckLUCIHICode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckInstitutionCareType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckInstitutionCareType]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckDiagnosisM]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckDiagnosisM]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckCPIDeleteOK]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckCPIDeleteOK]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckCCTopoStaging]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckCCTopoStaging]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckCCRecordExists]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckCCRecordExists]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckCCDiagnosisStaging]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckCCDiagnosisStaging]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckBasicOption]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckBasicOption]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckALCLOS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckALCLOS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_CheckAbsComplete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_CheckAbsComplete]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_Check_ProviderSuspend]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_Check_ProviderSuspend]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_Check_OMHRS_LastX80]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_Check_OMHRS_LastX80]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_Check_OMHRS_Admission_A1]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_Check_OMHRS_Admission_A1]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_Check_DeficiencyActivity]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_Check_DeficiencyActivity]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_Check_CLRequest]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_Check_CLRequest]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_Check_CLLoan]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_Check_CLLoan]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_ChangeOMHRS_AssessType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_ChangeOMHRS_AssessType]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_ChangeCCRS_AssessType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_ChangeCCRS_AssessType]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_AmcareCIHIErrorList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [P_AmcareCIHIErrorList]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_UpdateUserRule]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_UpdateUserRule]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_TopXDiagInterv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_TopXDiagInterv]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_StandAloneSecurity]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_StandAloneSecurity]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_Security]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_Security]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpRangeMorph]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpRangeMorph]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpRangeCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpRangeCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpNeoplasmLast_B]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpNeoplasmLast_B]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpNeoplasm_F]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpNeoplasm_F]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpNeoplasm_C]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpNeoplasm_C]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpNeoplasm_B]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpNeoplasm_B]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpDrugsLast_B]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpDrugsLast_B]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpDrugs_F]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpDrugs_F]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpDrugs_C]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpDrugs_C]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpDrugs_B]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpDrugs_B]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpCDCodeSimpler]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpCDCodeSimpler]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpCDCodeAdvTest]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpCDCodeAdvTest]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpCDCodeAdv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpCDCodeAdv]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpCDCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpCDCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpAlphaInt_F]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpAlphaInt_F]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpAlphaInt_C]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpAlphaInt_C]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpAlphaInt_B]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpAlphaInt_B]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpAlphaECI_F]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpAlphaECI_F]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpAlphaECI_C]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpAlphaECI_C]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpAlphaECI_B]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpAlphaECI_B]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpAlpha_F]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpAlpha_F]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpAlpha_C]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpAlpha_C]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LookUpAlpha_B]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LookUpAlpha_B]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_LinkCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_LinkCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_InsertUserRule]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_InsertUserRule]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_IN_Prv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_IN_Prv]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_GetUserPrvNotes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_GetUserPrvNotes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_GetUserNotes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_GetUserNotes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_GetProfiles]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_GetProfiles]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_GetLUType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_GetLUType]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_GetIProfile]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_GetIProfile]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_GetInclude]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_GetInclude]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_GetGuidelinesCodes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_GetGuidelinesCodes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_GetExcludesUP]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_GetExcludesUP]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_GetExcludes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_GetExcludes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_GetExclude]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_GetExclude]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_GetDProfile]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_GetDProfile]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_ExtraValuesFr]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_ExtraValuesFr]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_ExtraValues]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_ExtraValues]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_DelUserGuideline]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_DelUserGuideline]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_DeleteSecurity]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_DeleteSecurity]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_CreatePrototypeNeoplasmFrench]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_CreatePrototypeNeoplasmFrench]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_CreatePrototypeNeoplasmEnglish]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_CreatePrototypeNeoplasmEnglish]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_CreatePrototypeDrugsFrench]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_CreatePrototypeDrugsFrench]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_CreatePrototypeDrugsEnglish]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_CreatePrototypeDrugsEnglish]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_CodeSearch2]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_CodeSearch2]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NU_CodeSearch]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NU_CodeSearch]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[NewLookUpKey]') AND type in (N'P', N'PC'))
DROP PROCEDURE [NewLookUpKey]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[MG_GetMessageInfoFr]') AND type in (N'P', N'PC'))
DROP PROCEDURE [MG_GetMessageInfoFr]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[MG_GetMessageInfo2]') AND type in (N'P', N'PC'))
DROP PROCEDURE [MG_GetMessageInfo2]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[MG_GetMessageInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [MG_GetMessageInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[M_TableContents]') AND type in (N'P', N'PC'))
DROP PROCEDURE [M_TableContents]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[M_ShrinkDB]') AND type in (N'P', N'PC'))
DROP PROCEDURE [M_ShrinkDB]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[M_SetViewPermission]') AND type in (N'P', N'PC'))
DROP PROCEDURE [M_SetViewPermission]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[M_ServerMemory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [M_ServerMemory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[M_SecurityMed2020]') AND type in (N'P', N'PC'))
DROP PROCEDURE [M_SecurityMed2020]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[M_RecoveryMode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [M_RecoveryMode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[M_OjectSearch]') AND type in (N'P', N'PC'))
DROP PROCEDURE [M_OjectSearch]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[M_NewIndexFind]') AND type in (N'P', N'PC'))
DROP PROCEDURE [M_NewIndexFind]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[M_IndexesInsert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [M_IndexesInsert]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[M_IndexCleanupNew]') AND type in (N'P', N'PC'))
DROP PROCEDURE [M_IndexCleanupNew]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[M_IndexCleanup]') AND type in (N'P', N'PC'))
DROP PROCEDURE [M_IndexCleanup]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[M_EnableViewProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [M_EnableViewProcess]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[M_DetectDuplicates]') AND type in (N'P', N'PC'))
DROP PROCEDURE [M_DetectDuplicates]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[M_DeleteBackup]') AND type in (N'P', N'PC'))
DROP PROCEDURE [M_DeleteBackup]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[M_CreateIndex]') AND type in (N'P', N'PC'))
DROP PROCEDURE [M_CreateIndex]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[M_CreateBackup]') AND type in (N'P', N'PC'))
DROP PROCEDURE [M_CreateBackup]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[M_CheckUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [M_CheckUpdate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[M_BAKUP_TABLE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [M_BAKUP_TABLE]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_VisitHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_VisitHistory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_Users]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_Users]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_Transcription]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_Transcription]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_Trans_WordMerge]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_Trans_WordMerge]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_Schedule]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_Schedule]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_SchedAppnt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_SchedAppnt]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_ROI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_ROI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_Reports]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_Reports]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_ReportDistribution]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_ReportDistribution]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_RehabData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_RehabData]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_RegionProf]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_RegionProf]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_REC_Notes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_REC_Notes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_PurgedPullList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_PurgedPullList]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_Purge]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_Purge]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_PullListForPurge]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_PullListForPurge]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_PullList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_PullList]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_OMHRS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_OMHRS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_NU_PRV_Notes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_NU_PRV_Notes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_NU_LookUps]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_NU_LookUps]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_NU_CrossReference]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_NU_CrossReference]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_NextAvailableApp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_NextAvailableApp]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_LUReports]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_LUReports]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_LUProvider]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_LUProvider]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_LUMDAS_Group]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_LUMDAS_Group]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_LUGeneral]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_LUGeneral]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_Locator_Activities]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_Locator_Activities]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_LLUProvdrSpec]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_LLUProvdrSpec]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_LLUProvdrServ]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_LLUProvdrServ]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_InstProf]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_InstProf]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_HospProf]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_HospProf]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_GetMCCPartition]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_GetMCCPartition]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_DPG_Years]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_DPG_Years]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_DPG_Opt_Summary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_DPG_Opt_Summary]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_DPG_Opt_Detail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_DPG_Opt_Detail]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_DPG]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_DPG]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_DisplayFields]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_DisplayFields]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_DefSlipSummary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_DefSlipSummary]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_Deficiency_Activities]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_Deficiency_Activities]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_Deficiency]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_Deficiency]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_Def_Main]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_Def_Main]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_Def_ChartInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_Def_ChartInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_DBUpdateHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_DBUpdateHistory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CtrlMain]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CtrlMain]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CtrlDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CtrlDetail]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CPI_VolumeOrphans]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CPI_VolumeOrphans]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CPI_VolumeAbstracts]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CPI_VolumeAbstracts]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CPI_Volume_List]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CPI_Volume_List]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CPI_Volume_FormList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CPI_Volume_FormList]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CPI_Volume_AbstractList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CPI_Volume_AbstractList]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CPI_Volume]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CPI_Volume]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CPI_Deficiency_List]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CPI_Deficiency_List]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CPI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CPI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CMV_ChartInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CMV_ChartInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CMG_Years]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CMG_Years]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CMG_Opt_Summary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CMG_Opt_Summary]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CMG_Opt_Detail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CMG_Opt_Detail]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CMG]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CMG]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_ClinicBatchVerify]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_ClinicBatchVerify]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_ClinicBatchLoadItem]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_ClinicBatchLoadItem]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_ClinicBatchLoad]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_ClinicBatchLoad]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_ClinicalPathway]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_ClinicalPathway]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_Clinic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_Clinic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CL_ActivityVolume]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CL_ActivityVolume]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CL_ActivityRaw]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CL_ActivityRaw]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CJRRData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CJRRData]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CCRSData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CCRSData]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CancerCare]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CancerCare]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CACS_Years]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CACS_Years]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_CACS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_CACS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_BatchGrouper2007P]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_BatchGrouper2007P]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_BatchGrouper]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_BatchGrouper]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[L_AbstractData]') AND type in (N'P', N'PC'))
DROP PROCEDURE [L_AbstractData]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_WM_WorkLoad]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_WM_WorkLoad]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_UpdateHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_UpdateHistory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_UpdateAudit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_UpdateAudit]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_U_Users_password]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_U_Users_password]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_U_Users]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_U_Users]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_U_UserFields]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_U_UserFields]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_U_Permission]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_U_Permission]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_Transcription]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_Transcription]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_SH_UpdateHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_SH_UpdateHistory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_SH_Appointments]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_SH_Appointments]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_ROI_UserDefined]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_ROI_UserDefined]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_ROI_UpdateHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_ROI_UpdateHistory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_ROI_UDFieldsTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_ROI_UDFieldsTime]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_ROI_UDFieldsText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_ROI_UDFieldsText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_ROI_UDFieldsSmallText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_ROI_UDFieldsSmallText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_ROI_UDFieldsLookUp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_ROI_UDFieldsLookUp]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_ROI_UDFieldsInteger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_ROI_UDFieldsInteger]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_ROI_UDFieldsDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_ROI_UDFieldsDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_ROI_SentItems]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_ROI_SentItems]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_ROI_RequesterInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_ROI_RequesterInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_ROI_Payments]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_ROI_Payments]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_ROI_Main]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_ROI_Main]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_ROI_Document]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_ROI_Document]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_ROI_Actions]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_ROI_Actions]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_UpdateHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_UpdateHistory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_UDFieldsTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_UDFieldsTime]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_UDFieldsText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_UDFieldsText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_UDFieldsSmallText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_UDFieldsSmallText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_UDFieldsLookUp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_UDFieldsLookUp]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_UDFieldsInteger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_UDFieldsInteger]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_UDFieldsDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_UDFieldsDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_UDAbstracting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_UDAbstracting]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_Therapy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_Therapy]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_ServiceInterupt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_ServiceInterupt]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_Rehabilitation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_Rehabilitation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_Provider]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_Provider]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_Project]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_Project]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_Intervention]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_Intervention]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_Health]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_Health]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_FollowUpAssess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_FollowUpAssess]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_Diagnosis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_Diagnosis]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_Demographic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_Demographic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_ClientInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_ClientInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_BasicOption]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_BasicOption]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_Ancillary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_Ancillary]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_Administrative]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_Administrative]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_RH_Activity]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_RH_Activity]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_REC_Purge]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_REC_Purge]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_REC_Notes_OMHRS_Reporting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_REC_Notes_OMHRS_Reporting]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_REC_Notes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_REC_Notes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_UserDefined]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_UserDefined]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_UDFieldsTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_UDFieldsTime]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_UDFieldsText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_UDFieldsText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_UDFieldsSmallText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_UDFieldsSmallText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_UDFieldsLookUp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_UDFieldsLookUp]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_UDFieldsInteger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_UDFieldsInteger]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_UDFieldsDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_UDFieldsDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_Serv_Interrupt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_Serv_Interrupt]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecR]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecR]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecQ]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecQ]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecP]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecP]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecO]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecO]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecN]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecN]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecM]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecM]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecL]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecK]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecK]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecJ]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecJ]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecH]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecH]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecG]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecG]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecF]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecF]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecE]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecDD]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecDD]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecD]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecD]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecCC]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecCC]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecC]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecC]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecBB]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecBB]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecB]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecB]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecAA]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecAA]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_SecA]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_SecA]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_RecInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_RecInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_Provider]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_Provider]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_Project]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_Project]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_MHAPS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_MHAPS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_Medication]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_Medication]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_Med_Diag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_Med_Diag]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_Intervention_CodeSmart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_Intervention_CodeSmart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_Intervention]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_Intervention]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_IAR_CCIM]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_IAR_CCIM]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_DSM_Diag_II]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_DSM_Diag_II]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_DSM_Diag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_DSM_Diag]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_DSM_5]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_DSM_5]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_Diagnosis_CodeSmart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_Diagnosis_CodeSmart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_BasicOption]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_BasicOption]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMHRS_Ancillary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMHRS_Ancillary]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_OMH_UpdateHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_OMH_UpdateHistory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_NU_LookUps]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_NU_LookUps]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_NU_IProfile]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_NU_IProfile]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_NU_Excludes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_NU_Excludes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_NU_DProfile]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_NU_DProfile]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_NU_CrossReference]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_NU_CrossReference]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_M_DBULogging]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_M_DBULogging]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_TR_DocumentType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_TR_DocumentType]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_ROI_SentItemTypes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_ROI_SentItemTypes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_ROI_RequestTypes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_ROI_RequestTypes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_ROI_Requesters]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_ROI_Requesters]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_ROI_Contacts]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_ROI_Contacts]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_ROI_AuthTypes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_ROI_AuthTypes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_ResidenceCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_ResidenceCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_RequestPriority]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_RequestPriority]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_Reports]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_Reports]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_Provider]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_Provider]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_Project]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_Project]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_PostalCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_PostalCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_PatientService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_PatientService]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_OR_GeneralLink]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_OR_GeneralLink]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_MISCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_MISCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_MDAS_Group]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_MDAS_Group]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_LoanLocationType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_LoanLocationType]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_Institution10]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_Institution10]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_ICD9Interv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_ICD9Interv]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_ICD9Diag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_ICD9Diag]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_ICD9CMInterv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_ICD9CMInterv]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_ICD9CMDiag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_ICD9CMDiag]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_ICD10Interv]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_ICD10Interv]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_ICD10DiagCCRS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_ICD10DiagCCRS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_ICD10Diag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_ICD10Diag]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_GeneralAssoc]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_GeneralAssoc]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_General_NoCIHI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_General_NoCIHI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_General]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_General]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_DirectBillFeeCodes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_DirectBillFeeCodes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_DeficiencyStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_DeficiencyStatus]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_DeficiencyCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_DeficiencyCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_ClinicalPathway]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_ClinicalPathway]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_CJRR_StickerCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_CJRR_StickerCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_ChartLocation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_ChartLocation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_CCM_NHPIP_Code]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_CCM_NHPIP_Code]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_CCM_BodyRegion]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_CCM_BodyRegion]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_CC_RT_PROTOCOL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_CC_RT_PROTOCOL]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_Borrower]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_Borrower]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_BasicOptions]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_BasicOptions]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_AutoRequester]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_AutoRequester]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LU_AutoBorrower]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LU_AutoBorrower]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LLU_ReportDistribution]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LLU_ReportDistribution]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LLU_ProviderSpecialty]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LLU_ProviderSpecialty]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LLU_ProviderServices]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LLU_ProviderServices]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LLU_ProviderPrivileges]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LLU_ProviderPrivileges]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LLU_Provider_Vacation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LLU_Provider_Vacation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LLU_Provider_UnAvailable]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LLU_Provider_UnAvailable]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LLU_Provider_Suspention]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LLU_Provider_Suspention]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LLU_Provider_Schedule]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LLU_Provider_Schedule]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_LLU_History]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_LLU_History]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_H_RegionProfile_Message]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_H_RegionProfile_Message]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_H_InstitutionProfile]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_H_InstitutionProfile]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_H_HospitalProfile_Message]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_H_HospitalProfile_Message]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_H_History]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_H_History]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_Deficiency_FromTran]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_Deficiency_FromTran]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_Def_UpdateHistory_FromCPI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_Def_UpdateHistory_FromCPI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_Def_UpdateHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_Def_UpdateHistory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_Def_Transfer_Undo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_Def_Transfer_Undo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_Def_Transfer]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_Def_Transfer]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_Def_SlipMain]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_Def_SlipMain]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_Def_Key]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_Def_Key]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_Def_BatchCompleteDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_Def_BatchCompleteDetail]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_Def_BatchComplete]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_Def_BatchComplete]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_Def_Activity]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_Def_Activity]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_UpdateRecord]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_UpdateRecord]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_UDFieldsTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_UDFieldsTime]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_UDFieldsText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_UDFieldsText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_UDFieldsSmallText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_UDFieldsSmallText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_UDFieldsLookUp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_UDFieldsLookUp]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_UDFieldsInteger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_UDFieldsInteger]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_UDFieldsDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_UDFieldsDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_UDAbstracting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_UDAbstracting]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_Signature]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_Signature]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_RAPS2]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_RAPS2]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_Project]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_Project]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_OutcomeScale]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_OutcomeScale]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_Medication]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_Medication]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_Hobic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_Hobic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_Diagnosis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_Diagnosis]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_Demographic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_Demographic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_CAPS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_CAPS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_BasicOption]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_BasicOption]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_AssessShare5]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_AssessShare5]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_AssessShare4]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_AssessShare4]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_AssessShare3]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_AssessShare3]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_AssessShare2]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_AssessShare2]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_AssessShare1]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_AssessShare1]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_AssessFull2]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_AssessFull2]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_AssessFull1]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_AssessFull1]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_Ancillary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_Ancillary]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CRS_Admission]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CRS_Admission]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CR_VitalSign]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CR_VitalSign]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CR_Visit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CR_Visit]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CR_UpdateHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CR_UpdateHistory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CR_Supply]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CR_Supply]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CR_ReconItem]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CR_ReconItem]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CR_ReconHeader]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CR_ReconHeader]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CR_ReconClaimHD]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CR_ReconClaimHD]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CR_ProviderService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CR_ProviderService]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CR_Prescription]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CR_Prescription]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CR_OBEC]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CR_OBEC]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CR_Intervention]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CR_Intervention]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CR_Immunization]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CR_Immunization]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CR_ErrorsHeader]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CR_ErrorsHeader]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CR_ErrorItem]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CR_ErrorItem]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CR_ErrorClaimHD]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CR_ErrorClaimHD]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CR_DirectBillingPayments]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CR_DirectBillingPayments]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CR_DirectBillingItems]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CR_DirectBillingItems]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CR_DirectBilling]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CR_DirectBilling]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CR_Diagnosis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CR_Diagnosis]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CR_Demographic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CR_Demographic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CR_BatchEncounter]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CR_BatchEncounter]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CMV_Variance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CMV_Variance]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CMV_UpdateHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CMV_UpdateHistory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CMV_ClinicalPathway]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CMV_ClinicalPathway]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CM_Volume_History]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CM_Volume_History]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CM_UserDefined]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CM_UserDefined]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CM_UDFieldsTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CM_UDFieldsTime]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CM_UDFieldsText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CM_UDFieldsText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CM_UDFieldsSmallText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CM_UDFieldsSmallText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CM_UDFieldsLookUp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CM_UDFieldsLookUp]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CM_UDFieldsInteger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CM_UDFieldsInteger]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CM_UDFieldsDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CM_UDFieldsDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CM_RiskFactors]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CM_RiskFactors]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CM_LabHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CM_LabHistory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CM_History]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CM_History]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CM_Files]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CM_Files]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CM_FamilyHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CM_FamilyHistory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CM_CPI_Volume]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CM_CPI_Volume]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CM_CPI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CM_CPI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CM_ChartLink]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CM_ChartLink]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CM_BabyChart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CM_BabyChart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CM_Alias]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CM_Alias]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CM_Alert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CM_Alert]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CM_Address]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CM_Address]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CL_UpdateHistory_FromCPI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CL_UpdateHistory_FromCPI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CL_UpdateHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CL_UpdateHistory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CL_PullListUpdateHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CL_PullListUpdateHistory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CL_PullList_FromPurged]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CL_PullList_FromPurged]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CL_PullList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CL_PullList]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CL_Activity]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CL_Activity]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CJRR_UpdateHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CJRR_UpdateHistory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CJRR_UDFieldsTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CJRR_UDFieldsTime]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CJRR_UDFieldsText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CJRR_UDFieldsText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CJRR_UDFieldsSmallText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CJRR_UDFieldsSmallText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CJRR_UDFieldsLookUp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CJRR_UDFieldsLookUp]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CJRR_UDFieldsInteger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CJRR_UDFieldsInteger]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CJRR_UDFieldsDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CJRR_UDFieldsDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CJRR_TibialInsert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CJRR_TibialInsert]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CJRR_TibialComponent]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CJRR_TibialComponent]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CJRR_PatellarComponent]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CJRR_PatellarComponent]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CJRR_FemoralHead]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CJRR_FemoralHead]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CJRR_FemoralComponent]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CJRR_FemoralComponent]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CJRR_Cement]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CJRR_Cement]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CJRR_AcetabularInsert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CJRR_AcetabularInsert]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CJRR_AcetabularComponent]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CJRR_AcetabularComponent]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CJRR_Abstract]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CJRR_Abstract]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_ChartLoanToRequest]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_ChartLoanToRequest]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CCRS_UpdateHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CCRS_UpdateHistory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CC_UserDefined]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CC_UserDefined]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CC_UpdateHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CC_UpdateHistory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CC_UDFieldsTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CC_UDFieldsTime]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CC_UDFieldsText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CC_UDFieldsText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CC_UDFieldsSmallText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CC_UDFieldsSmallText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CC_UDFieldsLookUp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CC_UDFieldsLookUp]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CC_UDFieldsInteger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CC_UDFieldsInteger]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CC_UDFieldsDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CC_UDFieldsDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CC_ReferralDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CC_ReferralDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CC_RecordInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CC_RecordInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CC_NDFP]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CC_NDFP]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CC_HealthCareProf]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CC_HealthCareProf]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CC_DiseaseRegister]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CC_DiseaseRegister]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CC_DischargeInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CC_DischargeInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CC_Demographic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CC_Demographic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CC_CollaborateStageDiag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CC_CollaborateStageDiag]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_CC_CancerStageDiag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_CC_CancerStageDiag]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_UDFieldsTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_UDFieldsTime]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_UDFieldsText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_UDFieldsText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_UDFieldsSmallText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_UDFieldsSmallText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_UDFieldsLookUp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_UDFieldsLookUp]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_UDFieldsInteger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_UDFieldsInteger]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_UDFieldsDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_UDFieldsDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_UDAbstracting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_UDAbstracting]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_TransferService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_TransferService]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_Therapeutic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_Therapeutic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_SpecialProjects]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_SpecialProjects]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_SpecialProject]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_SpecialProject]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_SpecialCareUnit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_SpecialCareUnit]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_ReproductiveCare]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_ReproductiveCare]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_QBP_Flag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_QBP_Flag]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_Provider]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_Provider]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_Project]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_Project]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_PresentingComplaints]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_PresentingComplaints]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_PatientService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_PatientService]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_NACRS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_NACRS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_MIS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_MIS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_MentalHealth]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_MentalHealth]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_MB_NonALC]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_MB_NonALC]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_MB_FacilityStudy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_MB_FacilityStudy]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_MB_ALC]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_MB_ALC]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_Manitoba]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_Manitoba]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_MainHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_MainHistory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_Main]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_Main]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_InvestigativeTechnology]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_InvestigativeTechnology]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_Intervention_Replicate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_Intervention_Replicate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_Intervention_CodeSmart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_Intervention_CodeSmart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_Intervention]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_Intervention]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_History]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_History]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_EDInterventionValueSet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_EDInterventionValueSet]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_EDInterventionPicklist]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_EDInterventionPicklist]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_DPG]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_DPG]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_DischargeDiagnosis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_DischargeDiagnosis]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_Diagnosis_CodeSmart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_Diagnosis_CodeSmart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_Diagnosis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_Diagnosis]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_DeathInformation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_DeathInformation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_Consult]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_Consult]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_CMG2007P]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_CMG2007P]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_CMG]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_CMG]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_CCM_SystemicDrug]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_CCM_SystemicDrug]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_CCM_Radiation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_CCM_Radiation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_CCM_CancerCareInformation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_CCM_CancerCareInformation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_CancerStaging]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_CancerStaging]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_CACS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_CACS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_Blood]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_Blood]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_BasicOption]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_BasicOption]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_Ancillary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_Ancillary]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[I_AB_Abstract]') AND type in (N'P', N'PC'))
DROP PROCEDURE [I_AB_Abstract]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[GetPass]') AND type in (N'P', N'PC'))
DROP PROCEDURE [GetPass]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[GetLookUpUpdateHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [GetLookUpUpdateHistory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchVisit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchVisit]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchUserCtrl]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchUserCtrl]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchUser]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchUser]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchTransEdit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchTransEdit]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchTransAdd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchTransAdd]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchSchedule]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchSchedule]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchROI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchROI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchRehab_Chart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchRehab_Chart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchPullList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchPullList]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchPull_List]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchPull_List]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchProvider_ForDefTransfer]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchProvider_ForDefTransfer]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchProvider]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchProvider]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchProfileVisits_OMHRS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchProfileVisits_OMHRS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchProfileVisits]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchProfileVisits]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchOMHRS_Chart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchOMHRS_Chart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchLocator_Chart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchLocator_Chart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchLocator_ByVolumeID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchLocator_ByVolumeID]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchLocator_BarCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchLocator_BarCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchInstitution]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchInstitution]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchHospital]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchHospital]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchDeficiencyBySearch]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchDeficiencyBySearch]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchDeficiencyByProvider]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchDeficiencyByProvider]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchDeficiency_Volume]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchDeficiency_Volume]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchDeficiency_VH]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchDeficiency_VH]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchDeficiency_List]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchDeficiency_List]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchDeficiency_Chart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchDeficiency_Chart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchDeficiency_Abstract]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchDeficiency_Abstract]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchCloneVisits_OMHRS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchCloneVisits_OMHRS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchCloneVisits]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchCloneVisits]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchClinic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchClinic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchCJRR_Chart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchCJRR_Chart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchChart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchChart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchCCRS_Chart_OLD]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchCCRS_Chart_OLD]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchCCRS_Chart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchCCRS_Chart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchCC_Chart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchCC_Chart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchCareMap]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchCareMap]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchAbstract2]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchAbstract2]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchAbstract_Chart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchAbstract_Chart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_SearchAbstract]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_SearchAbstract]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_QuickSearch]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_QuickSearch]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_GetDictationDeficiencyCode]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_GetDictationDeficiencyCode]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_Fetch_HIM_Location]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_Fetch_HIM_Location]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[F_BarcodeChart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [F_BarcodeChart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[E_Transcription]') AND type in (N'P', N'PC'))
DROP PROCEDURE [E_Transcription]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[E_ROI_Main]') AND type in (N'P', N'PC'))
DROP PROCEDURE [E_ROI_Main]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[E_RH_ClientInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [E_RH_ClientInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[E_OMHRS_SecAA]') AND type in (N'P', N'PC'))
DROP PROCEDURE [E_OMHRS_SecAA]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[E_CRS_Demographic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [E_CRS_Demographic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[E_CR_Demographic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [E_CR_Demographic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[E_CM_CPI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [E_CM_CPI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[E_CJRR_Abstract]') AND type in (N'P', N'PC'))
DROP PROCEDURE [E_CJRR_Abstract]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[E_CC_RecordInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [E_CC_RecordInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[E_AB_Main]') AND type in (N'P', N'PC'))
DROP PROCEDURE [E_AB_Main]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[E_AB_Abstract]') AND type in (N'P', N'PC'))
DROP PROCEDURE [E_AB_Abstract]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[DSS_Upload_Terminate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [DSS_Upload_Terminate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[DSS_Upload_Steps]') AND type in (N'P', N'PC'))
DROP PROCEDURE [DSS_Upload_Steps]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[DSS_UpLoad_Purge_Abstract]') AND type in (N'P', N'PC'))
DROP PROCEDURE [DSS_UpLoad_Purge_Abstract]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[DSS_Upload_Initialize]') AND type in (N'P', N'PC'))
DROP PROCEDURE [DSS_Upload_Initialize]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[DSS_Upload_Init_Abstract]') AND type in (N'P', N'PC'))
DROP PROCEDURE [DSS_Upload_Init_Abstract]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[DSS_Upload_GetRecords]') AND type in (N'P', N'PC'))
DROP PROCEDURE [DSS_Upload_GetRecords]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[DSS_I_Import_Category]') AND type in (N'P', N'PC'))
DROP PROCEDURE [DSS_I_Import_Category]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[DSS_Drop_LinkServer]') AND type in (N'P', N'PC'))
DROP PROCEDURE [DSS_Drop_LinkServer]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[DSS_Create_LinkServer]') AND type in (N'P', N'PC'))
DROP PROCEDURE [DSS_Create_LinkServer]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_U_Permission]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_U_Permission]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_Transcription]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_Transcription]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_SH_Appointments]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_SH_Appointments]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_ROI_UserDefined]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_ROI_UserDefined]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_ROI_UDFieldsTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_ROI_UDFieldsTime]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_ROI_UDFieldsText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_ROI_UDFieldsText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_ROI_UDFieldsSmallText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_ROI_UDFieldsSmallText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_ROI_UDFieldsLookUp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_ROI_UDFieldsLookUp]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_ROI_UDFieldsInteger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_ROI_UDFieldsInteger]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_ROI_UDFieldsDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_ROI_UDFieldsDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_ROI_SentItems]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_ROI_SentItems]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_ROI_RequesterInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_ROI_RequesterInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_ROI_Payments]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_ROI_Payments]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_ROI_Main]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_ROI_Main]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_ROI_Document]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_ROI_Document]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_ROI_Actions]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_ROI_Actions]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_UDFieldsTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_UDFieldsTime]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_UDFieldsText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_UDFieldsText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_UDFieldsSmallText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_UDFieldsSmallText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_UDFieldsLookUp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_UDFieldsLookUp]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_UDFieldsInteger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_UDFieldsInteger]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_UDFieldsDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_UDFieldsDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_UDAbstracting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_UDAbstracting]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_Therapy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_Therapy]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_ServiceInterupt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_ServiceInterupt]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_Rehabilitation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_Rehabilitation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_Provider]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_Provider]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_Project]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_Project]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_Intervention]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_Intervention]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_Health]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_Health]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_FollowUpAssess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_FollowUpAssess]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_Diagnosis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_Diagnosis]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_Demographic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_Demographic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_ClientInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_ClientInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_BasicOption]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_BasicOption]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_Ancillary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_Ancillary]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_Administrative]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_Administrative]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_RH_Activity]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_RH_Activity]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_REC_Notes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_REC_Notes]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_PullList_Purged]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_PullList_Purged]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_PullList_Purge]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_PullList_Purge]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_PullList_Item]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_PullList_Item]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_UserDefined]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_UserDefined]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_UDFieldsTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_UDFieldsTime]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_UDFieldsText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_UDFieldsText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_UDFieldsSmallText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_UDFieldsSmallText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_UDFieldsLookUp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_UDFieldsLookUp]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_UDFieldsInteger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_UDFieldsInteger]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_UDFieldsDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_UDFieldsDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_Serv_Interrupt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_Serv_Interrupt]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecR]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecR]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecQ]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecQ]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecP]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecP]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecO]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecO]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecN]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecN]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecM]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecM]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecL]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecK]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecK]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecJ]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecJ]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecH]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecH]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecG]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecG]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecF]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecF]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecE]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecDD]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecDD]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecD]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecD]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecCC]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecCC]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecC]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecC]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecBB]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecBB]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecB]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecB]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecAA]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecAA]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_SecA]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_SecA]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_RecInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_RecInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_Provider]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_Provider]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_Project]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_Project]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_MHAPS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_MHAPS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_Medication]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_Medication]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_Med_Diag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_Med_Diag]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_Intervention_CodeSmart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_Intervention_CodeSmart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_Intervention]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_Intervention]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_IAR_CCIM]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_IAR_CCIM]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_DSM_Diag_II]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_DSM_Diag_II]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_DSM_Diag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_DSM_Diag]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_DSM_5]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_DSM_5]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_DischargeDiagnosis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_DischargeDiagnosis]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_Diagnosis_CodeSmart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_Diagnosis_CodeSmart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_BasicOption]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_BasicOption]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_OMHRS_Ancillary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_OMHRS_Ancillary]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_NU_Profile]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_NU_Profile]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_MultiCMG]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_MultiCMG]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_LU_ROIRequesterContacts]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_LU_ROIRequesterContacts]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_LU_ProviderSpecialty]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_LU_ProviderSpecialty]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_LU_ProviderServices]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_LU_ProviderServices]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_LU_ProjectQuestions]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_LU_ProjectQuestions]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_LU_InstitutionBOPs]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_LU_InstitutionBOPs]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_LLU_ReportDistribution]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_LLU_ReportDistribution]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_LLU_ProviderSpecialty]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_LLU_ProviderSpecialty]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_LLU_ProviderServices]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_LLU_ProviderServices]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_LLU_ProviderPrivileges]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_LLU_ProviderPrivileges]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_LLU_Provider_Vacation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_LLU_Provider_Vacation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_LLU_Provider_UnAvailable]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_LLU_Provider_UnAvailable]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_LLU_Provider_Suspention]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_LLU_Provider_Suspention]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_LLU_Provider_Schedule]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_LLU_Provider_Schedule]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_H_RegionProfile_Message]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_H_RegionProfile_Message]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_H_HospitalProfile_Message]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_H_HospitalProfile_Message]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_DEF_Main]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_DEF_Main]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_Def_Activity]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_Def_Activity]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_Def_Activities]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_Def_Activities]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_UpdateRecord]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_UpdateRecord]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_UDFieldsTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_UDFieldsTime]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_UDFieldsText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_UDFieldsText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_UDFieldsSmallText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_UDFieldsSmallText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_UDFieldsLookUp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_UDFieldsLookUp]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_UDFieldsInteger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_UDFieldsInteger]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_UDFieldsDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_UDFieldsDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_UDAbstracting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_UDAbstracting]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_Signature]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_Signature]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_RAPS2]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_RAPS2]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_Project]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_Project]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_OutcomeScale]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_OutcomeScale]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_Medication]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_Medication]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_Hobic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_Hobic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_Diagnosis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_Diagnosis]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_Demographic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_Demographic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_CAPS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_CAPS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_BasicOption]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_BasicOption]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_AssessShare5]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_AssessShare5]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_AssessShare4]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_AssessShare4]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_AssessShare3]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_AssessShare3]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_AssessShare2]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_AssessShare2]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_AssessShare1]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_AssessShare1]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_AssessFull2]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_AssessFull2]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_AssessFull1]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_AssessFull1]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_Ancillary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_Ancillary]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CRS_Admission]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CRS_Admission]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CR_VitalSign]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CR_VitalSign]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CR_Visit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CR_Visit]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CR_Supply]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CR_Supply]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CR_ProviderService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CR_ProviderService]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CR_Prescription]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CR_Prescription]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CR_Intervention]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CR_Intervention]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CR_Immunization]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CR_Immunization]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CR_DirectBillingPayments]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CR_DirectBillingPayments]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CR_DirectBillingItems]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CR_DirectBillingItems]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CR_DirectBilling]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CR_DirectBilling]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CR_Diagnosis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CR_Diagnosis]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CR_Demographic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CR_Demographic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CMV_Variance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CMV_Variance]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CMV_ClinicalPathway]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CMV_ClinicalPathway]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CM_UserDefined]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CM_UserDefined]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CM_UDFieldsTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CM_UDFieldsTime]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CM_UDFieldsText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CM_UDFieldsText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CM_UDFieldsSmallText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CM_UDFieldsSmallText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CM_UDFieldsLookUp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CM_UDFieldsLookUp]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CM_UDFieldsInteger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CM_UDFieldsInteger]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CM_UDFieldsDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CM_UDFieldsDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CM_RiskFactors]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CM_RiskFactors]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CM_LabHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CM_LabHistory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CM_Files]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CM_Files]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CM_FamilyHistory]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CM_FamilyHistory]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CM_CPI_Volume]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CM_CPI_Volume]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CM_CPI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CM_CPI]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CM_ChartLink]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CM_ChartLink]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CM_BabyChart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CM_BabyChart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CM_Alias]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CM_Alias]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CM_Alert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CM_Alert]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CM_Address]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CM_Address]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CL_Activity]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CL_Activity]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CL_Activities_Chart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CL_Activities_Chart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CL_Activities]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CL_Activities]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CJRR_UDFieldsTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CJRR_UDFieldsTime]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CJRR_UDFieldsText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CJRR_UDFieldsText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CJRR_UDFieldsSmallText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CJRR_UDFieldsSmallText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CJRR_UDFieldsLookUp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CJRR_UDFieldsLookUp]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CJRR_UDFieldsInteger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CJRR_UDFieldsInteger]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CJRR_UDFieldsDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CJRR_UDFieldsDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CJRR_TibialInsert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CJRR_TibialInsert]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CJRR_TibialComponent]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CJRR_TibialComponent]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CJRR_PatellarComponent]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CJRR_PatellarComponent]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CJRR_FemoralHead]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CJRR_FemoralHead]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CJRR_FemoralComponent]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CJRR_FemoralComponent]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CJRR_Cement]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CJRR_Cement]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CJRR_AcetabularInsert]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CJRR_AcetabularInsert]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CJRR_AcetabularComponent]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CJRR_AcetabularComponent]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CJRR_Abstract]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CJRR_Abstract]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CC_UserDefined]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CC_UserDefined]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CC_UDFieldsTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CC_UDFieldsTime]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CC_UDFieldsText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CC_UDFieldsText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CC_UDFieldsSmallText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CC_UDFieldsSmallText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CC_UDFieldsLookUp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CC_UDFieldsLookUp]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CC_UDFieldsInteger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CC_UDFieldsInteger]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CC_UDFieldsDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CC_UDFieldsDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CC_ReferralDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CC_ReferralDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CC_RecordInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CC_RecordInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CC_NDFP]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CC_NDFP]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CC_Information]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CC_Information]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CC_HealthCareProf]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CC_HealthCareProf]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CC_DiseaseRegister]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CC_DiseaseRegister]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CC_DischargeInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CC_DischargeInfo]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CC_Demographic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CC_Demographic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CC_CollaborateStageDiag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CC_CollaborateStageDiag]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_CC_CancerStageDiag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_CC_CancerStageDiag]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_UDFieldsTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_UDFieldsTime]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_UDFieldsText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_UDFieldsText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_UDFieldsSmallText]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_UDFieldsSmallText]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_UDFieldsLookUp]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_UDFieldsLookUp]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_UDFieldsInteger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_UDFieldsInteger]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_UDFieldsDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_UDFieldsDate]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_UDAbstracting]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_UDAbstracting]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_TransferService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_TransferService]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_Therapeutic]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_Therapeutic]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_SurgicalProcedure]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_SurgicalProcedure]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_SpecialProjects]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_SpecialProjects]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_SpecialProject]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_SpecialProject]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_SpecialCareUnit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_SpecialCareUnit]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_ReproductiveCare]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_ReproductiveCare]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_QBP_Flag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_QBP_Flag]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_Provider]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_Provider]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_Project]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_Project]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_PresentingComplaints]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_PresentingComplaints]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_PatientService]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_PatientService]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_NACRS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_NACRS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_MIS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_MIS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_MentalHealth]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_MentalHealth]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_MB_NonALC]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_MB_NonALC]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_MB_FacilityStudy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_MB_FacilityStudy]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_MB_ALC]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_MB_ALC]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_Manitoba]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_Manitoba]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_Main]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_Main]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_InvestigativeTechnology]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_InvestigativeTechnology]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_Intervention_CodeSmart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_Intervention_CodeSmart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_Intervention]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_Intervention]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_EDInterventionValueSet]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_EDInterventionValueSet]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_EDInterventionPicklist]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_EDInterventionPicklist]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_DPG_Single]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_DPG_Single]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_DPG]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_DPG]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_DischargeDiagnosis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_DischargeDiagnosis]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_Diagnosis_CodeSmart]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_Diagnosis_CodeSmart]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_Diagnosis]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_Diagnosis]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_DeathInformation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_DeathInformation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_Consult]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_Consult]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_CMG_Single]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_CMG_Single]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_CMG]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_CMG]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_CCM_SystemicDrug]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_CCM_SystemicDrug]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_CCM_Radiation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_CCM_Radiation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_CCM_CancerCareInformation]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_CCM_CancerCareInformation]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_CancerStaging]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_CancerStaging]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_CACS_Single]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_CACS_Single]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_CACS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_CACS]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_Blood]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_Blood]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_BasicOption]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_BasicOption]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_Ancillary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_Ancillary]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_Abstract]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_Abstract]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[D_AB_AB_QBP_Flag]') AND type in (N'P', N'PC'))
DROP PROCEDURE [D_AB_AB_QBP_Flag]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[CS_Security]') AND type in (N'P', N'PC'))
DROP PROCEDURE [CS_Security]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[cmdIPCDiagFile10Select]') AND type in (N'P', N'PC'))
DROP PROCEDURE [cmdIPCDiagFile10Select]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[cmdDiagFile10Select]') AND type in (N'P', N'PC'))
DROP PROCEDURE [cmdDiagFile10Select]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[CACS_Grouping_2007]') AND type in (N'P', N'PC'))
DROP PROCEDURE [CACS_Grouping_2007]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[CACS_Grouping_2006]') AND type in (N'P', N'PC'))
DROP PROCEDURE [CACS_Grouping_2006]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[CACS_Grouping_2005]') AND type in (N'P', N'PC'))
DROP PROCEDURE [CACS_Grouping_2005]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[CACS_Grouping_2004]') AND type in (N'P', N'PC'))
DROP PROCEDURE [CACS_Grouping_2004]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[CACS_Grouping_2003]') AND type in (N'P', N'PC'))
DROP PROCEDURE [CACS_Grouping_2003]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[CACS_Grouping_2002]') AND type in (N'P', N'PC'))
DROP PROCEDURE [CACS_Grouping_2002]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[CACS_Grouping]') AND type in (N'P', N'PC'))
DROP PROCEDURE [CACS_Grouping]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[C_DefCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [C_DefCount]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE  PROCEDURE [C_DefCount]
	@DefSlipID as int = 0
AS
Declare @DefId as int
Declare @DefDrN as int
Declare @DrStatus as VarChar(10)
Declare @DefHSDate as datetime
Declare @DefHEDate as datetime
Declare @DefSDate as datetime
declare @DefEndDate as datetime
Declare @VacSDate as datetime
Declare @VacEDate as datetime
Declare @SuspSDate as datetime
Declare @SuspEDate as datetime
Declare @DefVDays as int
Declare @DefSDays as int
Declare @DefMDays as int
Declare @DefDays as int
Declare @DefHoldDays as int
Declare @VolumeID as int
Declare @InCodingArea as varchar(12)
Declare @Now as datetime
Declare @DateFrom1 as Datetime
Declare @DateTo1   as Datetime
Declare @DateFrom2 as Datetime
Declare @DateTo2   as Datetime
Declare @DateFrom3 as Datetime
Declare @DateTo3   as Datetime
Declare @IncludeDays as int
Declare @IsSuspend as int
Declare @IsCountDay as varchar(12)
--PR - 01663
Declare @HasLocator as int
Declare @HospitalID as int
Declare @i          as int
--EN - 00333
declare @DefTotalDays as int

--Ticket 12456 reset deficiency header status
Declare @Level_1 int, @Level_2 int, @Level_3 int, @Level_4 int, @Level_5 int

SET NOCOUNT ON 

set @Level_1 = isnull((select top 1 NumberDays from dbo.DefLU_ChartStatus where displaycode = '1'), 0)
set @Level_2 = isnull((select top 1 NumberDays from dbo.DefLU_ChartStatus where displaycode = '2'), 0)
set @Level_3 = isnull((select top 1 NumberDays from dbo.DefLU_ChartStatus where displaycode = '3'), 0)
set @Level_4 = isnull((select top 1 NumberDays from dbo.DefLU_ChartStatus where displaycode = '4'), 0)
set @Level_5 = isnull((select top 1 NumberDays from dbo.DefLU_ChartStatus where displaycode = '5'), 0)

--PR - 01663
set @HospitalID = 0
if @DefSlipID > 0 
    set @HospitalID = isnull((select top 1 HospitalID from Def_SlipMain where DefID = @DefSlipID), 0)

set @HasLocator = 1
if isnull(@HospitalID, 0) > 0 
begin
    set @i = ascii(substring((select top 1 CDKEY from H_HospitalProfile where code = @HospitalID), 6, 1))
    set @HasLocator = @i % 3
    if @HasLocator > 0 set @HasLocator = @i % 2
end
else
begin
    declare cur_hosp cursor for
        select ascii(substring(CDKEY, 6, 1)) from H_HospitalProfile
    open cur_hosp
    fetch next from cur_hosp into @i
    while(@@fetch_status = 0)
    begin
        set @HasLocator = @i % 3
        if @HasLocator > 0 set @HasLocator = @i % 2
        if @HasLocator = 0 break
        fetch next from cur_hosp into @i
    end
    close cur_hosp
    deallocate cur_hosp
end
if @HasLocator is null set @HasLocator = 1
-- end PR - 01663

if (@Level_2 > 0 and @Level_1 >= @Level_2) or @Level_1 = 0
begin
    set @Level_2 = 0
    set @Level_3 = 0
    set @Level_4 = 0
    set @Level_5 = 0
end
if (@Level_3 > 0 and @Level_2 >= @Level_3) or @Level_2 = 0
begin
    set @Level_3 = 0
    set @Level_4 = 0
    set @Level_5 = 0
end
if (@Level_4 > 0 and @Level_3 >= @Level_4) or @Level_3 = 0
begin
    set @Level_4 = 0
    set @Level_5 = 0
end
if (@Level_5 > 0 and @Level_4 >= @Level_5) or @Level_4 = 0 
begin
    set @Level_5 = 0
end

set @Now = cast(convert(varchar(20), getdate(), 111) as datetime)
Set @DefDays = 0

Declare @TempTable table(
    DateFrom  datetime, 
    DateTo    datetime, 
    CrossDays int)

Declare @HoldTable table(
    Code     int identity(1,1),
    HoldFrom datetime,
    HoldTo   datetime
) 
--PR-01663
Declare @InterTable table(
    Code     int identity(1,1),
    DateFrom datetime,
    DateTo   datetime
) 


-- If @DefSlipID = 0
-- Begin
-- PR-00245 
Declare Cur_DefCount cursor fast_forward for
--EN-00183
select
    DefID = isnull(Y.DefID, N.DefID),
--    DefeciencyID = isnull(Y.DefeciencyID, N.DefeciencyID),
    DefDrNumber  = isnull(Y.DefDrNumber, N.DefDrNumber),
    DefHoldStartDate = isnull(Y.DefHoldStartDate, N.DefHoldStartDate),
    DefHoldEndDate = isnull(Y.DefHoldEndDate, N.DefHoldEndDate), 
    DefStartDate   = isnull(Y.DefStartDate, N.DefStartDate),
    DefEndDate   = isnull(Y.DefEndDate, N.DefEndDate),
    DefHoldDays = isnull(Y.DefHoldDays, N.DefHoldDays), 
    DefManualDays = isnull(Y.DefManualDays, N.DefManualDays),
    VolumeID      = isnull(Y.VolumeID, N.VolumeID),
    IsCountDays   = isnull(Y.IsCountDays, N.IsCountDays)
from 
(SELECT distinct 
    S.DefID,    --S.DefeciencyID, 
    S.DefDrNumber, 
    isnull(S.DefHoldStartDate, getdate()) + 1 as DefHoldStartDate,
    isnull(S.DefHoldEndDate,   getdate()) + 1 as DefHoldEndDate, 
    S.DefStartDate, 
    s.DefEndDate,
    isnull(S.DefHoldDays, 0) as DefHoldDays, 
    isnull(S.DefManualDays, 0) as DefManualDays,
    isnull(S.DefVolumeID, 0) as VolumeID,
    isnull(YN.CIHIValue, '0') as IsCountDays
FROM dbo.Def_SlipMain S 
    inner join Def_Activity a on s.DefID = a.DefID
    inner join DefLU_DeficiencyCode D on a.DefCode = D.Code
    inner join LU_YesNoSystem YN on D.DefCountDays = YN.Code
WHERE ((isnull(S.DefMainStatus, 0) not in (8, 11)  --<> 8 PR - 02842
    and isnull(a.DefStatus, 0) not in (8, 11)  --<> 8 PR - 02842
    and @DefSlipID = 0) or s.DefID = @DefSlipID)    
--    and (@DefSlipID = 0 or s.DefeciencyID = @DefSlipID)
    and YN.CIHIValue = '1') Y
full join 
(SELECT distinct 
    S.DefID,    --S.DefeciencyID, 
    S.DefDrNumber, 
    isnull(S.DefHoldStartDate, getdate()) + 1 as DefHoldStartDate,
    isnull(S.DefHoldEndDate,   getdate()) + 1 as DefHoldEndDate, 
    S.DefStartDate, 
    s.DefEndDate,
    isnull(S.DefHoldDays, 0) as DefHoldDays, 
    isnull(S.DefManualDays, 0) as DefManualDays,
    isnull(S.DefVolumeID, 0) as VolumeID,
    isnull(YN.CIHIValue, '0') as IsCountDays
FROM dbo.Def_SlipMain S 
    inner join Def_Activity a on s.DefID = a.DefID
    inner join DefLU_DeficiencyCode D on a.DefCode = D.Code
    left join LU_YesNoSystem YN on D.DefCountDays = YN.Code
WHERE ((isnull(S.DefMainStatus, 0) not in (8, 11)  --<> 8 PR - 02842
    and isnull(a.DefStatus, 0) not in (8, 11)  --<> 8 PR - 02842
    and @DefSlipID = 0) or s.DefID = @DefSlipID)    
--    and (@DefSlipID = 0 or s.DefeciencyID = @DefSlipID)
    and isnull(YN.CIHIValue, '0') <> '1') N
    on Y.DefID = N.DefID    --Y.DefeciencyID = N.DefeciencyID 


-- End
-- Else
-- Begin
-- 	Declare Cur_DefCount cursor fast_forward for
-- 	SELECT DefeciencyID, DefDrNumber, DefEndDate, DefStartDate, isnull(DefHoldDays, 0) as DefHoldDays, 
-- 	isnull(DefManualDays, 0) as DefManualDays FROM dbo.Def_SlipMain WHERE (DefeciencyID = @DefSlipID)
-- End
Open Cur_DefCount

fetch next from Cur_DefCount
into @DefId, @DefDrN, @DefHSDate, @DefHEDate, @DefSDate, @DefEndDate, @DefHoldDays, @DefMDays, @VolumeID, @IsCountDay

While @@Fetch_Status = 0
Begin
    Set @DefHSDate = IsNull(@DefHSDate, @Now)
    set @DefEndDate = isnull(@DefEndDate, @Now)

    if exists (select * from dbo.LLU_Provider_Suspention
        	Where ProviderID = @DefDrN and( @DefEndDate between DateFrom and DateTo or @DefSDate between datefrom and dateto))
        set @IsSuspend = 1
    else
        set @IsSuspend = 0

    delete from @HoldTable
    delete from @TempTable 
    delete from @InterTable

    if isnull(@VolumeID, 0) = 0 --PR-01663
    begin
        if isnull(@HasLocator, 0) = 0 and isnull(@DefHoldDays, 0) > 0 
            set @DefHoldDays = 0 
--         else
--         begin
--     	--Calculate UnAvailable Days
--                 
--             Set @DefVDays = isnull(
--             (select sum(dbo.CalculateExcludeDays(@DefSDate, DateFrom, DateTo, @DefHSDate, @DefHEDate, @DefEndDate))
--              from LLU_Provider_UnAvailable 
--     
--              Where ProviderID = @DefDrN and DateTo > @DefSDate), 0)
--     
--     	--Calculate Suspension Days
--             Set @DefSDays = isnull(
--             (select sum(dbo.CalculateExcludeDays(@DefSDate, DateFrom, DateTo, @DefHSDate, @DefHEDate, @DefEndDate))
--             FROM dbo.LLU_Provider_Suspention
--         	Where ProviderID = @DefDrN and DateTo > @DefSDate), 0)
--             Set @DefHSDate = null
--             Set @DefHEDate = null
--         end
	End
    else
    begin
	--Calculate Holding Days 
        insert @HoldTable(HoldFrom, HoldTo)
        select distinct ActivityDateOut, 
            isnull(ActivityDateIn, @DefEndDate) as ActivityDateIn
        from CL_Activity a 
            inner join LoanLu_Location l on a.ActivityLocation = l.code
            left join LU_YesNoSystem YN on l.InHospital = YN.code     
        where VolumeID = @VolumeID and ActivityType = 1    -- PR - 01663 ActivityType <> 4  Only calculate Loan transaction
            and isnull(YN.CIHIValue, '0') <> '1' 
            and (isnull(ActivityDateIn, getdate()) between  @DefSDate and @DefEndDate
                or isnull(ActivityDateOut, getdate()) between  @DefSDate and @DefEndDate)
            and a.ActivityType = 1
        order by ActivityDateOut, isnull(ActivityDateIn, @DefEndDate)

        if @@rowcount > 1
        begin
            update @HoldTable
            set HoldFrom = dateadd(day, 1, V.HoldTo) --dateadd(day, 1, H.HoldFrom)
            from @HoldTable H
                inner join (select * from @HoldTable) V on H.Code - 1 = V.Code 
            where V.HoldTo >= H.HoldFrom

            delete from @HoldTable where HoldFrom > HoldTo
        end

    --This is to calculate the loan out days
        select @DefHoldDays = sum((case when HoldFrom > @DefSDate 
                              then datediff(day, HoldFrom, HoldTo) 
                              else datediff(day, @DefSDate, HoldTo)
                              end) + (case when HoldTo < @DefEndDate then 1 else 0 end))
--                @DefHSDate = min(HoldFrom),
--                @DefHEDate = max(isnull(HoldTo, @Now))
             from @HoldTable
        if @DefHoldDays is null set @DefHoldDays = 0
    end
    --Calculate Suspension Days
    insert into @InterTable(DateFrom, DateTo)
    select DateFrom, DateTo
    FROM dbo.LLU_Provider_Suspention
    where ProviderID = @DefDrN and (DateTo between @DefSDate and @DefEndDate or DateFrom between @DefSDate and @DefEndDate) 
    order by DateFrom, DateTo

    if @@rowcount > 1
    begin
        update @InterTable
        set DateFrom = dateadd(day, 1, H.DateFrom)
        from @InterTable H
            inner join (select * from @InterTable) V on H.Code - 1 = V.Code 
        where V.DateTo >= H.DateFrom

        delete from @InterTable where DateFrom > DateTo

        insert @TempTable(DateFrom, DateTo, CrossDays)
        select v.DateFrom, v.DateTo, 
            sum((case when act.HoldFrom is null 
                      then 0 
                      else dbo.CalculateCrossDays(@DefSDate, v.DateFrom, v.DateTo, act.HoldFrom, act.HoldTo, @DefEndDate)
                      end)) as CrossDays
        FROM @InterTable v
            left join @HoldTable act 
                on dbo.IsDateCross(v.DateFrom, v.DateTo, act.HoldFrom, act.HoldTo) = 1
        group by v.DateFrom, v.DateTo
    
        Set @DefSDays = isnull(
        (select sum(dbo.CalculateTotalDays(@DefSDate, DateFrom, DateTo, @DefEndDate) - isnull(CrossDays, 0))
        from @TempTable), 0)
    
        if @DefSDays < 0 set @DefSDays = 0
        delete from @TempTable   	
        --Merge together 
        if @DefSDays > 0
        begin
            insert into @InterTable(DateFrom, DateTo) select HoldFrom, HoldTo from @HoldTable 
            delete from @HoldTable
            insert into @HoldTable(HoldFrom, HoldTo) select DateFrom, DateTo from @InterTable order by DateFrom, DateTo
            set @i = 1
            while(@i > 0)
            begin
                update @HoldTable
                set HoldFrom = dateadd(day, 1, V.HoldTo) 
                from @HoldTable H
                    inner join (select * from @HoldTable) V on H.Code - 1 = V.Code 
                where V.HoldTo >= H.HoldFrom
                delete from @HoldTable where HoldFrom > HoldTo
                set @i = @@rowcount
                if @i > 0
                begin
                    delete from @InterTable
                    insert into @InterTable(DateFrom, DateTo) select HoldFrom, HoldTo from @HoldTable 
                    delete from @HoldTable
                    insert into @HoldTable(HoldFrom, HoldTo) select DateFrom, DateTo from @InterTable order by DateFrom, DateTo
                end    
            end
        end
        
    end

    --9047 replace LLU_Provider_Vacation with LLU_Provider_UnAvailable.
    delete from @TempTable
    insert @TempTable(DateFrom, DateTo, CrossDays)
    select v.DateFrom, v.DateTo, 
        sum((case when act.HoldFrom is null 
                  then 0 
                  else dbo.CalculateCrossDays(@DefSDate, v.DateFrom, v.DateTo, act.HoldFrom, isnull(act.HoldTo, @DefEndDate), @DefEndDate)
                  end)) as CrossDays
    FROM 
        (select DateFrom, DateTo
        FROM dbo.LLU_Provider_UnAvailable
    	Where ProviderID = @DefDrN and DateTo > @DefSDate) v
        left join @HoldTable act 
            on dbo.IsDateCross(v.DateFrom, v.DateTo, act.HoldFrom, act.Holdto) = 1
    group by v.DateFrom, v.DateTo

    Set @DefVDays = isnull(
    (select sum(dbo.CalculateTotalDays(@DefSDate, DateFrom, DateTo, @DefEndDate) - isnull(CrossDays, 0))
    from @TempTable), 0)

    if @DefVDays < 0 set @DefVDays = 0
    delete from @TempTable   	

	Set @DrStatus = isnull(@DrStatus, 'Active')
--	Set @DefDays =  datediff(d, @DefSDate, @DefHSDate) - (isnull(@DefSDays, 0) + isnull(@DefVDays, 0) + isnull(@DefMDays, 0) + isnull(@DefHoldDays, 0))
    Set @DefDays = datediff(day, @DefSDate, @DefEndDate) - (isnull(@DefVDays, 0) + isnull(@DefSDays, 0) + isnull(@DefMDays, 0) + isnull(@DefHoldDays, 0))

	if @DefDays < 0 Set @DefDays = 0
    --EN-00333
    Set @DefTotalDays = datediff(day, @DefSDate, @DefEndDate)
    if @DefTotalDays < 0 set @DefTotalDays = 0

--Ticket 12456 reset deficiency header status
	Update dbo.Def_SlipMain 
    Set DefDays = isnull(@DefDays, 0), 
        DefVacationDays = isnull(@DefVDays, 0), 
	    DefSuspensionDays = isnull(@DefSDays, 0),
        DefHoldDays = isnull(@DefHoldDays, 0),
        DefMainStatus = (case when DefMainStatus = 8 then DefMainStatus
                              when @IsCountDay = '0' then 7
                              when @IsSuspend = 1 then 10
                              when isnull(@DefDays, 0) = 0 then 7 --DefMainStatus
                              when @Level_5 > 0 and @DefDays >= @Level_5 then 6
                              when @Level_4 > 0 and @DefDays >= @Level_4 then 5
                              when @Level_3 > 0 and @DefDays >= @Level_3 then 4
                              when @Level_2 > 0 and @DefDays >= @Level_2 then 3
                              when @Level_1 > 0 and @DefDays >= @Level_1 then 2
                              else 7 --DefMainStatus
                         end),
        DefTotalDays = @DefTotalDays
    where DefID = @DefId
--EN-00183
--    where DefeciencyID = @DefId

--        DefHoldStartDate = (case when isnull(@DefHSDate, '2999/12/31') < DefHoldStartDate or DefHoldStartDate is null then @DefHSDate else DefHoldStartDate end),
--        DefHoldEndDate = (case when isnull(@DefHEDate, '1900/01/01') > DefHoldEndDate or DefHoldEndDate is null then @DefHEDate else DefHoldEndDate end)
--, DefDrStatus = @DrStatus

	fetch next from Cur_DefCount
	into  @DefId, @DefDrN, @DefHSDate, @DefHEDate, @DefSDate, @DefEndDate, @DefVDays, @DefMDays, @VolumeID, @IsCountDay
End

Close Cur_DefCount
Deallocate Cur_DefCount

if isnull(@DefSlipID , 0) > 0
	Update dbo.Def_Activity 
    Set DefDays = datediff(d, DefStartDate, isnull(DefEndDate, getdate()))
	where DefID = @DefId and DefStatus not in (8, 11)  --<> 8 PR - 02842
--EN-00183
--	where HeaderDefID = @DefId and DefStatus <> 8
else
	Update dbo.Def_Activity 
    Set DefDays = datediff(d, DefStartDate, isnull(DefEndDate, getdate()))
	where DefStatus not in (8, 11)  --<> 8 PR - 02842 and DefEndDate is null


return (isnull(@DefDays, 0))






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE  PROCEDURE [CACS_Grouping]
    @ICDType varchar(1),  
    @AnesTech1 varchar(1),  
    @Age int,  
    @Gender varchar(1),  
    @Diagnosis1 varchar(10),  
    @Procedure1 varchar(10),  
    @Procedure2 varchar(10),  
    @Procedure3 varchar(10),  
    @Procedure4 varchar(10),  
    @Procedure5 varchar(10),  
    @Procedure6 varchar(10),  
    @Procedure7 varchar(10),  
    @Procedure8 varchar(10),  
    @Procedure9 varchar(10),  
    @Procedure10 varchar(10),  
    @EncounterNumber varchar(50),  
    @MAC_Return int output,  
    @CACSCell_Return decimal(5,1) output,     
    @ACW decimal(6,4) output,  
    @CACSDescription varchar(150) output,  
    @AbstractID int,  
    @IntervCode int,             
    @DispositionCode varchar(2), 
    @AgeCode varchar(1),    -- CIHI value
    @Program varchar(12),   -- CIHI value
    @OOH1 varchar(12),    -- CIHI value
    @OOH2 varchar(12),    -- CIHI value
    @OOH3 varchar(12),    -- CIHI value
    @OOH4 varchar(12),    -- CIHI value
    @OOH5 varchar(12),    -- CIHI value
    @OOH6 varchar(12),    -- CIHI value
    @OOH7 varchar(12),    -- CIHI value
    @OOH8 varchar(12),    -- CIHI value
    @OOH9 varchar(12),    -- CIHI value
    @OOH10 varchar(12),    -- CIHI value
    @Status1 varchar(12),    -- CIHI value
    @Status2 varchar(12),    -- CIHI value
    @Status3 varchar(12),    -- CIHI value
    @Status4 varchar(12),    -- CIHI value
    @Status5 varchar(12),    -- CIHI value
    @Status6 varchar(12),    -- CIHI value
    @Status7 varchar(12),    -- CIHI value
    @Status8 varchar(12),    -- CIHI value
    @Status9 varchar(12),    -- CIHI value
    @Status10 varchar(12),    -- CIHI value
    @Location1 varchar(12),    -- CIHI value
    @Location2 varchar(12),    -- CIHI value
    @Location3 varchar(12),    -- CIHI value
    @Location4 varchar(12),    -- CIHI value
    @Location5 varchar(12),    -- CIHI value
    @Location6 varchar(12),    -- CIHI value
    @Location7 varchar(12),    -- CIHI value
    @Location8 varchar(12),    -- CIHI value
    @Location9 varchar(12),    -- CIHI value
    @Location10 varchar(12),    -- CIHI value
    @Extent1 varchar(12),    -- CIHI value
    @Extent2 varchar(12),    -- CIHI value
    @Extent3 varchar(12),    -- CIHI value
    @Extent4 varchar(12),    -- CIHI value
    @Extent5 varchar(12),    -- CIHI value
    @Extent6 varchar(12),    -- CIHI value
    @Extent7 varchar(12),    -- CIHI value
    @Extent8 varchar(12),   -- CIHI value
    @Extent9 varchar(12),    -- CIHI value
    @Extent10 varchar(12)    -- CIHI value
as  
    declare @CACSCell varchar(6)  
    declare @cMajorInvestTech varchar(10)
    declare @Mac int  
	Declare @CACSCellHolding Varchar(6)
	declare @GYear as varchar(4)
	set @GYear = '2006'
    set @AnesTech1   = isnull(@AnesTech1, '')
    set @Diagnosis1  = isnull(@Diagnosis1, '')
    set @Procedure1  = isnull(@Procedure1, '')
    set @Procedure2  = isnull(@Procedure2, '')
    set @Procedure3  = isnull(@Procedure3, '')
    set @Procedure4  = isnull(@Procedure4, '')
    set @Procedure5  = isnull(@Procedure5, '')
    set @Procedure6  = isnull(@Procedure6, '')
    set @Procedure7  = isnull(@Procedure7, '')
    set @Procedure8  = isnull(@Procedure8, '')
    set @Procedure9  = isnull(@Procedure9, '')
    set @Procedure10 = isnull(@Procedure10, '')
    set @OOH1  = isnull(@OOH1, '')
    set @OOH2  = isnull(@OOH2, '')
    set @OOH3  = isnull(@OOH3, '')
    set @OOH4  = isnull(@OOH4, '')
    set @OOH5  = isnull(@OOH5, '')
    set @OOH6  = isnull(@OOH6, '')
    set @OOH7  = isnull(@OOH7, '')
    set @OOH8  = isnull(@OOH8, '')
    set @OOH9  = isnull(@OOH9, '')
    set @OOH10  = isnull(@OOH10, '')
    set @Status1  = isnull(@Status1, '')
    set @Status2  = isnull(@Status2, '')
    set @Status3  = isnull(@Status3, '')
    set @Status4  = isnull(@Status4, '')
    set @Status5  = isnull(@Status5, '')
    set @Status6  = isnull(@Status6, '')
    set @Status7  = isnull(@Status7, '')
    set @Status8  = isnull(@Status8, '')
    set @Status9  = isnull(@Status9, '')
    set @Status10  = isnull(@Status10, '')
    set @Location1  = isnull(@Location1, '')
    set @Location2  = isnull(@Location2, '')
    set @Location3  = isnull(@Location3, '')
    set @Location4  = isnull(@Location4, '')
    set @Location5  = isnull(@Location5, '')
    set @Location6  = isnull(@Location6, '')
    set @Location7  = isnull(@Location7, '')
    set @Location8  = isnull(@Location8, '')
    set @Location9  = isnull(@Location9, '')
    set @Location10  = isnull(@Location10, '')
    set @Extent1  = isnull(@Extent1, '')
    set @Extent2  = isnull(@Extent2, '')
    set @Extent3  = isnull(@Extent3, '')
    set @Extent4  = isnull(@Extent4, '')
    set @Extent5  = isnull(@Extent5, '')
    set @Extent6  = isnull(@Extent6, '')
    set @Extent7  = isnull(@Extent7, '')
    set @Extent8  = isnull(@Extent8, '')
    set @Extent9  = isnull(@Extent9, '')
    set @Extent10  = isnull(@Extent10, '')
    set @Age = (case @AgeCode when 'Y' then @Age else 0 end)
    set @MAC = ''  
    set @CACSCell = ''  
    set @cMajorInvestTech = ''

	--Initialize Intervention Table
	--Declare #IntervAll table (Occ int, IntervCode Varchar(10))
	Create Table #IntervAll  
		(Occ int, IntervCode Varchar(10))

    if @Procedure1 <> '' and @Status1 <> 'A' and @OOH1 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (1, @Procedure1)
    if @Procedure2 <> '' and @Status2 <> 'A' and @OOH2 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (2, @Procedure2)
    if @Procedure3 <> '' and @Status3 <> 'A' and @OOH3 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (3, @Procedure3)
    if @Procedure4 <> '' and @Status4 <> 'A' and @OOH4 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (4, @Procedure4)
    if @Procedure5 <> '' and @Status5 <> 'A' and @OOH5 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (5, @Procedure5)
    if @Procedure6 <> '' and @Status6 <> 'A' and @OOH6 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (6, @Procedure6)
    if @Procedure7 <> '' and @Status7 <> 'A' and @OOH7 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (7, @Procedure7)
    if @Procedure8 <> '' and @Status8 <> 'A' and @OOH8 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (8, @Procedure8)
    if @Procedure9 <> '' and @Status9 <> 'A' and @OOH9 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (9, @Procedure9)
    if @Procedure10 <> '' and @Status10 <> 'A' and @OOH10 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (10, @Procedure10)

    -- 4.4 Assign MAC based on Main Problem...  
    if @Diagnosis1 = ''  
    begin  
        -- Ungroupable when no diagnosis code.
        set @CACSCell = '9990'  
        set @MAC = '99'  
        goto IdentifyMajorInvestigativeTech  
    end  
    else  
    begin  
		Declare @cDiagGender as VarChar(1)
		Declare @cCACSSplit1 as VarChar(4)
        select @MAC = MAC, @cCACSSplit1 = CACSSplit1, @cDiagGender = ValidGender
        from dbo.Grouper_CACS_I10DX
        Where GYear = @GYear and  (ICD10CACode = @Diagnosis1) 
		--and ValidGender in ('B', @Gender)   
      
        -- Consider it ungroupable if the diagnosis code is not in the CACS table  
        if isnull(@MAC, '') = ''
        begin  
            set @CACSCell = '9990'  
            set @MAC = '99'  
            goto IdentifyMajorInvestigativeTech  
        end
    end  
	-- 4.5 Assign Intervention Cells
	-- 4.5.1-4.5.3
	declare @cIntervGender as Varchar(1)
	declare @cAnaesFlag as Varchar(1)
	declare @cIntervSplit as Varchar(4)
--check 1YM89LA and 1YM91LA here
	select top 1 @cAnaesFlag = AnaesFlag, @cIntervSplit = IntervSplit, @cIntervGender = IntervGender from [Grouper_CACS_IntervAss] Where GYear = @GYear and  (IntervCode = @Procedure1 and LocAttribute = '98') or
	(IntervCode = @Procedure1 and LocAttribute = @Location1)
	order by LocAttribute desc
	-- 4.5.4
	if @cAnaesFlag is null
	Begin
		Set @cAnaesFlag = '8'
		Set @cIntervSplit = '3000'
	End

	-- 4.5.5
	if @cAnaesFlag = 'Y' and isnull(@AnesTech1, '') = ''
		Set @cIntervSplit = '9990'
	--4.5.6
	set @CACSCellHolding = ''
	select @CACSCellHolding = CACSCode from [Grouper_CACS_InterAnaesSplit] Where GYear = @GYear and  IntervSplit = @cIntervSplit and AnaesTech = @AnesTech1 and AnaesFlag = @cAnaesFlag
	set @CACSCell = @CACSCellHolding
	--4.5.7
	if isnull(@CACSCell, '') = ''
		set @CACSCell = @cIntervSplit 

	--4.5.8
	if isnull(@CACSCell, '') <> '3000' and @Status1 = 'A'
		set @CACSCell = '9990'
	--4.5.9
	Else if isnull(@CACSCell, '') <> '3000' and @OOH1 = 'Y'
		set @CACSCell = '3000'
	--4.5.10
	Else if isnull(@CACSCell, '') not in ('3000', '9990') and @cIntervGender <> @Gender and @Gender <> 'O'
		and @cIntervGender <> 'B'
		set @CACSCell = '9990'

	--4.6.1
	If @DispositionCode = '02'
	Begin
		set @CACSCell = '7010'
		Goto IdentifyMajorInvestigativeTech
	End
	--4.6.2
	Else If @DispositionCode = '11'
	Begin
		set @CACSCell = '7000'
		Goto IdentifyMajorInvestigativeTech
	End
	--4.7 Assign Rehab
/*--Rehab Debug Code
print 'Rehab Debug - CACS, Procedure1, Status1, ProgramCode: [Grouper_CACS_RehabInterv]'
print @CACSCell
Print @Procedure1
print @Status1
print @Program
*/
	--4.7.1
	If isnull(@CACSCell, '') <> '3000'
		goto AssignMentalHealth
	--4.7.2
	If @OOH1 = 'Y' or @Status1 = 'A'
		goto AssignMentalHealth
	--4.7.3
	Declare @cRehabIntervCat as Varchar(1)
	select top 1 @cRehabIntervCat = IntervCat from [Grouper_CACS_RehabInterv] 
	Where GYear = @GYear and  (IntervCode = @Procedure1 and StatusAttribute = @Status1 and ProgramArea = @Program)
	--4.7.4
	if isnull(@cRehabIntervCat, '') = ''
		select top 1 @cRehabIntervCat = IntervCat from [Grouper_CACS_RehabInterv] 
		Where GYear = @GYear and  (IntervCode = @Procedure1 and StatusAttribute = '98' and ProgramArea = @Program)
	--4.7.5
	if isnull(@cRehabIntervCat, '') = ''
		select top 1 @cRehabIntervCat = IntervCat from [Grouper_CACS_RehabInterv] 
		Where GYear = @GYear and  (IntervCode = @Procedure1 and StatusAttribute = '98' and ProgramArea = '98')
	--4.7.6
	if isnull(@cRehabIntervCat, '') = ''
		goto AssignMentalHealth
	--4.7.7

	Declare @cRehabSplit as Varchar(4)
	select @cRehabSplit = RehabDiagSplit from Grouper_CACS_RehabDiagSplitAss
	Where GYear = @GYear and  DiagCode = @Diagnosis1
	--4.7.8
	if isnull(@cRehabSplit, '') = ''
		print 'Troy Do Exception Flow 1'
	--4.7.9
	set @CACSCellHolding = ''
	select @CACSCellHolding = CACSCode from Grouper_CACS_RehabIntervCatAss 
	Where GYear = @GYear and  DiagSplit = @cRehabSplit and IntervCat = @cRehabIntervCat
	set @CACSCell = @CACSCellHolding
	--4.7.10
	if isnull(@CACSCell, '') = ''
		set @CACSCell = @cRehabSplit
	--4.7.11
	goto IdentifyMajorInvestigativeTech

	--4.8 Assign Mental
	AssignMentalHealth:
/*--MH Debug Code
print 'MH Debug - CACS, Procedure1, @Status1, @Extent1, ProgramCode: Grouper_CACS_MHIntervAss'
print @CACSCell
Print @Procedure1
print @Status1
print @Extent1
print @Program
*/
	--4.8.1, 4.8.3
	If isnull(@CACSCell, '') <> '3000' or @OOH1 = 'Y' or @Status1 = 'A'
		goto AssignCACSonMainProblem
	--4.8.4
	Declare @cMHIntervSplit as Varchar(4)
	select top 1 @cMHIntervSplit = MHIntervSplit from Grouper_CACS_MHIntervAss 
	Where GYear = @GYear and  (IntervCode = @Procedure1 and ProgramArea = @Program)

	--4.8.5
	if isnull(@cMHIntervSplit, '') = ''
		select top 1 @cMHIntervSplit = MHIntervSplit from Grouper_CACS_MHIntervAss 
		Where GYear = @GYear and  (IntervCode = @Procedure1 and ExtentAttribute = @Extent1)
	--4.8.6
	if isnull(@cMHIntervSplit, '') = ''
		select top 1 @cMHIntervSplit = MHIntervSplit from Grouper_CACS_MHIntervAss 
		Where GYear = @GYear and  (IntervCode = @Procedure1 and StatusAttribute = @Status1)
	--4.8.7
	if isnull(@cMHIntervSplit, '') = ''
		select top 1 @cMHIntervSplit = MHIntervSplit from Grouper_CACS_MHIntervAss 
		Where GYear = @GYear and  (IntervCode = @Procedure1 and StatusAttribute = '98' and ExtentAttribute = '98' and ProgramArea = '98')
	--4.8.8
	if isnull(@cMHIntervSplit, '') = ''
		goto AssignCACSonMainProblem
	--4.8.9
	set @CACSCellHolding = ''
	select @CACSCellHolding = CACSCode from Grouper_CACS_MHDiagTypeAss
	Where GYear = @GYear and  DiagCode = @Diagnosis1 and MHIntervSplit = @cMHIntervSplit
	set @CACSCell = @CACSCellHolding
	--4.8.10
	if isnull(@CACSCell, '') = ''
		Set @CACSCell = @cMHIntervSplit
	--4.8.11
	set @MAC = 19
	--4.8.12
	goto IdentifyMajorInvestigativeTech

	--4.9
	AssignCACSonMainProblem:

	--4.9.1
	If isnull(@CACSCell, '') <> '3000'
		goto IdentifyMajorInvestigativeTech
	--4.9.2
	if @cDiagGender in ('M', 'F') and @Gender <> @cDiagGender
	Begin
		Set @CACSCell = '9990'
		goto IdentifyMajorInvestigativeTech
	End
	--4.9.3
	Declare @cMinorInvTechFlag as VarChar(1)
	Set @cMinorInvTechFlag = 'N'
	Declare @cCACSSplit2 as Varchar(4)
	Set @cCACSSplit2 = ''
	--4.9.4, 4.9.5
	if exists (select * from Grouper_CACS_MinorInvestTech 
			Where GYear = @GYear and  IntervCode in (select IntervCode from #IntervAll))
		Set @cMinorInvTechFlag = 'Y'
	--4.9.6
	if @cMinorInvTechFlag = 'Y'
	Begin
		Select @cCACSSplit2 = CACSSplit2 from Grouper_CACS_MinorInvestTechSplit
		Where GYear = @GYear and  CACSSplit1 = @cCACSSplit1
		--4.9.7
		If isnull(@cCACSSplit2, '') = ''
			set @cCACSSplit2 = @cCACSSplit1
	End
	--4.9.8
	if @cMinorInvTechFlag <> 'Y'
		set @cCACSSplit2 = @cCACSSplit1
	--4.9.9
	set @CACSCellHolding = ''
	Select @CACSCellHolding = CACSCode from Grouper_CACS_AgeSplit
	Where GYear = @GYear and  CACSSplit2 = @cCACSSplit2 and AgeYears = @Age
	set @CACSCell = @CACSCellHolding
	--4.9.10
	if isnull(@CACSCell, '') = ''
		set @CACSCell = @cCACSSplit2

	--4.10 Identify Major Investigative Technology
	IdentifyMajorInvestigativeTech:
/*--IdentifyMajorInvestigativeTech Debug Code
print 'IdentifyMajorInvestigativeTech Debug - @CACSCell, Procedure1, @Procedure2, @Procedure3, @Procedure4: Grouper_CACS_MajorInvestTech'
print @CACSCell
Print @Procedure1
print @Procedure2
print @Procedure3
print @Procedure4
--End Debug
*/
	--4.10.2
	select top 1 @cMajorInvestTech = MajorInvTech from Grouper_CACS_MajorInvestTech
	Where GYear = @GYear and  IntervCode in (select IntervCode from #IntervAll) order by MajorInvTechRank
	--4.10.3
	if isnull(@cMajorInvestTech, 0) = 0
		Set @cMajorInvestTech = 0
	--4.10.4
	if @CACSCell in ('7000', '7010') and @cMajorInvestTech <> 0
		set @CACSCell = '9990'

	--4.11 Assign Weight
	set @CACSCell_Return = @CACSCell
	Set @MAC_Return = @MAC
	Select @ACW = CACSRIW, @CACSDescription = CACSDescription from Grouper_CACS_WeightAss
		Where GYear = @GYear and  CACSCode = @CACSCell_Return and VisitDisposition = @DispositionCode and
		MajorInvestTech = @cMajorInvestTech
/*--Assign Weight Debug Code
print 'Assign Weight Debug - @cMajorInvestTech, @DispositionCode, @CACSCell_Return: Grouper_CACS_WeightAss'
print @cMajorInvestTech
print @DispositionCode
print @CACSCell_Return
--End Debug
*/	
	If @CACSCell_Return = '9990' and isnull(@ACW, 0) = 0
		set @ACW = '0.0000'

	--Ticket 11969 Enhancement for CACS Auditing
	If isnull(@AbstractID, 0) > 0
	Begin
		Declare @AUMAC as Varchar(6)
		Declare @AUCACSCell as VarChar(20)
		Declare @AUACW as VarChar(20)
		Declare @AUAid as int
		SELECT @AUAid = Abstractid, @AUMAC = MAC, @AUCACSCell = CACSCell, @AUACW = ACW
		FROM AB_CACS Where AbstractID = @AbstractID and OccurrenceNumber = 1 and CACS_Year = 2006
		If isnull(@AUAid, 0) > 0
		Begin
			If @AUMAC <> @MAC_Return
				Insert into AB_GrouperAudit Values (@AbstractID, 2006, 'MAC', @AUMAC, @MAC_Return, GetDate())
			If @AUCACSCell <> @CACSCell_Return
				Insert into AB_GrouperAudit Values (@AbstractID, 2006, 'CACSCell', @AUCACSCell, @CACSCell_Return, GetDate())
			If @AUACW <> @ACW
				Insert into AB_GrouperAudit Values (@AbstractID, 2006, 'ACW', @AUACW, @ACW, GetDate())
		End
	End

    -- For batch processing use...update the CACS table here.  Otherwise update it from vb.  
    if isnull(@AbstractID, 0) > 0  
    begin
        delete AB_CACS Where Abstractid = @Abstractid and CACS_Year = 2006 and OccurrenceNumber = 1  
        if IsNull(@MAC, '') <> ''  
        begin  
            insert into [dbo].[AB_CACS] (AbstractID, OccurrenceNumber, CACS_Year, MAC, CACSCell, ACW, CACSDescription, InterventionCode) values   
            (@AbstractID, 1, 2006, @MAC_Return, @CACSCell_Return, @ACW, @CACSDescription, @IntervCode)  
        end  
    end  

    -- For DPG Ontario calculation...
    declare @CACSValue int
    declare @CACSDPGONValid int
    declare @HospCode int
    -- Set a arbitrary constant to determine if client has access to this calculation...
    set @CACSDPGONValid = 66101
    select @CACSValue = CACSDPGONValue from CACS_DPGON Where CACSYear = 2006
    --select top 1 @HospCode = code from H_HospitalProfile order by code
    -- Criteria: Constant = HospitalCode + CACSValue

    --if (@AbstractID > 0) and  (@CACSValue + @HospCode = @CACSDPGONValid)
    if (@AbstractID > 0) and exists(select code from H_HospitalProfile Where code + @CACSValue = 66101) --PR - 00993
    begin
        -- Check for 'abandon' intervention...
        if @Status1 = 'A'
            set @Procedure1 = 'Abandon'
        exec P_LookupDPGON  @ICDType, 2006, @Procedure1, @Location1, @AbstractID
    end


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE PROCEDURE [CACS_Grouping_2002]  
   @ICDType VarChar(1),  
   @AnesTech Varchar(1),  
   @Age Int,  
   @Gender VarChar(1),  
   @Diagnosis1 VarChar(10),  
   @Procedure1 VarChar(10),  
   @Procedure2 VarChar(10),  
   @Procedure3 VarChar(10),  
   @Procedure4 VarChar(10),  
   @Procedure5 VarChar(10),  
   @Procedure6 VarChar(10),  
   @Procedure7 VarChar(10),  
   @Procedure8 VarChar(10),  
   @Procedure9 VarChar(10),  
   @Procedure10 VarChar(10),  
   @Encounter_no Varchar(50),  
   @MAC_Return int output,  
   @CACSCell_Return Decimal(5,1) output,     
   @ACW Decimal(6,4) output,  
   @CACSDescription VarChar(150) output,  
   @AbstractID int,  
    @IntervCode int,             -- Added...New, 2002/06/25, it is the code value of @Procedure1 above.  
    @DispositionCode varchar(2)  -- Added...new, 2002/06/25, the CIHI value.  
AS  
   Declare @CACSBranch Varchar(4)  
   Declare @DPGNumber Varchar(16)   
   Declare @InvesTechType Varchar(10)        
   Declare @ITFlag int  
   Declare @Intmh int   
   Declare @Intrh int   
   Declare @P_Count Int   
   Declare @C_Count Int   
   Declare @CountTemp3 Varchar(8)  
   Declare @TypeTemp int   
   Declare @ReDiaBranch Varchar(8)  
    Declare @Mac int  
    Declare @CACSCell Varchar(6)  
-- NB: Incoming Parameters are CIHI values.  
  
    if isnull(@AnesTech, '0') = '0' set @AnesTech = ''  
   if isnull(@Diagnosis1, '0') = '0' set @Diagnosis1 = ''  
   if isnull(@Procedure1, '0') = '0' set @Procedure1 = ''  
   if isnull(@Procedure2, '0') = '0' set @Procedure2 = ''  
   if isnull(@Procedure3, '0') = '0' set @Procedure3 = ''  
   if isnull(@Procedure4, '0') = '0' set @Procedure4 = ''  
   if isnull(@Procedure5, '0') = '0' set @Procedure5 = ''  
   if isnull(@Procedure6, '0') = '0' set @Procedure6 = ''  
   if isnull(@Procedure7, '0') = '0' set @Procedure7 = ''  
   if isnull(@Procedure8, '0') = '0' set @Procedure8 = ''  
   if isnull(@Procedure9, '0') = '0' set @Procedure9 = ''  
   if isnull(@Procedure10,'0') = '0' set @Procedure10 = ''  
   Set @MAC = ''  
    set @CACSCell = ''  
   Set @CACSBranch = ''  
   Set @ITFlag = 0  
     
-- Step 1. Assign MAC based on Main Problem...  
   If @Diagnosis1 = ''  
   Begin  
        -- Ungroupable when no diagnosis code  
           set @CACSCell = '9999'  
           Set @MAC = '99'  
           Goto FinalStep  
   End  
    else  
    begin  
           Select @MAC = MAC, @CACSBranch = CACSBranch  
        From dbo.LU_CACS_MD_2002  
           Where (ICDCode = @Diagnosis1)    
      
           If isnull(@MAC, '') = ''    
           Begin  
                   Select @MAC = MAC, @CACSBranch = CACSBranch  
            From dbo.LU_CACS_MD_2002  
                   Where (ICDCode = Left(@Diagnosis1,4))    
            -- Consider it ungroupable when diagnosis code is not in the CACS table  
                   If isnull(@MAC, '') = ''   
                   Begin  
                           set @CACSCell = '9999'  
                           Set @MAC = '99'  
                           Goto FinalStep  
                   End  
           End  
           Set @CACSCell = @CACSBranch  
    end  
  
-- Step 2. Check Dead On Arrival (DOA) or Left without being seen...  
    set @CACSCell =   
        (case   
            when @DispositionCode = '11' then '9900' -- DOA  
            when @DispositionCode = '02' then '9905' -- Left without being seen  
            else @CACSCell  
        end)  
    if @CACSCell in ('9900','9905')  
    begin  
        set @MAC = '99'  
        goto FinalStep  
    end  
  
-- Step 3. Examine patient abstract for any Day Procedure...  
   If @Procedure1 <> ''  
   Begin  
           Select @DPGNumber = DPGNumber   
        From dbo.LU_CACS_DPG_2002  
           Where (ProcedureCode = @Procedure1)   
  
           If isnull(@DPGNumber, '') <> ''  
           Begin  
                   set @CACSCell = @DPGNumber  
                   If @DPGNumber in ('01','15','48','50','52','65')  
                           Set @CACSCell =   
                           (Case  
                                     When @AnesTech >= '1' And @AnesTech <= '4' Then @CACSCell + '.1'  
                                     When @AnesTech >= '5' And @AnesTech <= '6' Then @CACSCell + '.2'  
                                     When @AnesTech >= '7' And @AnesTech <= '9' Then @CACSCell + '.3'  
                      else @CACSCell  
                            End)  
                   Goto FinalStep  
           End  
   End  
  
-- Step 4. Examine patient abstract for any Major Investigative Technologies...  
   If @Procedure1 <> '' or @Procedure2 <> '' or @Procedure3 <> '' or @Procedure4 <> '' or   
      @Procedure5 <> '' or @Procedure6 <> '' or @procedure7 <> '' or @procedure8 <> '' or   
      @procedure9 <> '' or @procedure10 <> ''  
   Begin  
           Set @InvesTechType = ''  
           Declare cur_FlagMIT cursor for  
           Select InvesTechType   
        from dbo.LU_CACS_TECH_2002   
        Where (code in (@Procedure1,@Procedure2,@Procedure3,@Procedure4,@Procedure5,  
            @Procedure6,@Procedure7,@Procedure8,@Procedure9,@Procedure10))   
          
           Open cur_FlagMIT  
           fetch next from cur_FlagMIT   
        into @InvesTechType  
  
           While @@fetch_status = 0  
           Begin  
                   Set @ITFlag = 1           
                   If @InvesTechType = 'MRI'   
                           Set @CACSCell = '9700'  
                   If @InvesTechType = 'CATS' and @CACSCell <>'9700'  
                           Set @CACSCell = '9705'  
                   If @InvesTechType = 'NUKE' and @CACSCell not like '970%'   
                           Set @CACSCell = '9710'  
                   If @InvesTechType = 'LYMPH' and @CACSCell not like '97%'  
                           Set @CACSCell = '9715'  
                   fetch next from cur_FlagMIT  
                   into @InvesTechType  
           End  
           Close cur_FlagMIT  
           Deallocate cur_FlagMIT  
           If @CACSCell like '97%' GoTO FinalStep  
             
-- Step 5. Rehabilitation or mental health...   
        Set @Intmh = 0  
        Set @INTRH = 0  
        Set @P_Count = 0  
        Set @C_Count = 0  
          
        If @Procedure1 <> ''  
        Begin  
           IF Exists (Select Top 1 * From dbo.LU_CACS_INTMH_2002 Where (InterventionCode = @Procedure1))  
                   Set @INTMH = @INTMH+1  
           Set @CountTemp3 = ''  
           Select @CountTemp3 = RehabIntervCate From dbo.LU_CACS_INTRH_2002 Where (CIHIIntervCode = @Procedure1)  
           If @CountTemp3 <> ''              
                Set @INTRH = @INTRH + 1  
           If @CountTemp3 = 'prhab'                  
                Set @P_Count = @P_Count + 1  
           IF @CountTemp3 = 'crhab'                  
                Set @C_Count = @C_Count + 1  
        End  
          
        IF @Procedure2 <> ''  
        Begin  
           IF Exists (Select Top 1 * From dbo.LU_CACS_INTMH_2002 Where (InterventionCode = @Procedure2))  
                   Set @INTMH = @INTMH + 1  
           Set @CountTemp3 = ''  
           Select @CountTemp3 = RehabIntervCate From dbo.LU_CACS_INTRH_2002 Where (CIHIIntervCode = @Procedure2)  
           If @CountTemp3 <> ''              
                Set @INTRH = @INTRH + 1  
           If @CountTemp3 = 'prhab'                  
                Set @P_Count = @P_Count + 1  
           IF @CountTemp3 = 'crhab'                  
                Set @C_Count = @C_Count + 1  
        End  
          
        IF @Procedure3 <> ''  
        Begin  
           IF Exists (Select Top 1 * From dbo.LU_CACS_INTMH_2002 Where (InterventionCode = @Procedure3))  
                   Set @INTMH = @INTMH + 1  
           Set @CountTemp3 = ''  
           Select @CountTemp3 = RehabIntervCate From dbo.LU_CACS_INTRH_2002 Where (CIHIIntervCode = @Procedure3)  
           If @CountTemp3 <> ''              
                Set @INTRH = @INTRH + 1  
           If @CountTemp3 = 'prhab'                  
                Set @P_Count = @P_Count + 1  
           IF @CountTemp3 = 'crhab'                  
                Set @C_Count = @C_Count + 1  
        End  
          
        IF @Procedure4 <> ''  
        Begin  
           IF Exists (Select Top 1 * From dbo.LU_CACS_INTMH_2002 Where (InterventionCode = @Procedure4))  
                   Set @INTMH = @INTMH + 1  
           Set @CountTemp3 = ''  
           Select @CountTemp3 = RehabIntervCate From dbo.LU_CACS_INTRH_2002 Where (CIHIIntervCode = @Procedure4)  
           If @CountTemp3 <> ''              
                Set @INTRH = @INTRH + 1  
           If @CountTemp3 = 'prhab'                  
                Set @P_Count = @P_Count + 1  
           IF @CountTemp3 = 'crhab'                  
                Set @C_Count = @C_Count + 1  
        End  
          
        If @Procedure5 <> ''  
        Begin  
           IF Exists (Select Top 1 * From dbo.LU_CACS_INTMH_2002 Where (InterventionCode = @Procedure5))  
                   Set @INTMH = @INTMH + 1  
           Set @CountTemp3 = ''  
           Select @CountTemp3 = RehabIntervCate From dbo.LU_CACS_INTRH_2002 Where (CIHIIntervCode = @Procedure5)  
           If @CountTemp3 <> ''              
                Set @INTRH = @INTRH + 1  
           If @CountTemp3 = 'prhab'                  
                Set @P_Count = @P_Count + 1  
           IF @CountTemp3 = 'crhab'                  
                Set @C_Count = @C_Count + 1  
        End  
          
        If @Procedure6 <> ''  
        Begin  
           IF Exists (Select Top 1 * From dbo.LU_CACS_INTMH_2002 Where (InterventionCode = @Procedure6))  
                   Set @INTMH = @INTMH + 1  
           Set @CountTemp3 = ''  
           Select @CountTemp3 = RehabIntervCate From dbo.LU_CACS_INTRH_2002 Where (CIHIIntervCode = @Procedure6)  
           If @CountTemp3 <> ''              
                Set @INTRH = @INTRH + 1  
           If @CountTemp3 = 'prhab'                  
                Set @P_Count = @P_Count + 1  
           IF @CountTemp3 = 'crhab'                  
                Set @C_Count = @C_Count + 1  
        End  
          
        IF @Procedure7 <> ''  
        Begin  
           IF Exists (Select Top 1 * From dbo.LU_CACS_INTMH_2002 Where (InterventionCode = @Procedure7))  
                   Set @INTMH = @INTMH + 1  
           Set @CountTemp3 = ''  
           Select @CountTemp3 = RehabIntervCate From dbo.LU_CACS_INTRH_2002 Where (CIHIIntervCode = @Procedure7)  
           If @CountTemp3 <> ''              
                Set @INTRH = @INTRH + 1  
           If @CountTemp3 = 'prhab'                  
                Set @P_Count = @P_Count + 1  
           IF @CountTemp3 = 'crhab'                  
                Set @C_Count = @C_Count + 1  
        End  
          
        If @Procedure8 <> ''  
        Begin  
           IF Exists (Select Top 1 * From dbo.LU_CACS_INTMH_2002 Where (InterventionCode = @Procedure8))  
                   Set @INTMH = @INTMH + 1  
           Set @CountTemp3 = ''  
           Select @CountTemp3 = RehabIntervCate From dbo.LU_CACS_INTRH_2002 Where (CIHIIntervCode = @Procedure8)  
           If @CountTemp3 <> ''              
                Set @INTRH = @INTRH + 1  
           If @CountTemp3 = 'prhab'                  
                Set @P_Count = @P_Count + 1  
           IF @CountTemp3 = 'crhab'                  
                Set @C_Count = @C_Count + 1  
        End  
          
        If @Procedure9 <> ''  
        Begin  
           IF Exists (Select Top 1 * From dbo.LU_CACS_INTMH_2002 Where (InterventionCode = @Procedure9))  
                   Set @INTMH = @INTMH + 1  
           Set @CountTemp3 = ''  
           Select @CountTemp3 = RehabIntervCate From dbo.LU_CACS_INTRH_2002 Where (CIHIIntervCode = @Procedure9)  
           If @CountTemp3 <> ''              
                Set @INTRH = @INTRH + 1  
           If @CountTemp3 = 'prhab'                  
                Set @P_Count = @P_Count + 1  
           IF @CountTemp3 = 'crhab'                  
                Set @C_Count = @C_Count + 1  
        End  
          
        If @Procedure10 <> ''  
        Begin  
           IF Exists (Select Top 1 * From dbo.LU_CACS_INTMH_2002 Where (InterventionCode = @Procedure10))  
                   Set @INTMH = @INTMH + 1  
           Set @CountTemp3 = ''  
           Select @CountTemp3 = RehabIntervCate From dbo.LU_CACS_INTRH_2002 Where (CIHIIntervCode = @Procedure10)  
           If @CountTemp3 <> ''              
                Set @INTRH = @INTRH + 1  
           If @CountTemp3 = 'prhab'                  
                Set @P_Count = @P_Count + 1  
           IF @CountTemp3 = 'crhab'                  
                Set @C_Count = @C_Count + 1  
        End  
     
        -- Mental health step...  
           If @Intmh > @Intrh   
           Begin  
            -- More mental health than rehab...  
            -- The CACS is assigned above based on the main problem.  
                   Set @MAC = '19'  
            declare @CACS_Temp varchar(6)  
            select @CACS_Temp = CACS from dbo.LU_CACS_Mac19_2002 where DiagCode = @Diagnosis1 and IntervCode = @Procedure1  
            if @CACS_Temp is null  
                set @CACSCell = (case when @Procedure1 = '080004' then '1960'  
                                    when @Procedure1 = '080002' then '1961'  
                                    when @Procedure1 in ('6DA30DCBE', '6DA30DCCE', '6DA30DCDE', '6DA30DCJA', '6DA30DCRE', '6DA30DCXA', '6DA30DCZZ') then '1962'  
                                    when @Procedure1 = '990302M' then '1963'  
                                    when @Procedure1 in ('6DA30DFBE', '6DA30DFCE', '6DA30DFDE', '6DA30DFJA', '6DA30DFRE', '6DA30DFXA', '6DA30DFZZ') then '1964'  
                                    when @Procedure1 = '7SJ34PA' then '1965'  
                                    when @Procedure1 = '990303M' then '1966'  
                                    when @Procedure1 in ('2AZ08AB', '2AZ08AC', '2AZ08AH', '2AZ08AJ', '2AZ08YL', '2AZ08ZZ') then '1967'  
                                    when @Procedure1 = '083001' then '1968'  
                                    when @Procedure1 = '084801' then '1969'  
                                    when @Procedure1 = '990306M' then '1970'  
                                    when @Procedure1 = '990304M' then '1971'  
                                    when @Procedure1 = '6AA10CT' then '1972'  
                                    when @Procedure1 = '080003' then '1973'  
                                    when @Procedure1 = '080001' then '1974'  
                                    when @Procedure1 = '990309M' then '1975'  
                                    when @Procedure1 = '990308M' then '1976'  
                                    when @Procedure1 = '990307M' then '1977'  
                                    when @Procedure1 = '990305M' then '1978'  
                                    when @Procedure1 = '084402' then '1979'  
                                    else @CACSCell  
                                end)  
            else  
                set @CACSCell = @CACS_Temp  
  
                   GoTo FinalStep  
           End  
             
        -- Rehabilitation Step...  
           If @Intrh >= @Intmh and @Intrh <> 0  
           Begin  
            -- # of rehab >= # of mental health...  
                   Set @ReDiaBranch = ''  
      
                   Select @ReDiaBranch = ReDiaBranch   
            From LU_CACS_RHDX_2002   
            Where (ICDCode = @Diagnosis1)  
      
                   Set @CACSCell =                           
                   (Case  
                           When @ReDiaBranch = 'BB'  Then '9400'  
                           When @ReDiaBranch Like 'Cr%' Then '9410'  
                           When @ReDiaBranch = 'Cg'  Then '9420'  
                           When @ReDiaBranch = 'DS'  Then '9430'  
                           When @ReDiaBranch = 'EN'  Then '9440'  
                           When @ReDiaBranch = 'Mn'  Then '9450'  
                           When @ReDiaBranch = 'PP'  Then '9460'  
                           When @ReDiaBranch Like 'Re%' Then '9470'  
                           When @ReDiaBranch = 'Sk'  Then '9480'  
      
                           When @ReDiaBranch = 'Oth' Then '9590'  
      
                           When @ReDiaBranch = 'GU'  Then '9489'  
                           When @ReDiaBranch = 'IP'  Then '9499'  
                           When @ReDiaBranch Like 'IT%' Then '9511'  
                           When @ReDiaBranch Like 'MS%' Then '9519'  
                           When @ReDiaBranch = 'Ne'  Then '9529'  
                           When @ReDiaBranch Like 'NS%' Then '9539'  
                           When @ReDiaBranch = 'SO'  Then '9549'  
                           When @ReDiaBranch = 'Sp'  Then '9559'  
                           When @ReDiaBranch = 'Sy'  Then '9569'  
                           Else @CACSCell  
                   End)  
                   If @ReDiaBranch = 'ITIc' or @ReDiaBranch = 'ITNe'  
                Set @CACSCell = '9510'  
  
           If @CACSCell not Like '%0'  
           Begin  
                   Declare cur_FlagInterv cursor for  
                   Select RehabIntervCate From dbo.LU_CACS_INTRH_2002    
                   Where (CIHIIntervCode in (@Procedure1,@Procedure2,@Procedure3,@Procedure4,  
                   @Procedure5,@Procedure6,@Procedure7,@Procedure8,@Procedure9,@Procedure10))  
                     
                   Open cur_FlagInterv  
                   fetch next from cur_FlagInterv  
                   into @CountTemp3  
  
                   Set @TypeTemp = 9  
                     
                   While @@fetch_status = 0  
                   Begin  
                           If @CountTemp3 = 'assmnt' and @Intrh < 3   
                                   Set @TypeTemp = 1  
                           If @CountTemp3 = 'commling' and @Intrh < 6 and @TypeTemp > 1  
                                   Set @TypeTemp = 2  
          
                           If @CountTemp3 = 'prhab'   
                           Begin     
                                   If (@ReDiaBranch = 'GU' or @ReDiaBranch = 'MS')and @TypeTemp >= 3  Set @TypeTemp = 3                      
                                   If (@ReDiaBranch = 'IP' or @ReDiaBranch = 'Sy'or @ReDiaBranch like 'IT%' or @ReDiaBranch = 'Ne' or @ReDiaBranch like 'NS%') and @P_Count >= @C_Count and @TypeTemp > 2    
                                           set @TypeTemp = 3  
                                   If @ReDiaBranch = 'SO' and @Intrh > 2 and @P_Count >= @C_Count and @TypeTemp > 2  
                                           Set @TypeTemp = 3  
                                   If @ReDiaBranch = 'SO' and @Intrh <= 2 and @P_Count >= @C_Count and @TypeTemp > 3  
                                           Set @TypeTemp = 4  
                           End  
          
                           If @CountTemp3 = 'crhab'  
                           Begin   
                                   If (@ReDiaBranch = 'GU' or @ReDiaBranch like 'MS%') and @TypeTemp > 4 Set @TypeTemp = 3   
                                   If @ReDiaBranch like 'IT%' and @P_Count < @C_Count and @TypeTemp > 4  Set @TypeTemp = 2  
                                   If (@ReDiaBranch = 'SO' or @ReDiaBranch = 'Sy') and @TypeTemp > 4  Set @TypeTemp = 5  
                                   Set @TypeTemp =   
                                   (Case  
                                           When @Intrh > 1 and @TypeTemp > 4 Then 5  
                                           When @Intrh <= 1 and @TypeTemp > 5 Then 6         
                                           Else @TypeTemp  
                                   End)  
                           End                   
                           If @CountTemp3 = 'socialp' and @Intrh < 6 and @TypeTemp > 6                                     Set @TypeTemp = 7  
                           If @Intrh > 1 and @TypeTemp > 7  
                                   Set @TypeTemp = 8  
                                                     
                           fetch next from cur_FlagInterv  
                           into @CountTemp3  
                   End       
                             
                   Close cur_FlagInterv  
                   Deallocate cur_FlagInterv   
          
                   If @ReDiaBranch Like 'IT%' and @TypeTemp = 7  Set @TypeTemp = 5  
                   If @ReDiaBranch Like 'IT%' and @TypeTemp = 8  Set @TypeTemp = 6  
                   If @ReDiaBranch Like 'IT%' and @TypeTemp = 9  Set @TypeTemp = 7  
                   If @ReDiaBranch = 'Ne' and @TypeTemp = 8 Set @TypeTemp = 5  
                   If @ReDiaBranch Like 'NS%' and @TypeTemp = 8 Set @TypeTemp = 5  
                   If @ReDiaBranch Like 'NS%' and @TypeTemp = 9 Set @TypeTemp = 6  
                   If @ReDiaBranch = 'SO' and @TypeTemp = 8 Set @TypeTemp = 3  
                   If @ReDiaBranch = 'Sy' and @TypeTemp = 9 Set @TypeTemp = 8  
                                             
                   Set @CACSCell = Cast((Cast(@CACSCell as int) + @TypeTemp) as Varchar(5))  
                   If @ReDiaBranch = 'Sp'  
                           Set  @CACSCell =   
                           (Case   
                                   When @Age < 40 Then '9560'  
                                   When @Age >= 40 and @Age < 60 Then '9562'  
                                   When @Age >= 60 and @Age < 80 Then '9564'  
                                   When @Age >= 80 Then '9566'  
                        Else @CACSCell  
                           End)  
                   GoTO FinalStep  
           End  
  
           If @ReDiaBranch = 'Oth' Set @CACSCell = '9599'  
           GoTo FinalStep  
           End  
    End  
     
-- Age Group Assignment...  
   If @MAC = '1' and @ITFlag = 0  
   Begin  
           If @CACSBranch = '100'  
                   If @Age >= 0 and @Age < 65  
                           Set @CACSCell = '105'  
                   Else  
                           Set @CACSCell = '110'  
           If @CACSBranch = '160'   
                   Set @CACSCell = '165'  
  
           If @CACSBranch = '170'   
                   Set @CACSCell = '175'  
   End  
     
   If @MAC = '2' and @ITFlag = 0 and @CACSBranch = '200'   
           If @Age >= 0 and @Age < 45  
                   Set @CACSCell = '210'  
           Else  
                   Set @CACSCell = '215'  
  
   If @MAC = '3' and @CACSBranch = '300' and @ITFlag = 0  
           Set @CACSCell = '310'  
  
   If @MAC = '4' and @CACSBranch = '400'  
   Begin  
           If @ITFlag = 1 and @Age >= 18  
                   Set @CACSCell = '410'  
           If @ITFlag = 0 and @Age >= 65  
                   Set @CACSCell = '430'  
           If @ITFlag = 0 and @Age < 65  
                   Set @CACSCell = '420'  
   End  
  
   If @MAC = '5' and @ITFlag = 0   
   Set @CACSCell =   
           (Case @CACSBranch  
                   When '500' Then '510'  
                   When '570' Then '580'  
                   Else @CACSCell  
           End)  
             
   If @MAC = '6' and @CACSBranch = '600'  
   Begin  
           If @ITFlag = 1 and @Age >= 18  
                   Set @CACSCell = '610'  
           If @ITFlag = 0   
                   Set @CACSCell =   
                   (Case   
                           When @Age >= 45 then '640'  
                           When @Age >= 18 and @Age < 45 then '630'  
                           When @Age < 18 then '620'  
                Else @CACSCell  
                   End)  
   End  
  
   If @MAC = '7' and @ITFlag = 0 and @CACSBranch = '700'  
           Set @CACSCell = '710'  
  
   If @MAC = '8' and @ITFlag = 0   
   Begin  
           Set @CACSCell =   
           (Case @CACSBranch  
                   When '800' Then '810'  
                   When '840' Then '850'  
                   When '860' Then '870'  
                   Else @CACSCell  
           End)  
           If @CACSBranch = '820' and @Age < 18  
                   Set @CACSCell = '830'  
           If @CACSBranch = '820' and @Age >= 18  
                   Set @CACSCell = '835'  
   End  
  
   If @MAC = '8' and @CACSBranch = '820' and @ITFlag = 1 and @Age >= 18  
           set @CACSCell = '825'  
  
   If @MAC = '9' and @ITFlag = 0 and @CACSBranch = '900'  
           If @Age < 18  
                   Set @CACSCell = '910'  
           Else  
                   Set @CACSCell = '915'  
  
   If @MAC = '10' and @ITFlag = 0  
           Set @CACSCell =   
           (Case  
                   When @Age < 6 and @CACSBranch = '1000' Then '1010'  
                   When @Age >= 6 and @CACSBranch = '1000' Then '1015'  
                   When @Age >= 18 and @CACSBranch = '1020' Then '1025'  
                   Else @CACSCell  
           End)  
  
   If @MAC = '10' and @ITFlag = 1   
           Set @CACSCell =   
           (Case  
                   When @CACSBranch = '1000' and @Age >= 18 Then '1005'  
                   When @CACSBranch = '1020' and @Age >= 18 Then '1005'  
                   When @CACSBranch = '1020' and @Age < 18 Then '1000'  
                   Else @CACSCell  
           End)  
  
   If @MAC = '11' and @ITFlag = 0  
           Set @CACSCell =   
           (Case  
                   When @CACSBranch = '1100' and @Age < 18 Then '1110'  
                   When @CACSBranch = '1100' and @Age >= 18 Then '1115'  
                   When @CACSBranch = '1130' and @Age < 18 Then '1140'  
                   When @CACSBranch = '1130' and @Age >= 18 Then '1145'  
                   When @CACSBranch = '1150' and @Age < 18 Then '1160'  
                   When @CACSBranch = '1150' and @Age >= 18 Then '1165'  
                   Else @CACSCell  
           End)  
  
   If @MAC = '11' and @ITFlag = 1 and @CACSBranch = '1150' and @Age >= 18   
           Set @CACSCell = '1155'  
  
   If @MAC = '14' and @ITFlag = 0  
           Set @CACSCell =   
           (Case @CACSBranch  
                   When '1420' Then '1430'  
                   When '1490' Then '1495'  
                   Else @CACSCell  
           End)  
  
   If @MAC = '16' and @ITFlag = 0  
           Set @CACSCell =   
           (Case   
                   When @Age < 18 Then '1610'  
                   When @Age >= 18 and @Age < 65 Then '1615'  
                   When @Age >= 65 Then '1620'  
            Else @CACSCell  
           End)  
  
   If @MAC = '17' and @ITFlag = 0 and @CACSBranch = '1700'  
           Set @CACSCell = '1710'  
  
   If @MAC = '18' and @ITFlag = 0  
   Begin  
           If @CACSBranch = '1800'   
                   Set @CACSCell =   
                   (Case   
                           When @Age < 18 Then '1810'  
                           When @Age >= 18 Then '1815'  
                Else @CACSCell  
                   End)  
           If @CACSBranch = '1820' and @Age < 18 Set @CACSCell = '1830'  
           If @CACSBranch = '1820' and @Age >= 18 Set @CACSCell = '1835'  
   End  
     
   If @MAC = '20' and @ITFlag = 1 and @CACSBranch in ('2030','2035','2040','2045','2050','2055')  
           Set @CACSCell = '2000'  
  
   If @MAC = '20' and @ITFlag = 0 and @CACSBranch = '2000'  
           Set @CACSCell = '2005'  
  
FinalStep:  
--     Select @ACW = ACW, @CACSDescription = [Description] From LU_CACS_ACW_2002 Where CACS = @CACSCell  
    Select @ACW = ACW, @CACSDescription = [Description] From LU_CACS_ACW_2002 Where cast(CACS as decimal(5,1)) = cast(@CACSCell as decimal(5,1))
    -- 2003/06/19 Ticket 6939...Include "Atypical" calculation based on DispCode.
    set @ACW = 
        (case @DispositionCode
            when '01' then @ACW
            when '02' then 0.5225
            when '03' then round (@ACW * 0.7284, 4, 1)
            when '04' then round (@ACW * 0.7284, 4, 1)
            when '05' then round (@ACW * 0.7284, 4, 1)
            when '06' then round (@ACW * 3.1395, 4, 1)
            when '07' then round (@ACW * 2.2428, 4, 1)
            when '08' then round (@ACW * 1.9401, 4, 1)
            when '09' then round (@ACW * 1.9401, 4, 1)
            when '10' then round (@ACW * 1.7196, 4, 1)
            when '11' then 0.6248
            when '12' then @ACW
        end)
    -- Return numeric values...  
    set @MAC_Return = cast(@mac as int)  
    set @CACSCell_Return = cast(@CACSCell as decimal(5,1))  

	--Ticket 11969 Enhancement for CACS Auditing
	If isnull(@AbstractID, 0) > 0
	Begin
		Declare @AUMAC as Varchar(6)
		Declare @AUCACSCell as VarChar(20)
		Declare @AUACW as VarChar(20)
		Declare @AUAid as int
		SELECT @AUAid = Abstractid, @AUMAC = MAC, @AUCACSCell = CACSCell, @AUACW = ACW
		FROM AB_CACS where AbstractID = @AbstractID and OccurrenceNumber = 1 and CACS_Year = 2002
		If isnull(@AUAid, 0) > 0
		Begin
			If @AUMAC <> @MAC_Return
				Insert into AB_GrouperAudit Values (@AbstractID, 2002, 'MAC', @AUMAC, @MAC_Return, GetDate())
			If @AUCACSCell <> @CACSCell_Return
				Insert into AB_GrouperAudit Values (@AbstractID, 2002, 'CACSCell', @AUCACSCell, @CACSCell_Return, GetDate())
			If @AUACW <> @ACW
				Insert into AB_GrouperAudit Values (@AbstractID, 2002, 'ACW', @AUACW, @ACW, GetDate())
		End
	End

    -- For batch processing use, update the CACS table here.  Otherwise update it from vb.  
   If isnull(@AbstractID, 0) > 0  
   Begin  
           Delete AB_CACS where Abstractid = @Abstractid and CACS_Year = 2002 and OccurrenceNumber = 1  
           If IsNull(@MAC, '') <> ''  
           Begin  
                   insert into [dbo].[AB_CACS] (AbstractID, OccurrenceNumber, CACS_Year, MAC, CACSCell, ACW, CACSDescription, InterventionCode) values   
                   (@AbstractID, 1, 2002, @MAC_Return, @CACSCell_Return, @ACW, @CACSDescription, @IntervCode)  
           End  
   End  
  
Return 0  





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE PROCEDURE [CACS_Grouping_2003]
    @ICDType varchar(1),  
    @AnesTech1 varchar(1),  
    @Age int,  
    @Gender varchar(1),  
    @Diagnosis1 varchar(10),  
    @Procedure1 varchar(10),  
    @Procedure2 varchar(10),  
    @Procedure3 varchar(10),  
    @Procedure4 varchar(10),  
    @Procedure5 varchar(10),  
    @Procedure6 varchar(10),  
    @Procedure7 varchar(10),  
    @Procedure8 varchar(10),  
    @Procedure9 varchar(10),  
    @Procedure10 varchar(10),  
    @EncounterNumber varchar(50),  
    @MAC_Return int output,  
    @CACSCell_Return decimal(5,1) output,     
    @ACW decimal(6,4) output,  
    @CACSDescription varchar(150) output,  
    @AbstractID int,  
    @IntervCode int,             -- Added...New, 2002/06/25, it is the code value of @Procedure1 above.  
    @DispositionCode varchar(2),  -- Added...new, 2002/06/25, the CIHI value. 
    -- Added for the new 2003 CACS specs, 2004/02/20
    @AgeCode varchar(1),    -- CIHI value
    @Program varchar(12),   -- CIHI value
    @OOH1 varchar(12),    -- CIHI value
    @OOH2 varchar(12),    -- CIHI value
    @OOH3 varchar(12),    -- CIHI value
    @OOH4 varchar(12),    -- CIHI value
    @OOH5 varchar(12),    -- CIHI value
    @OOH6 varchar(12),    -- CIHI value
    @OOH7 varchar(12),    -- CIHI value
    @OOH8 varchar(12),    -- CIHI value
    @OOH9 varchar(12),    -- CIHI value
    @OOH10 varchar(12),    -- CIHI value
    @Status1 varchar(12),    -- CIHI value
    @Status2 varchar(12),    -- CIHI value
    @Status3 varchar(12),    -- CIHI value
    @Status4 varchar(12),    -- CIHI value
    @Status5 varchar(12),    -- CIHI value
    @Status6 varchar(12),    -- CIHI value
    @Status7 varchar(12),    -- CIHI value
    @Status8 varchar(12),    -- CIHI value
    @Status9 varchar(12),    -- CIHI value
    @Status10 varchar(12),    -- CIHI value
    @Location1 varchar(12),    -- CIHI value
    @Location2 varchar(12),    -- CIHI value
    @Location3 varchar(12),    -- CIHI value
    @Location4 varchar(12),    -- CIHI value
    @Location5 varchar(12),    -- CIHI value
    @Location6 varchar(12),    -- CIHI value
    @Location7 varchar(12),    -- CIHI value
    @Location8 varchar(12),    -- CIHI value
    @Location9 varchar(12),    -- CIHI value
    @Location10 varchar(12),    -- CIHI value
    @Extent1 varchar(12),    -- CIHI value
    @Extent2 varchar(12),    -- CIHI value
    @Extent3 varchar(12),    -- CIHI value
    @Extent4 varchar(12),    -- CIHI value
    @Extent5 varchar(12),    -- CIHI value
    @Extent6 varchar(12),    -- CIHI value
    @Extent7 varchar(12),    -- CIHI value
    @Extent8 varchar(12),   -- CIHI value
    @Extent9 varchar(12),    -- CIHI value
    @Extent10 varchar(12)    -- CIHI value
as  
    
--     print '@Procedure1: ' + @Procedure1 
--     print '@Diagnosis1: ' + @Diagnosis1 
--     print '@AbstractID: ' + cast(@AbstractID as varchar(10))
--     print '@Gender = ' + @Gender
--     print '-----------------'
    declare @CACSBranch varchar(4)  
    declare @DPGNumber varchar(16)   
    declare @ICode varchar(50)
    declare @IAttribStatusCIHI varchar(50)
    declare @IAttribLocationCIHI varchar(50)
    declare @IAttribExtentCIHI varchar(50)
    declare @IOOHIndicatorCIHI varchar(50)
    declare @CACSCell varchar(6)  
    declare @IProgramCIHI varchar(50)
    declare @RehabCategory varchar(10)
    declare @FilteredStatus varchar(2)
    declare @FilteredExtent varchar(2)
    declare @FilteredProgram varchar(2)
    declare @FilteredLocation varchar(12)
    declare @CACS_Temp varchar(10)
    declare @MHIntType varchar(30)
    declare @MajorInvestTech varchar(10)
    declare @MinorInvestTech int  
    declare @Mac int  
    declare @Occ int
    declare @RehabCount int
    declare @MentHlthCount int
    declare @PhysicalCount int
    declare @CognitiveCount int
    declare @InterventionCount int
    -- NB: Incoming Parameters are CIHI values.  
    set @AnesTech1   = isnull(@AnesTech1, '')
    set @Diagnosis1  = isnull(@Diagnosis1, '')
    set @Procedure1  = isnull(@Procedure1, '')
    set @Procedure2  = isnull(@Procedure2, '')
    set @Procedure3  = isnull(@Procedure3, '')
    set @Procedure4  = isnull(@Procedure4, '')
    set @Procedure5  = isnull(@Procedure5, '')
    set @Procedure6  = isnull(@Procedure6, '')
    set @Procedure7  = isnull(@Procedure7, '')
    set @Procedure8  = isnull(@Procedure8, '')
    set @Procedure9  = isnull(@Procedure9, '')
    set @Procedure10 = isnull(@Procedure10, '')
    set @OOH1  = isnull(@OOH1, '')
    set @OOH2  = isnull(@OOH2, '')
    set @OOH3  = isnull(@OOH3, '')
    set @OOH4  = isnull(@OOH4, '')
    set @OOH5  = isnull(@OOH5, '')
    set @OOH6  = isnull(@OOH6, '')
    set @OOH7  = isnull(@OOH7, '')
    set @OOH8  = isnull(@OOH8, '')
    set @OOH9  = isnull(@OOH9, '')
    set @OOH10  = isnull(@OOH10, '')
    set @Status1  = isnull(@Status1, '')
    set @Status2  = isnull(@Status2, '')
    set @Status3  = isnull(@Status3, '')
    set @Status4  = isnull(@Status4, '')
    set @Status5  = isnull(@Status5, '')
    set @Status6  = isnull(@Status6, '')
    set @Status7  = isnull(@Status7, '')
    set @Status8  = isnull(@Status8, '')
    set @Status9  = isnull(@Status9, '')
    set @Status10  = isnull(@Status10, '')
    set @Location1  = isnull(@Location1, '')
    set @Location2  = isnull(@Location2, '')
    set @Location3  = isnull(@Location3, '')
    set @Location4  = isnull(@Location4, '')
    set @Location5  = isnull(@Location5, '')
    set @Location6  = isnull(@Location6, '')
    set @Location7  = isnull(@Location7, '')
    set @Location8  = isnull(@Location8, '')
    set @Location9  = isnull(@Location9, '')
    set @Location10  = isnull(@Location10, '')
    set @Extent1  = isnull(@Extent1, '')
    set @Extent2  = isnull(@Extent2, '')
    set @Extent3  = isnull(@Extent3, '')
    set @Extent4  = isnull(@Extent4, '')
    set @Extent5  = isnull(@Extent5, '')
    set @Extent6  = isnull(@Extent6, '')
    set @Extent7  = isnull(@Extent7, '')
    set @Extent8  = isnull(@Extent8, '')
    set @Extent9  = isnull(@Extent9, '')
    set @Extent10  = isnull(@Extent10, '')
    set @Age = (case @AgeCode when 'Y' then @Age else 0 end)
    set @MAC = ''  
    set @CACSCell = ''  
    set @CACSBranch = ''  
    set @MajorInvestTech = ''
    set @MinorInvestTech = 0  
    set @PhysicalCount = 0
    set @CognitiveCount = 0
    set @RehabCount = 0
    set @MentHlthCount = 0
    -- Assign MAC based on Main Problem...  
    if @Diagnosis1 = ''  
    begin  
        -- Ungroupable when no diagnosis code.
        set @CACSCell = '9999'  
        set @MAC = '99'  
        goto FinalStep  
    end  
    else  
    begin  
        select @MAC = MAC, @CACSBranch = CACSBranch  
        from dbo.LU_CACS_I10DX_2003
        where (ICD10CACode = @Diagnosis1)    
      
        -- Consider it ungroupable if the diagnosis code is not in the CACS table  
        if isnull(@MAC, '') = ''
        begin  
            set @CACSCell = '9999'  
            set @MAC = '99'  
            goto FinalStep  
        end
        set @CACSCell = @CACSBranch  
    end  
    -- Check for Dead On Arrival (DOA) or Left without being seen...  
    set @CACSCell =   
        (case   
            when @DispositionCode = '11' then '9900' -- DOA  
            when @DispositionCode = '02' then '9905' -- Left without being seen  
            else @CACSCell  
        end)
    if @CACSCell in ('9900','9905') goto FinalStep  
    truncate table LU_CACS_Temp_2003
    
    if @Procedure1 <> ''
        insert LU_CACS_Temp_2003 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (1, @Procedure1, @Status1, @Extent1, @Location1, @OOH1, @Program)
    if @Procedure2 <> ''
        insert LU_CACS_Temp_2003 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (2, @Procedure2, @Status2, @Extent2, @Location2, @OOH2, @Program)
    if @Procedure3 <> ''
        insert LU_CACS_Temp_2003 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (3, @Procedure3, @Status3, @Extent3, @Location3, @OOH3, @Program)
    if @Procedure4 <> ''
        insert LU_CACS_Temp_2003 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (4, @Procedure4, @Status4, @Extent4, @Location4, @OOH4, @Program)
    if @Procedure5 <> ''
        insert LU_CACS_Temp_2003 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (5, @Procedure5, @Status5, @Extent5, @Location5, @OOH5, @Program)
    if @Procedure6 <> ''
        insert LU_CACS_Temp_2003 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (6, @Procedure6, @Status6, @Extent6, @Location6, @OOH6, @Program)
    if @Procedure7 <> ''
        insert LU_CACS_Temp_2003 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (7, @Procedure7, @Status7, @Extent7, @Location7, @OOH7, @Program)
    if @Procedure8 <> ''
        insert LU_CACS_Temp_2003 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (8, @Procedure8, @Status8, @Extent8, @Location8, @OOH8, @Program)
    if @Procedure9 <> ''
        insert LU_CACS_Temp_2003 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (9, @Procedure9, @Status9, @Extent9, @Location9, @OOH9, @Program)
    if @Procedure10 <> ''
        insert LU_CACS_Temp_2003 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (10, @Procedure10, @Status10, @Extent10, @Location10, @OOH10, @Program)
    
    -- Filter the data...
    declare cur_Interv cursor local fast_forward for  
        select 
            Occ, -- i.IntervOccurrence,
            IntervCode,        -- i.IntervCode,
            IntervAttStatus,        -- i.IntervAttribStatus,
            IntervAttLocation,        -- i.IntervAttribLocation,
            IntervAttExtent,        -- i.IntervAttribExtent,
            OOHIndicator,        -- i.IntervOOHIndicator,
            ProgramArea         -- a.Program
        from LU_CACS_Temp_2003
        order by Occ
    open cur_Interv 
    while (1 = 1) 
    begin  
        fetch next from cur_Interv  
        into @Occ, @ICode, @IAttribStatusCIHI, @IAttribLocationCIHI, 
            @IAttribExtentCIHI, @IOOHIndicatorCIHI, @IProgramCIHI
    
        if (@@fetch_status <> 0) break 
    
        if isnull(@IOOHIndicatorCIHI, '') = 'Y' or isnull(@IAttribStatusCIHI, '') = 'A'
            update LU_CACS_Temp_2003
            set IgnoreData = 'Y'
    
            where occ = @Occ
        else
        begin
            -- Filter the IntervAttribStatus...
            if not exists (select * from LU_CACS_CACSTA_2003 where CCICode = @ICode and isnull(CCIStatusAttribute, '') = @IAttribStatusCIHI)
                set @FilteredStatus = ''
            else
                set @FilteredStatus = @IAttribStatusCIHI
            -- Filter the IntervAttribExtent...
            if not exists (select * from LU_CACS_CACEXT_2003 where CCICode = @ICode and isnull(CCIExtentAttribute, '') = @IAttribExtentCIHI)
                set @FilteredExtent = ''
            else
                set @FilteredExtent = @IAttribExtentCIHI
            -- Filter the IntervAttriLocation
            if not exists (select * from LU_CACS_DPGLOC_2003 where CCICode = @ICode and isnull(CCILocationAttribute, '') = @IAttribLocationCIHI)
                set @FilteredLocation = ''
            else
                set @FilteredLocation = @IAttribLocationCIHI
            -- Filter the Program...
            if not exists (select * from LU_CACS_CACPGM_2003 where CCICode = @ICode and isnull(ProgramArea, '') = @IProgramCIHI)
                set @FilteredProgram = ''
            else
                set @FilteredProgram = @IProgramCIHI
    
            update LU_CACS_Temp_2003
            set FilteredAttStatus = @FilteredStatus, 
                FilteredAttExtent = @FilteredExtent, 
                FilteredProgramArea = @FilteredProgram, 
                FilteredAttLocation = @FilteredLocation
            where Occ = @Occ
    
            -- Compute the MentalHealth count...
            if exists (select * from LU_CACS_INTMHCCI_2003 where CCICode = @ICode and isnull(CCIStatusAttribute, '') = @FilteredStatus and isnull(ProgramArea, '') = @FilteredProgram and isnull(CCIExtentAttribute, '') = @FilteredExtent)
            begin
                set @MentHlthCount = @MentHlthCount + 1
                update LU_CACS_Temp_2003 set IsMentalHealth = 'Y' where Occ = @Occ
            end
    
            -- Compute the Rehab count...
            set @RehabCategory = isnull((select RehabInterventionCategory from LU_CACS_INTRHCCI_2003 where CCICode = @ICode and isnull(CCIStatusAttribute, '') = @FilteredStatus and isnull(ProgramArea, '') = @FilteredProgram), '')
            if @RehabCategory <> ''
            begin
                set @RehabCount = @RehabCount + 1
                update LU_CACS_Temp_2003 
                set RehabCategory = @RehabCategory,
                    IsRehab = 'Y' 
                where Occ = @Occ        
            end
    
            if @RehabCategory = 'prhab'                  
                set @PhysicalCount = @PhysicalCount + 1  
            else if @RehabCategory = 'crhab'                  
                set @CognitiveCount = @CognitiveCount + 1 
        end
    end 
    
    close cur_Interv  
    deallocate cur_Interv  
    -- Retrieve the InterventionCount...
    select @InterventionCount = count(*) from LU_CACS_Temp_2003 --where isnull(IgnoreData, '') <> 'Y'
--     print '@InterventionCount = ' + cast(@InterventionCount as varchar(500))
    -- Retrieve info for Day Procedure...
    set @FilteredLocation = ''
    set @ICode = ''
    set @DPGNumber = ''
    -- Examine patient abstract for any Day Procedure in occurrence one...
    select 
        @FilteredLocation = isnull(FilteredAttLocation, ''),
        @ICode = isnull(IntervCode, '')
    from LU_CACS_Temp_2003 
    where Occ = 1 
    and isnull(IgnoreData, '') <> 'Y'
    -- Retrieve the DPG cell.
    select 
        @DPGNumber = isnull(DPGNumber, '')
    from dbo.LU_CACS_DPGCCI_2003
    where CCICode = @ICode
    and isnull(CCILocationAttribute, '') = @FilteredLocation 
    -- Is it Day Procedure???
    if (isnull(@DPGNumber, '') <> '')  
    begin  
--         print '@FilteredLocation = ' + cast(@FilteredLocation as varchar(500))
--         print '@ICode = ' + cast(@ICode as varchar(500))
--         print '@DPGNumber = ' + cast(@DPGNumber as varchar(500))
--         print '@AnesTech1 = ' + cast(@AnesTech1 as varchar(500))
        -- Further split the DPG cell
        if isnull(@DPGNumber, '') <> ''  
        begin  
--             print 'BEFORE: @CACSCell = ' + cast(@CACSCell as varchar(500))
            set @CACSCell = @DPGNumber  
            if @DPGNumber in ('1','15','48','50','52','65')  
                set @CACSCell =   
                    (Case  
                        when @AnesTech1 >= '1' And @AnesTech1 <= '4' then @CACSCell + '.1'  
                        when @AnesTech1 >= '5' And @AnesTech1 <= '6' then @CACSCell + '.2'  
                        when @AnesTech1 >= '7' And @AnesTech1 <= '9' then @CACSCell + '.3'  
                        else @CACSCell  
                    end)  
--             print 'AFTER: @CACSCell = ' + cast(@CACSCell as varchar(500))
            Goto FinalStep  
        end  
    end  
    -- Rehab and Mental Health...
    if exists (select * from LU_CACS_Temp_2003 where isnull(IgnoreData, '') <> 'Y')  
    Begin
--         print 'inside: Rehab and Mental Health...'
--         print '@MentHlthCount = ' + cast(@MentHlthCount as varchar(10))
--         print '@RehabCount = ' + cast(@RehabCount as varchar(10))
        if @MentHlthCount > @RehabCount
        begin
--             print 'inside: MentHlthCount > RehabCount'
            -- More MentalHealth than Rehab...
            set @MAC = '19'
            set @MHIntType = ''
            set @CACS_Temp = ''
            set @ICode = ''
            -- Find the first CACS for mental health intervention code and intervention type.
            declare cur_Mental cursor local fast_forward for
                select IntervCode, FilteredAttStatus, FilteredAttExtent, FilteredProgramArea
                from LU_CACS_Temp_2003
                where isnull(IsMentalHealth, '') = 'Y'
                and isnull(IgnoreData, '') <> 'Y'
                order by Occ
            open cur_Mental
            While (1 = 1) 
            begin  
                -- Loop through all mental health interventions and get the first availble CACS
                fetch next from cur_Mental  
                into @ICode, @FilteredStatus, @FilteredExtent, @FilteredProgram
                if (@@fetch_status <> 0) break 
    
                set @MHIntType = isnull((
                    select MentalHealthInterventionType 
                    from LU_CACS_INTMHCCI_2003 
                    where CCICode = @ICode 
                    and isnull(CCIStatusAttribute, '') = @FilteredStatus
                    and isnull(CCIExtentAttribute, '') = @FilteredExtent
                    and isnull(ProgramArea, '') = @FilteredProgram), '')
                -- Once the MentalHealthInterventionType is found, get the CACS. Otherwise, get the next mental health intervention.
                if isnull(@MHIntType, '') <> ''
                begin
                    -- Retrieve the MAC 19 CACS from the table, otherwise assign the default value for this MentalHealthInterventionType.
                    set @CACS_Temp = isnull((select CACS from dbo.LU_CACS_Mac19_2003 where ICD10CACode = @Diagnosis1 and IntervCode = @ICode and isnull(MHIntType, '') = @MHIntType), '')
                    if isnull(@CACS_Temp, '') = ''
                        set @CACSCell =  
                            (case  
                                when @MHIntType = 'LEGAL ASSESSMENT FULL DAY' then '1961'  
                                when @MHIntType = 'PSYCHOTHERAPY COUPLE' then '1962'  
                                when @MHIntType = 'INITIAL ASSESSMENT MH' then '1963'  
                                when @MHIntType = 'PSYCHOTHERAPY FAMILY'then '1964'  
                                when @MHIntType = 'PATIENT SPECIFIC HEARINGS' then '1965'  
                                when @MHIntType = 'RE-ASSESSMENT MG' then '1966'
                                when @MHIntType = 'SCREENING ASSESSMENT MH' then '1967'  
                                when @MHIntType = 'MED ADMIN/MANAGEMENT' then '1968'  
                                when @MHIntType = 'PSYCHOTHERAPY IND' then '1969'  
                                when @MHIntType = 'SERVICE PLANNING' then '1971'  
                                when @MHIntType = 'CRISIS INTERVENTION CALL' then '1972'  
                                when @MHIntType = 'LEGAL ASSESSMENT HALF DAY' then '1974'  
                                when @MHIntType = 'COUNSELLING EXT' then '1975'  
                                when @MHIntType = 'COUNSELLING INT' then '1976'
                                when @MHIntType = 'COUNSELLING BRIEF' then '1977'  
                                when @MHIntType = 'EDUCATION MH' then '1978'  
                                when @MHIntType = 'PSYCHOTHERAPY GROUP' then '1979'  
                                else @CACSCell
                            end)
                    else
                        set @CACSCell = @CACS_Temp
                    -- Exit loop...CACS found
                    break
                end
            end 
            close cur_Mental
            deallocate cur_mental
            goto FinalStep  
        end
        else if @RehabCount >= @MentHlthCount and @RehabCount <> 0
        begin
            -- print 'Inside: RehabCount >= MentHlthCount and RehabCount <> 0'
            -- Rehab >= MentalHealth...
            declare cur_Rehab cursor local fast_forward for
                select IntervCode, FilteredAttStatus, FilteredAttLocation, FilteredAttExtent, FilteredProgramArea, RehabCategory
                from LU_CACS_Temp_2003
                where isnull(IsRehab, '') = 'Y'
                and isnull(IgnoreData, '') <> 'Y'
                order by Occ
            open cur_Rehab
            
            while (1 = 1)
            begin
                fetch next from cur_Rehab
                into @ICode, @FilteredStatus, @FilteredLocation, @FilteredExtent, @FilteredProgram, @RehabCategory
                if (@@fetch_status <> 0) break
--             print '@RehabCategory = ' + @RehabCategory + '  ' + cast(len(@RehabCategory) as varchar(10))
--             The LU_CACS_RH_Diagnosis_2003 and LU_CACS_RH_Intervention_2003 are built from the html.
--             The following CCICode is not in the html but added manually to the table:
--             6AA30ZZZZ, 6KA50MD, 6KA50ME, 6KA50MP, 6KA50MR, 6KA50MZ.
--             They belong to the Cognitive Rehabilitation Interventions.
--             Wonder what other CCICode is missing from the html...
                set @CACS_Temp = isnull((
                    select d.CACS
                    from LU_CACS_RH_Diagnosis_2003 d
                        join LU_CACS_RH_Intervention_2003 i
                            on d.CACS = i.CACS
                    where d.ICD10CACode = @Diagnosis1
                    and i.CCICode = @ICode
                    and isnull(i.CCIStatus, '') = @FilteredStatus
--                     and isnull(i.CCILocation, '') = @FilteredLocation
--                     and isnull(i.CCIExtent, '') = @FilteredExtent
                    and isnull(i.CCIProgram, '') = @FilteredProgram), '')
--                 print '@Diagnosis1 = ' + @Diagnosis1 
--                 print '@ICode = ' + @ICode 
--                 print '@FilteredStatus = ' + @FilteredStatus 
--                 print '@FilteredLocation = ' + @FilteredLocation 
--                 print '@FilteredExtent = ' + @FilteredExtent 
--                 print '@FilteredProgram = ' + @FilteredProgram 
--                 print '@CACS_Temp = ' + @CACS_Temp 
                if isnull(@CACS_Temp, '') <> ''
                begin
                    -- Exit loop upon CACS found...
                    if @CACS_Temp in ('9400','9410','9420','9430','9440','9450',
                        '9460','9470','9480','9492','9510','9522') break
                    if @CACS_Temp = '9490' and @RehabCount < 3 break
                    if @CACS_Temp = '9496' and @RehabCount < 6  break
                    if @CACS_Temp = '9497' and @RehabCount > 1  break
                    if @CACS_Temp = '9498' and @RehabCount <= 1  break
                    if @CACS_Temp = '9500' and @RehabCount < 3  break
                    if @CACS_Temp = '9501' and @RehabCount < 6  break
                    if @CACS_Temp = '9502' and @PhysicalCount >= @CognitiveCount break
                    if @CACS_Temp = '9504' and @RehabCount > 1  break
                    if @CACS_Temp = '9506' and @RehabCount < 6  break
                    if @CACS_Temp = '9507' and @RehabCount > 1  break
                    if @CACS_Temp = '9508' and @RehabCount <= 1  break
                    if @CACS_Temp = '9512' and @RehabCount < 3  break
                    if @CACS_Temp = '9513' and @RehabCategory = 'commling' and @RehabCount < 6  break
                    if @CACS_Temp = '9513' and @RehabCategory = 'crhab' break
                    if @CACS_Temp = '9514' and @PhysicalCount >= @CognitiveCount  break
                    if @CACS_Temp = '9516' and @InterventionCount < 6  break
                    if @CACS_Temp = '9517' and @RehabCount > 1  break
                    if @CACS_Temp = '9518' and @RehabCount <= 1  break
                    if @CACS_Temp = '9520' and @RehabCount < 3  break
                    if @CACS_Temp = '9521' and @RehabCount < 6  break
                    if @CACS_Temp = '9526' and @RehabCount < 6  break
                    if @CACS_Temp = '9527' and @RehabCount > 1  break
                    if @CACS_Temp = '9528' and @RehabCount <= 1  break
                    if @CACS_Temp = '9530' and @RehabCount < 3  break
                    if @CACS_Temp = '9531' and @RehabCount < 6  break
                    if @CACS_Temp = '9532' and @PhysicalCount >= @CognitiveCount  break
                    if @CACS_Temp = '9534' and @RehabCategory = 'crhab' and @RehabCount < 1  break
                    if @CACS_Temp = '9534' and @RehabCategory = 'orhab' and  @RehabCount < 1  break
                    if @CACS_Temp = '9535' and @RehabCount <= 1  break
                    if @CACS_Temp = '9536' and @RehabCount < 6  break
                    if @CACS_Temp = '9534' and @RehabCount < 3  break
                    if @CACS_Temp = '9538' and @RehabCount <= 1  break
                    if @CACS_Temp = '9540' and @RehabCount < 3  break
                    if @CACS_Temp = '9541' and @RehabCount < 6  break
                    if @CACS_Temp = '9542' and @PhysicalCount >= @CognitiveCount  break
                    if @CACS_Temp = '9544' and @RehabCategory = 'crhab' and @RehabCount > 1  break
                    if @CACS_Temp = '9544' and @RehabCategory = 'orhab' and  @RehabCount > 1  break
                    if @CACS_Temp = '9545' and @RehabCategory = 'crhab' and @RehabCount <= 1  break
                    if @CACS_Temp = '9545' and @RehabCategory = 'orhab' and  @RehabCount <= 1  break
                    if @CACS_Temp = '9546' and @RehabCount < 6  break
                    if @CACS_Temp = '9550' and @RehabCount < 3  break
                    if @CACS_Temp = '9551' and @RehabCount < 6  break
                    if @CACS_Temp = '9552' and @RehabCategory = 'prhab' and @PhysicalCount >= @CognitiveCount and @RehabCount > 2  break
                    if @CACS_Temp = '9552' and @RehabCategory = 'orhab' and @RehabCount > 1  break
                    if @CACS_Temp = '9553' and @PhysicalCount >= @CognitiveCount and @RehabCount <= 2  break
                    if @CACS_Temp = '9556' and @RehabCount < 6  break
                    if @CACS_Temp = '9558' and @RehabCount <= 1  break
                    if @CACS_Temp = '9560'
                    begin 
                        set @CACS_Temp = 
                            (case
                                when @Age < 40 then '9560'
                                when @Age < 60 then '9562'
                                when @Age < 80 then '9564'
                                else '9566'
                            end)
                        break
                    end
                    if @CACS_Temp = '9570' and @RehabCount < 3  break
                    if @CACS_Temp = '9571' and @RehabCount < 6  break
                    if @CACS_Temp = '9572' and @PhysicalCount >= @CognitiveCount break
                    if @CACS_Temp = '9576' and @RehabCount < 6  break
                end
            end
            -- Keep the new CACS.
            if isnull(@CACS_Temp, '') <> ''
                set @CACSCell = @CACS_Temp
            close cur_Rehab
            deallocate cur_Rehab
--             print '@CACSCell = ' + cast (@CACSCell as varchar(20))
--             print '@CACS_Temp = ' + cast (@CACS_Temp as varchar(20))
--             print '@CACSCell = ' + cast (@CACSCell as varchar(20))
--             print 'Exiting... RehabCount >= MentHlthCount and RehabCount <> 0'
            goto FinalStep  
        end  
    end  
    -- Identify the Standard Investigative Technologies
    if exists (select * from LU_CACS_INVTECHCCI_2003
                where CCICode in (select IntervCode from LU_CACS_Temp_2003 where isnull(OOHIndicator, '') <> 'Y'))
        set @MinorInvestTech = 1           
    -- Assign diagnosis driven CACS based on interventions, gender and age.
    if @MAC = '1' 
    begin
        if @CACSCell = '100' and @MinorInvestTech = 0
            if @Age < 65
                set @CACSCell = '105'
            else
                set @CACSCell = '110'
        if @CACSCell = '160' and @MinorInvestTech = 0
            set @CACSCell = '165'
        if @CACSCell = '170' and @MinorInvestTech = 0
            set @CACSCell = '175'
        goto FinalStep
    end
    if @MAC = '2'
    begin
        if @CACSCell = '200' and @MinorInvestTech = 0
            if @Age < 45
                set @CACSCell = '210'
            else
                set @CACSCell = '215'
        goto FinalStep
    end
         
    if @MAC = '3'
    begin
--     print 'mac 3'
--     print '@MinorInvestTech = ' + cast (@MinorInvestTech as varchar(10))
        if @CACSCell = '300' and @MinorInvestTech = 0 
            set @CACSCell = '310'  
        goto FinalStep
    end
    if @MAC = '4' 
    begin  
        if @CACSCell = '400'
            if @MinorInvestTech = 1
            begin 
                if @Age >= 18
                    set @CACSCell = '410'
            end
            else
                if @Age < 65
                    set @CACSCell = '420'
                else
                    set @CACSCell = '430'
        goto FinalStep
    end  
    if @MAC = '5'
    begin
        if @CACSCell = '500' and @MinorInvestTech = 0
            set @CACSCell = '510'
        if @CACSCell = '570' and @MinorInvestTech = 0
            set @CACSCell = '580'
        goto FinalStep
    end
    if @MAC = '6' and @CACSBranch = '600'  
    begin  
        if @MinorInvestTech = 1 and @Age >= 18  
            set @CACSCell = '610'  
        if @MinorInvestTech = 0   
            set @CACSCell =   
                (Case   
                    when @Age < 18 then '620'  
                    when @Age >= 18 and @Age < 45 then '630'  
                    when @Age >= 45 then '640'  
                    else @CACSCell  
                end)  
        goto FinalStep
    end  
    if @MAC = '7' and @MinorInvestTech = 0
    begin  
        set @CACSCell = '710'  
        goto FinalStep
    end
  
    if @MAC = '8'  
    Begin
        if @CACSCell = '800' and @MinorInvestTech = 0
            set @CACSCell = '810'
        else if @CACSCell = '820' and @MinorInvestTech = 1 and @Age >= 18
            set @CACSCell = '825'
        else if @CACSCell = '820' and @MinorInvestTech = 0 and @Age < 18
            set @CACSCell = '830'
        else if @CACSCell = '820' and @MinorInvestTech = 0 and @Age >= 18
            set @CACSCell = '835'
        else if @CACSCell = '840' and @MinorInvestTech = 0 
            set @CACSCell = '850'
        else if @CACSCell = '860' and @MinorInvestTech = 0 
            set @CACSCell = '870'
        goto FinalStep
    end  
    if @MAC = '9' and @MinorInvestTech = 0 and @CACSBranch = '900'
    begin  
        if @Age < 18  
            set @CACSCell = '910'  
        else  
            set @CACSCell = '915'
        goto FinalStep
    end  
  
    if @MAC = '10' 
    begin
--         print 'Inside mac 10....'
--         print '@mac = ' + cast(@MAC_Return as varchar(100))
--         print '@CACSCell = ' + cast(@CACSCell as varchar(100))
--         print '@MinorInvestTech = ' + cast(@MinorInvestTech as varchar(100))
--         print '@Age = ' + cast(@Age as varchar(100))
--         print ''
        if @CACSCell = '1000' and @MinorInvestTech = 1 and @Age >= 18
            set @CACSCell = '1005'
        else if @CACSCell = '1000' and @MinorInvestTech = 0 and @Age < 6
            set @CACSCell = '1010'
        else if @CACSCell = '1000' and @MinorInvestTech = 0 and @Age >= 6
            set @CACSCell = '1015'
        else if @CACSCell = '1020' and @MinorInvestTech = 1 and @Age < 18
            set @CACSCell = '1000'
        else if @CACSCell = '1020' and @MinorInvestTech = 1 and @Age >= 18
            set @CACSCell = '1005' 
        else if @CACSCell = '1020' and @MinorInvestTech = 0 and @Age >= 18
            set @CACSCell = '1025' 
        goto FinalStep
    end
    if @MAC = '11'
    begin
--         print 'Inside mac 11....'
--         print '@mac = ' + cast(@MAC_Return as varchar(100))
--         print '@CACSCell = ' + cast(@CACSCell as varchar(100))
--         print '@MinorInvestTech = ' + cast(@MinorInvestTech as varchar(100))
--         print '@Age = ' + cast(@Age as varchar(100))
--         print '@Gender = ' + @Gender
--         print ''
        if @CACSCell = '1100' and @MinorInvestTech = 0 and @Age < 18 and @Gender = 'F'
            set @CACSCell = '1110'
        else if @CACSCell = '1100' and @MinorInvestTech = 0 and @Age >= 18 and @Gender = 'F'
            set @CACSCell = '1115'
        else if @CACSCell = '1130' and @MinorInvestTech = 0 and @Age < 18 and @Gender = 'F'
            set @CACSCell = '1110'
        else if @CACSCell = '1130' and @MinorInvestTech = 0 and @Age >= 18 and @Gender = 'F'
            set @CACSCell = '1115'
        else if @CACSCell = '1100' and @MinorInvestTech = 0 and @Age < 18 and @Gender = 'M'
            set @CACSCell = '1140'
        else if @CACSCell = '1100' and @MinorInvestTech = 0 and @Age >= 18 and @Gender = 'M'
            set @CACSCell = '1145'
        else if @CACSCell = '1130' and @MinorInvestTech = 0 and @Age < 18 and @Gender = 'M'
            set @CACSCell = '1140'
        else if @CACSCell = '1130' and @MinorInvestTech = 0 and @Age >= 18 and @Gender = 'M'
            set @CACSCell = '1145'
        else if @CACSCell = '1150' and @MinorInvestTech = 1 and @Age >= 18
            set @CACSCell = '1155'
        else if @CACSCell = '1150' and @MinorInvestTech = 0 and @Age < 18
            set @CACSCell = '1160'
        else if @CACSCell = '1150' and @MinorInvestTech = 0 and @Age >= 18
            set @CACSCell = '1165'
        goto FinalStep
    end
  
    if @MAC = '14' and @MinorInvestTech = 0
    begin 
        set @CACSCell =   
            (Case @CACSCell  
                when '1420' then '1430'  
                when '1490' then '1495'  
                else @CACSCell  
            end)
        goto FinalStep
    end
  
    if @MAC = '16' and @MinorInvestTech = 0
    begin  
        set @CACSCell =   
            (Case   
                when @Age < 18 then '1610'  
                when @Age >= 18 and @Age < 65 then '1615'  
                when @Age >= 65 then '1620'  
                else @CACSCell  
            end)
        goto FinalStep
    end
  
    if @MAC = '17' and @MinorInvestTech = 0 and @CACSBranch = '1700'
    begin  
        set @CACSCell = '1710'
        goto FinalStep
    end
 
    if @MAC = '18'
    begin  
        if @CACSCell = '1800' and @MinorInvestTech = 0 and @Age < 18
            set @CACSCell = '1810'
        if @CACSCell = '1800' and @MinorInvestTech = 0 and @Age >= 18
            set @CACSCell = '1815'
        if @CACSCell = '1820' and @MinorInvestTech = 0 and @Age < 18
            set @CACSCell = '1830'
        if @CACSCell = '1820' and @MinorInvestTech = 0 and @Age >= 18
            set @CACSCell = '1835'
        goto FinalStep
    end
    if @MAC = '20'
    begin
        if @CACSCell = '2000' and @MinorInvestTech = 0
            set @CACSCell = '2005'
        else if @MinorInvestTech = 1 and @CACSBranch in ('2030','2035','2040','2045','2050','2055')
            set @CACSCell = '2000'
        goto FinalStep
    end
FinalStep:
--     print '@MinorInvestTech = ' + cast(@MinorInvestTech as varchar(20))
    set @MajorInvestTech = isnull((
        select top 1 InvestigativeTechnologyType
        from dbo.LU_CACS_MITCCI_2003
        where CCICode in (
            select IntervCode from LU_CACS_Temp_2003 
            where isnull(OOHIndicator, '') <> 'Y')
        order by Hierarchy), '')
--     print '@MajorInvestTech = ' + cast(@MajorInvestTech as varchar(100))
    -- Return numeric values...  
    set @MAC_Return = cast(@mac as int)  
    set @CACSCell_Return = cast(@CACSCell as decimal(5,1))  
    select 
        @ACW = ACW,
        @CACSDescription = CACSDesc
    from LU_CACS_ACW_2003 
    where CACSBranch = @CACSCell
    and isnull(VisitDisposition, '') = @DispositionCode
    and isnull(InvestigativeTechnologyType, '') = isnull(@MajorInvestTech, '')
--     print '@mac = ' + cast(@MAC_Return as varchar(100))
--     print '@CACSCell = ' + cast(@CACSCell_Return as varchar(100))
--     print '@CACSDescription = ' + cast(@CACSDescription as varchar(100))
--     print '@DispositionCode = ' + cast(@DispositionCode as varchar(100))
--     print '@Age = ' + cast(@Age as varchar(100))

	--Ticket 11969 Enhancement for CACS Auditing
	If isnull(@AbstractID, 0) > 0
	Begin
		Declare @AUMAC as Varchar(6)
		Declare @AUCACSCell as VarChar(20)
		Declare @AUACW as VarChar(20)
		Declare @AUAid as int
		SELECT @AUAid = Abstractid, @AUMAC = MAC, @AUCACSCell = CACSCell, @AUACW = ACW
		FROM AB_CACS where AbstractID = @AbstractID and OccurrenceNumber = 1 and CACS_Year = 2003
		If isnull(@AUAid, 0) > 0
		Begin
			If @AUMAC <> @MAC_Return
				Insert into AB_GrouperAudit Values (@AbstractID, 2003, 'MAC', @AUMAC, @MAC_Return, GetDate())
			If @AUCACSCell <> @CACSCell_Return
				Insert into AB_GrouperAudit Values (@AbstractID, 2003, 'CACSCell', @AUCACSCell, @CACSCell_Return, GetDate())
			If @AUACW <> @ACW
				Insert into AB_GrouperAudit Values (@AbstractID, 2003, 'ACW', @AUACW, @ACW, GetDate())
		End
	End


    -- For batch processing use...update the CACS table here.  Otherwise update it from vb.  

    if isnull(@AbstractID, 0) > 0  
    begin  
        delete AB_CACS where Abstractid = @Abstractid and CACS_Year = 2003 and OccurrenceNumber = 1  
        if IsNull(@MAC, '') <> ''  
        begin  
            insert into [dbo].[AB_CACS] (AbstractID, OccurrenceNumber, CACS_Year, MAC, CACSCell, ACW, CACSDescription, InterventionCode) values   
            (@AbstractID, 1, 2003, @MAC_Return, @CACSCell_Return, @ACW, @CACSDescription, @IntervCode)  
        end  
    end  
DoNothing:
return 0  





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [CACS_Grouping_2004]
    -- The methodology is identical to CACS 2003.
    -- Uses the same 2003 CACS LU tables except for these two:
    -- 1) LU_CACS_ACW_2004...from CIHI with new 2004 ACW values
    -- 2) LU_CACS_Temp_2004...temp table for calculation
    @ICDType varchar(1),  
    @AnesTech1 varchar(1),  
    @Age int,  
    @Gender varchar(1),  
    @Diagnosis1 varchar(10),  
    @Procedure1 varchar(10),  
    @Procedure2 varchar(10),  
    @Procedure3 varchar(10),  
    @Procedure4 varchar(10),  
    @Procedure5 varchar(10),  
    @Procedure6 varchar(10),  
    @Procedure7 varchar(10),  
    @Procedure8 varchar(10),  
    @Procedure9 varchar(10),  
    @Procedure10 varchar(10),  
    @EncounterNumber varchar(50),  
    @MAC_Return int output,  
    @CACSCell_Return decimal(5,1) output,     
    @ACW decimal(6,4) output,  
    @CACSDescription varchar(150) output,  
    @AbstractID int,  
    @IntervCode int,             -- Added...New, 2002/06/25, it is the code value of @Procedure1 above.  
    @DispositionCode varchar(2),  -- Added...new, 2002/06/25, the CIHI value. 
    -- Added for the new 2003 CACS specs, 2004/02/20
    @AgeCode varchar(1),    -- CIHI value
    @Program varchar(12),   -- CIHI value
    @OOH1 varchar(12),    -- CIHI value
    @OOH2 varchar(12),    -- CIHI value
    @OOH3 varchar(12),    -- CIHI value
    @OOH4 varchar(12),    -- CIHI value
    @OOH5 varchar(12),    -- CIHI value
    @OOH6 varchar(12),    -- CIHI value
    @OOH7 varchar(12),    -- CIHI value
    @OOH8 varchar(12),    -- CIHI value
    @OOH9 varchar(12),    -- CIHI value
    @OOH10 varchar(12),    -- CIHI value
    @Status1 varchar(12),    -- CIHI value
    @Status2 varchar(12),    -- CIHI value
    @Status3 varchar(12),    -- CIHI value
    @Status4 varchar(12),    -- CIHI value
    @Status5 varchar(12),    -- CIHI value
    @Status6 varchar(12),    -- CIHI value
    @Status7 varchar(12),    -- CIHI value
    @Status8 varchar(12),    -- CIHI value
    @Status9 varchar(12),    -- CIHI value
    @Status10 varchar(12),    -- CIHI value
    @Location1 varchar(12),    -- CIHI value
    @Location2 varchar(12),    -- CIHI value
    @Location3 varchar(12),    -- CIHI value
    @Location4 varchar(12),    -- CIHI value
    @Location5 varchar(12),    -- CIHI value
    @Location6 varchar(12),    -- CIHI value
    @Location7 varchar(12),    -- CIHI value
    @Location8 varchar(12),    -- CIHI value
    @Location9 varchar(12),    -- CIHI value
    @Location10 varchar(12),    -- CIHI value
    @Extent1 varchar(12),    -- CIHI value
    @Extent2 varchar(12),    -- CIHI value
    @Extent3 varchar(12),    -- CIHI value
    @Extent4 varchar(12),    -- CIHI value
    @Extent5 varchar(12),    -- CIHI value
    @Extent6 varchar(12),    -- CIHI value
    @Extent7 varchar(12),    -- CIHI value
    @Extent8 varchar(12),   -- CIHI value
    @Extent9 varchar(12),    -- CIHI value
    @Extent10 varchar(12)    -- CIHI value
as  
    
--     print '@Procedure1: ' + @Procedure1 
--     print '@Diagnosis1: ' + @Diagnosis1 
--     print '@AbstractID: ' + cast(@AbstractID as varchar(10))
--     print '@Gender = ' + @Gender
--     print '-----------------'
    declare @CACSBranch varchar(4)  
    declare @DPGNumber varchar(16)   
    declare @ICode varchar(50)
    declare @IAttribStatusCIHI varchar(50)
    declare @IAttribLocationCIHI varchar(50)
    declare @IAttribExtentCIHI varchar(50)
    declare @IOOHIndicatorCIHI varchar(50)
    declare @CACSCell varchar(6)  
    declare @IProgramCIHI varchar(50)
    declare @RehabCategory varchar(10)
    declare @FilteredStatus varchar(2)
    declare @FilteredExtent varchar(2)
    declare @FilteredProgram varchar(2)
    declare @FilteredLocation varchar(12)
    declare @CACS_Temp varchar(10)
    declare @MHIntType varchar(30)
    declare @MajorInvestTech varchar(10)
    declare @MinorInvestTech int  
    declare @Mac int  
    declare @Occ int
    declare @RehabCount int
    declare @MentHlthCount int
    declare @PhysicalCount int
    declare @CognitiveCount int
    declare @InterventionCount int
    -- NB: Incoming Parameters are CIHI values.  
    set @AnesTech1   = isnull(@AnesTech1, '')
    set @Diagnosis1  = isnull(@Diagnosis1, '')
    set @Procedure1  = isnull(@Procedure1, '')
    set @Procedure2  = isnull(@Procedure2, '')
    set @Procedure3  = isnull(@Procedure3, '')
    set @Procedure4  = isnull(@Procedure4, '')
    set @Procedure5  = isnull(@Procedure5, '')
    set @Procedure6  = isnull(@Procedure6, '')
    set @Procedure7  = isnull(@Procedure7, '')
    set @Procedure8  = isnull(@Procedure8, '')
    set @Procedure9  = isnull(@Procedure9, '')
    set @Procedure10 = isnull(@Procedure10, '')
    set @OOH1  = isnull(@OOH1, '')
    set @OOH2  = isnull(@OOH2, '')
    set @OOH3  = isnull(@OOH3, '')
    set @OOH4  = isnull(@OOH4, '')
    set @OOH5  = isnull(@OOH5, '')
    set @OOH6  = isnull(@OOH6, '')
    set @OOH7  = isnull(@OOH7, '')
    set @OOH8  = isnull(@OOH8, '')
    set @OOH9  = isnull(@OOH9, '')
    set @OOH10  = isnull(@OOH10, '')
    set @Status1  = isnull(@Status1, '')
    set @Status2  = isnull(@Status2, '')
    set @Status3  = isnull(@Status3, '')
    set @Status4  = isnull(@Status4, '')
    set @Status5  = isnull(@Status5, '')
    set @Status6  = isnull(@Status6, '')
    set @Status7  = isnull(@Status7, '')
    set @Status8  = isnull(@Status8, '')
    set @Status9  = isnull(@Status9, '')
    set @Status10  = isnull(@Status10, '')
    set @Location1  = isnull(@Location1, '')
    set @Location2  = isnull(@Location2, '')
    set @Location3  = isnull(@Location3, '')
    set @Location4  = isnull(@Location4, '')
    set @Location5  = isnull(@Location5, '')
    set @Location6  = isnull(@Location6, '')
    set @Location7  = isnull(@Location7, '')
    set @Location8  = isnull(@Location8, '')
    set @Location9  = isnull(@Location9, '')
    set @Location10  = isnull(@Location10, '')
    set @Extent1  = isnull(@Extent1, '')
    set @Extent2  = isnull(@Extent2, '')
    set @Extent3  = isnull(@Extent3, '')
    set @Extent4  = isnull(@Extent4, '')
    set @Extent5  = isnull(@Extent5, '')
    set @Extent6  = isnull(@Extent6, '')
    set @Extent7  = isnull(@Extent7, '')
    set @Extent8  = isnull(@Extent8, '')
    set @Extent9  = isnull(@Extent9, '')
    set @Extent10  = isnull(@Extent10, '')
    set @Age = (case @AgeCode when 'Y' then @Age else 0 end)
    set @MAC = ''  
    set @CACSCell = ''  
    set @CACSBranch = ''  
    set @MajorInvestTech = ''
    set @MinorInvestTech = 0  
    set @PhysicalCount = 0
    set @CognitiveCount = 0
    set @RehabCount = 0
    set @MentHlthCount = 0
    -- Assign MAC based on Main Problem...  
    if @Diagnosis1 = ''  
    begin  
        -- Ungroupable when no diagnosis code.
        set @CACSCell = '9999'  
        set @MAC = '99'  
        goto FinalStep  
    end  
    else  
    begin  
        select @MAC = MAC, @CACSBranch = CACSBranch  
        from dbo.LU_CACS_I10DX_2003
        where (ICD10CACode = @Diagnosis1)    
      
        -- Consider it ungroupable if the diagnosis code is not in the CACS table  
        if isnull(@MAC, '') = ''
        begin  
            set @CACSCell = '9999'  
            set @MAC = '99'  
            goto FinalStep  
        end
        set @CACSCell = @CACSBranch  
    end  
    -- Check for Dead On Arrival (DOA) or Left without being seen...  
    set @CACSCell =   
        (case   
            when @DispositionCode = '11' then '9900' -- DOA  
            when @DispositionCode = '02' then '9905' -- Left without being seen  
            else @CACSCell  
        end)
    if @CACSCell in ('9900','9905') goto FinalStep  
    truncate table LU_CACS_Temp_2004
    
    if @Procedure1 <> ''
        insert LU_CACS_Temp_2004 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (1, @Procedure1, @Status1, @Extent1, @Location1, @OOH1, @Program)
    if @Procedure2 <> ''
        insert LU_CACS_Temp_2004 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (2, @Procedure2, @Status2, @Extent2, @Location2, @OOH2, @Program)
    if @Procedure3 <> ''
        insert LU_CACS_Temp_2004 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (3, @Procedure3, @Status3, @Extent3, @Location3, @OOH3, @Program)
    if @Procedure4 <> ''
        insert LU_CACS_Temp_2004 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (4, @Procedure4, @Status4, @Extent4, @Location4, @OOH4, @Program)
    if @Procedure5 <> ''
        insert LU_CACS_Temp_2004 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (5, @Procedure5, @Status5, @Extent5, @Location5, @OOH5, @Program)
    if @Procedure6 <> ''
        insert LU_CACS_Temp_2004 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (6, @Procedure6, @Status6, @Extent6, @Location6, @OOH6, @Program)
    if @Procedure7 <> ''
        insert LU_CACS_Temp_2004 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (7, @Procedure7, @Status7, @Extent7, @Location7, @OOH7, @Program)
    if @Procedure8 <> ''
        insert LU_CACS_Temp_2004 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (8, @Procedure8, @Status8, @Extent8, @Location8, @OOH8, @Program)
    if @Procedure9 <> ''
        insert LU_CACS_Temp_2004 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (9, @Procedure9, @Status9, @Extent9, @Location9, @OOH9, @Program)
    if @Procedure10 <> ''
        insert LU_CACS_Temp_2004 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (10, @Procedure10, @Status10, @Extent10, @Location10, @OOH10, @Program)
    
    -- Filter the data...
    declare cur_Interv cursor local fast_forward for  
        select 
            Occ, -- i.IntervOccurrence,
            IntervCode,        -- i.IntervCode,
            IntervAttStatus,        -- i.IntervAttribStatus,
            IntervAttLocation,        -- i.IntervAttribLocation,
            IntervAttExtent,        -- i.IntervAttribExtent,
            OOHIndicator,        -- i.IntervOOHIndicator,
            ProgramArea         -- a.Program
        from LU_CACS_Temp_2004
        order by Occ
    open cur_Interv 
    while (1 = 1) 
    begin  
        fetch next from cur_Interv  
        into @Occ, @ICode, @IAttribStatusCIHI, @IAttribLocationCIHI, 
            @IAttribExtentCIHI, @IOOHIndicatorCIHI, @IProgramCIHI
    
        if (@@fetch_status <> 0) break 
    
        if isnull(@IOOHIndicatorCIHI, '') = 'Y' or isnull(@IAttribStatusCIHI, '') = 'A'
            update LU_CACS_Temp_2004
            set IgnoreData = 'Y'
    
            where occ = @Occ
        else
        begin
            -- Filter the IntervAttribStatus...
            if not exists (select * from LU_CACS_CACSTA_2003 where CCICode = @ICode and isnull(CCIStatusAttribute, '') = @IAttribStatusCIHI)
                set @FilteredStatus = ''
            else
                set @FilteredStatus = @IAttribStatusCIHI
            -- Filter the IntervAttribExtent...
            if not exists (select * from LU_CACS_CACEXT_2003 where CCICode = @ICode and isnull(CCIExtentAttribute, '') = @IAttribExtentCIHI)
                set @FilteredExtent = ''
            else
                set @FilteredExtent = @IAttribExtentCIHI
            -- Filter the IntervAttriLocation
            if not exists (select * from LU_CACS_DPGLOC_2003 where CCICode = @ICode and isnull(CCILocationAttribute, '') = @IAttribLocationCIHI)
                set @FilteredLocation = ''
            else
                set @FilteredLocation = @IAttribLocationCIHI
            -- Filter the Program...
            if not exists (select * from LU_CACS_CACPGM_2003 where CCICode = @ICode and isnull(ProgramArea, '') = @IProgramCIHI)
                set @FilteredProgram = ''
            else
                set @FilteredProgram = @IProgramCIHI
    
            update LU_CACS_Temp_2004
            set FilteredAttStatus = @FilteredStatus, 
                FilteredAttExtent = @FilteredExtent, 
                FilteredProgramArea = @FilteredProgram, 
                FilteredAttLocation = @FilteredLocation
            where Occ = @Occ
    
            -- Compute the MentalHealth count...
            if exists (select * from LU_CACS_INTMHCCI_2003 where CCICode = @ICode and isnull(CCIStatusAttribute, '') = @FilteredStatus and isnull(ProgramArea, '') = @FilteredProgram and isnull(CCIExtentAttribute, '') = @FilteredExtent)
            begin
                set @MentHlthCount = @MentHlthCount + 1
                update LU_CACS_Temp_2004 set IsMentalHealth = 'Y' where Occ = @Occ
            end
    
            -- Compute the Rehab count...
            set @RehabCategory = isnull((select RehabInterventionCategory from LU_CACS_INTRHCCI_2003 where CCICode = @ICode and isnull(CCIStatusAttribute, '') = @FilteredStatus and isnull(ProgramArea, '') = @FilteredProgram), '')
            if @RehabCategory <> ''
            begin
                set @RehabCount = @RehabCount + 1
                update LU_CACS_Temp_2004 
                set RehabCategory = @RehabCategory,
                    IsRehab = 'Y' 
                where Occ = @Occ        
            end
    
            if @RehabCategory = 'prhab'                  
                set @PhysicalCount = @PhysicalCount + 1  
            else if @RehabCategory = 'crhab'                  
                set @CognitiveCount = @CognitiveCount + 1 
        end
    end 
    
    close cur_Interv  
    deallocate cur_Interv  
    -- Retrieve the InterventionCount...
    select @InterventionCount = count(*) from LU_CACS_Temp_2004 --where isnull(IgnoreData, '') <> 'Y'
--     print '@InterventionCount = ' + cast(@InterventionCount as varchar(500))
    -- Retrieve info for Day Procedure...
    set @FilteredLocation = ''
    set @ICode = ''
    set @DPGNumber = ''
    -- Examine patient abstract for any Day Procedure in occurrence one...
    select 
        @FilteredLocation = isnull(FilteredAttLocation, ''),
        @ICode = isnull(IntervCode, '')
    from LU_CACS_Temp_2004 
    where Occ = 1 
    and isnull(IgnoreData, '') <> 'Y'
    -- Retrieve the DPG cell.
    select 
        @DPGNumber = isnull(DPGNumber, '')
    from dbo.LU_CACS_DPGCCI_2003
    where CCICode = @ICode
    and isnull(CCILocationAttribute, '') = @FilteredLocation 
    -- Is it Day Procedure???
    if (isnull(@DPGNumber, '') <> '')  
    begin  
--         print '@FilteredLocation = ' + cast(@FilteredLocation as varchar(500))
--         print '@ICode = ' + cast(@ICode as varchar(500))
--         print '@DPGNumber = ' + cast(@DPGNumber as varchar(500))
--         print '@AnesTech1 = ' + cast(@AnesTech1 as varchar(500))
        -- Further split the DPG cell
        if isnull(@DPGNumber, '') <> ''  
        begin  
--             print 'BEFORE: @CACSCell = ' + cast(@CACSCell as varchar(500))
            set @CACSCell = @DPGNumber  
            if @DPGNumber in ('1','15','48','50','52','65')  
                set @CACSCell =   
                    (Case  
                        when @AnesTech1 >= '1' And @AnesTech1 <= '4' then @CACSCell + '.1'  
                        when @AnesTech1 >= '5' And @AnesTech1 <= '6' then @CACSCell + '.2'  
                        when @AnesTech1 >= '7' And @AnesTech1 <= '9' then @CACSCell + '.3'  
                        else @CACSCell  
                    end)  
--             print 'AFTER: @CACSCell = ' + cast(@CACSCell as varchar(500))
            Goto FinalStep  
        end  
    end  
    -- Rehab and Mental Health...
    if exists (select * from LU_CACS_Temp_2004 where isnull(IgnoreData, '') <> 'Y')  
    Begin
--         print 'inside: Rehab and Mental Health...'
--         print '@MentHlthCount = ' + cast(@MentHlthCount as varchar(10))
--         print '@RehabCount = ' + cast(@RehabCount as varchar(10))
        if @MentHlthCount > @RehabCount
        begin
--             print 'inside: MentHlthCount > RehabCount'
            -- More MentalHealth than Rehab...
            set @MAC = '19'
            set @MHIntType = ''
            set @CACS_Temp = ''
            set @ICode = ''
            -- Find the first CACS for mental health intervention code and intervention type.
            declare cur_Mental cursor local fast_forward for
                select IntervCode, FilteredAttStatus, FilteredAttExtent, FilteredProgramArea
                from LU_CACS_Temp_2004
                where isnull(IsMentalHealth, '') = 'Y'
                and isnull(IgnoreData, '') <> 'Y'
                order by Occ
            open cur_Mental
            While (1 = 1) 
            begin  
                -- Loop through all mental health interventions and get the first availble CACS
                fetch next from cur_Mental  
                into @ICode, @FilteredStatus, @FilteredExtent, @FilteredProgram
                if (@@fetch_status <> 0) break 
    
                set @MHIntType = isnull((
                    select MentalHealthInterventionType 
                    from LU_CACS_INTMHCCI_2003 
                    where CCICode = @ICode 
                    and isnull(CCIStatusAttribute, '') = @FilteredStatus
                    and isnull(CCIExtentAttribute, '') = @FilteredExtent
                    and isnull(ProgramArea, '') = @FilteredProgram), '')
                -- Once the MentalHealthInterventionType is found, get the CACS. Otherwise, get the next mental health intervention.
                if isnull(@MHIntType, '') <> ''
                begin
                    -- Retrieve the MAC 19 CACS from the table, otherwise assign the default value for this MentalHealthInterventionType.
                    set @CACS_Temp = isnull((select CACS from dbo.LU_CACS_Mac19_2003 where ICD10CACode = @Diagnosis1 and IntervCode = @ICode and isnull(MHIntType, '') = @MHIntType), '')
                    if isnull(@CACS_Temp, '') = ''
                        set @CACSCell =  
                            (case  
                                when @MHIntType = 'LEGAL ASSESSMENT FULL DAY' then '1961'  
                                when @MHIntType = 'PSYCHOTHERAPY COUPLE' then '1962'  
                                when @MHIntType = 'INITIAL ASSESSMENT MH' then '1963'  
                                when @MHIntType = 'PSYCHOTHERAPY FAMILY'then '1964'  
                                when @MHIntType = 'PATIENT SPECIFIC HEARINGS' then '1965'  
                                when @MHIntType = 'RE-ASSESSMENT MG' then '1966'
                                when @MHIntType = 'SCREENING ASSESSMENT MH' then '1967'  
                                when @MHIntType = 'MED ADMIN/MANAGEMENT' then '1968'  
                                when @MHIntType = 'PSYCHOTHERAPY IND' then '1969'  
                                when @MHIntType = 'SERVICE PLANNING' then '1971'  
                                when @MHIntType = 'CRISIS INTERVENTION CALL' then '1972'  
                                when @MHIntType = 'LEGAL ASSESSMENT HALF DAY' then '1974'  
                                when @MHIntType = 'COUNSELLING EXT' then '1975'  
                                when @MHIntType = 'COUNSELLING INT' then '1976'
                                when @MHIntType = 'COUNSELLING BRIEF' then '1977'  
                                when @MHIntType = 'EDUCATION MH' then '1978'  
                                when @MHIntType = 'PSYCHOTHERAPY GROUP' then '1979'  
                                else @CACSCell
                            end)
                    else
                        set @CACSCell = @CACS_Temp
                    -- Exit loop...CACS found
                    break
                end
            end 
            close cur_Mental
            deallocate cur_mental
            goto FinalStep  
        end
        else if @RehabCount >= @MentHlthCount and @RehabCount <> 0
        begin
            -- print 'Inside: RehabCount >= MentHlthCount and RehabCount <> 0'
            -- Rehab >= MentalHealth...
            declare cur_Rehab cursor local fast_forward for
                select IntervCode, FilteredAttStatus, FilteredAttLocation, FilteredAttExtent, FilteredProgramArea, RehabCategory
                from LU_CACS_Temp_2004
                where isnull(IsRehab, '') = 'Y'
                and isnull(IgnoreData, '') <> 'Y'
                order by Occ
            open cur_Rehab
            
            while (1 = 1)
            begin
                fetch next from cur_Rehab
                into @ICode, @FilteredStatus, @FilteredLocation, @FilteredExtent, @FilteredProgram, @RehabCategory
                if (@@fetch_status <> 0) break
--             print '@RehabCategory = ' + @RehabCategory + '  ' + cast(len(@RehabCategory) as varchar(10))
--             The LU_CACS_RH_Diagnosis_2003 and LU_CACS_RH_Intervention_2003 are built from the html.
--             The following CCICode is not in the html but added manually to the table:
--             6AA30ZZZZ, 6KA50MD, 6KA50ME, 6KA50MP, 6KA50MR, 6KA50MZ.
--             They belong to the Cognitive Rehabilitation Interventions.
--             Wonder what other CCICode is missing from the html...
                set @CACS_Temp = isnull((
                    select d.CACS
                    from LU_CACS_RH_Diagnosis_2003 d
                        join LU_CACS_RH_Intervention_2003 i
                            on d.CACS = i.CACS
                    where d.ICD10CACode = @Diagnosis1
                    and i.CCICode = @ICode
                    and isnull(i.CCIStatus, '') = @FilteredStatus
--                     and isnull(i.CCILocation, '') = @FilteredLocation
--                     and isnull(i.CCIExtent, '') = @FilteredExtent
                    and isnull(i.CCIProgram, '') = @FilteredProgram), '')
--                 print '@Diagnosis1 = ' + @Diagnosis1 
--                 print '@ICode = ' + @ICode 
--                 print '@FilteredStatus = ' + @FilteredStatus 
--                 print '@FilteredLocation = ' + @FilteredLocation 
--                 print '@FilteredExtent = ' + @FilteredExtent 
--                 print '@FilteredProgram = ' + @FilteredProgram 
--                 print '@CACS_Temp = ' + @CACS_Temp 
                if isnull(@CACS_Temp, '') <> ''
                begin
                    -- Exit loop upon CACS found...
                    if @CACS_Temp in ('9400','9410','9420','9430','9440','9450',
                        '9460','9470','9480','9492','9510','9522') break
                    if @CACS_Temp = '9490' and @RehabCount < 3 break
                    if @CACS_Temp = '9496' and @RehabCount < 6  break
                    if @CACS_Temp = '9497' and @RehabCount > 1  break
                    if @CACS_Temp = '9498' and @RehabCount <= 1  break
                    if @CACS_Temp = '9500' and @RehabCount < 3  break
                    if @CACS_Temp = '9501' and @RehabCount < 6  break
                    if @CACS_Temp = '9502' and @PhysicalCount >= @CognitiveCount break
                    if @CACS_Temp = '9504' and @RehabCount > 1  break
                    if @CACS_Temp = '9506' and @RehabCount < 6  break
                    if @CACS_Temp = '9507' and @RehabCount > 1  break
                    if @CACS_Temp = '9508' and @RehabCount <= 1  break
                    if @CACS_Temp = '9512' and @RehabCount < 3  break
                    if @CACS_Temp = '9513' and @RehabCategory = 'commling' and @RehabCount < 6  break
                    if @CACS_Temp = '9513' and @RehabCategory = 'crhab' break
                    if @CACS_Temp = '9514' and @PhysicalCount >= @CognitiveCount  break
                    if @CACS_Temp = '9516' and @InterventionCount < 6  break
                    if @CACS_Temp = '9517' and @RehabCount > 1  break
                    if @CACS_Temp = '9518' and @RehabCount <= 1  break
                    if @CACS_Temp = '9520' and @RehabCount < 3  break
                    if @CACS_Temp = '9521' and @RehabCount < 6  break
                    if @CACS_Temp = '9526' and @RehabCount < 6  break
                    if @CACS_Temp = '9527' and @RehabCount > 1  break
                    if @CACS_Temp = '9528' and @RehabCount <= 1  break
                    if @CACS_Temp = '9530' and @RehabCount < 3  break
                    if @CACS_Temp = '9531' and @RehabCount < 6  break
                    if @CACS_Temp = '9532' and @PhysicalCount >= @CognitiveCount  break
                    if @CACS_Temp = '9534' and @RehabCategory = 'crhab' and @RehabCount < 1  break
                    if @CACS_Temp = '9534' and @RehabCategory = 'orhab' and  @RehabCount < 1  break
                    if @CACS_Temp = '9535' and @RehabCount <= 1  break
                    if @CACS_Temp = '9536' and @RehabCount < 6  break
                    if @CACS_Temp = '9534' and @RehabCount < 3  break
                    if @CACS_Temp = '9538' and @RehabCount <= 1  break
                    if @CACS_Temp = '9540' and @RehabCount < 3  break
                    if @CACS_Temp = '9541' and @RehabCount < 6  break
                    if @CACS_Temp = '9542' and @PhysicalCount >= @CognitiveCount  break
                    if @CACS_Temp = '9544' and @RehabCategory = 'crhab' and @RehabCount > 1  break
                    if @CACS_Temp = '9544' and @RehabCategory = 'orhab' and  @RehabCount > 1  break
                    if @CACS_Temp = '9545' and @RehabCategory = 'crhab' and @RehabCount <= 1  break
                    if @CACS_Temp = '9545' and @RehabCategory = 'orhab' and  @RehabCount <= 1  break
                    if @CACS_Temp = '9546' and @RehabCount < 6  break
                    if @CACS_Temp = '9550' and @RehabCount < 3  break
                    if @CACS_Temp = '9551' and @RehabCount < 6  break
                    if @CACS_Temp = '9552' and @RehabCategory = 'prhab' and @PhysicalCount >= @CognitiveCount and @RehabCount > 2  break
                    if @CACS_Temp = '9552' and @RehabCategory = 'orhab' and @RehabCount > 1  break
                    if @CACS_Temp = '9553' and @PhysicalCount >= @CognitiveCount and @RehabCount <= 2  break
                    if @CACS_Temp = '9556' and @RehabCount < 6  break
                    if @CACS_Temp = '9558' and @RehabCount <= 1  break
                    if @CACS_Temp = '9560'
                    begin 
                        set @CACS_Temp = 
                            (case
                                when @Age < 40 then '9560'
                                when @Age < 60 then '9562'
                                when @Age < 80 then '9564'
                                else '9566'
                            end)
                        break
                    end
                    if @CACS_Temp = '9570' and @RehabCount < 3  break
                    if @CACS_Temp = '9571' and @RehabCount < 6  break
                    if @CACS_Temp = '9572' and @PhysicalCount >= @CognitiveCount break
                    if @CACS_Temp = '9576' and @RehabCount < 6  break
                end
            end
            -- Keep the new CACS.
            if isnull(@CACS_Temp, '') <> ''
                set @CACSCell = @CACS_Temp
            close cur_Rehab
            deallocate cur_Rehab
--             print '@CACSCell = ' + cast (@CACSCell as varchar(20))
--             print '@CACS_Temp = ' + cast (@CACS_Temp as varchar(20))
--             print '@CACSCell = ' + cast (@CACSCell as varchar(20))
--             print 'Exiting... RehabCount >= MentHlthCount and RehabCount <> 0'
            goto FinalStep  
        end  
    end  
    -- Identify the Standard Investigative Technologies
    if exists (select * from LU_CACS_INVTECHCCI_2003
                where CCICode in (select IntervCode from LU_CACS_Temp_2004 where isnull(OOHIndicator, '') <> 'Y'))
        set @MinorInvestTech = 1           
    -- Assign diagnosis driven CACS based on interventions, gender and age.
    if @MAC = '1' 
    begin
        if @CACSCell = '100' and @MinorInvestTech = 0
            if @Age < 65
                set @CACSCell = '105'
            else
                set @CACSCell = '110'
        if @CACSCell = '160' and @MinorInvestTech = 0
            set @CACSCell = '165'
        if @CACSCell = '170' and @MinorInvestTech = 0
            set @CACSCell = '175'
        goto FinalStep
    end
    if @MAC = '2'
    begin
        if @CACSCell = '200' and @MinorInvestTech = 0
            if @Age < 45
                set @CACSCell = '210'
            else
                set @CACSCell = '215'
        goto FinalStep
    end
         
    if @MAC = '3'
    begin
--     print 'mac 3'
--     print '@MinorInvestTech = ' + cast (@MinorInvestTech as varchar(10))
        if @CACSCell = '300' and @MinorInvestTech = 0 
            set @CACSCell = '310'  
        goto FinalStep
    end
    if @MAC = '4' 
    begin  
        if @CACSCell = '400'
            if @MinorInvestTech = 1
            begin 
                if @Age >= 18
                    set @CACSCell = '410'
            end
            else
                if @Age < 65
                    set @CACSCell = '420'
                else
                    set @CACSCell = '430'
        goto FinalStep
    end  
    if @MAC = '5'
    begin
        if @CACSCell = '500' and @MinorInvestTech = 0
            set @CACSCell = '510'
        if @CACSCell = '570' and @MinorInvestTech = 0
            set @CACSCell = '580'
        goto FinalStep
    end
    if @MAC = '6' and @CACSBranch = '600'  
    begin  
        if @MinorInvestTech = 1 and @Age >= 18  
            set @CACSCell = '610'  
        if @MinorInvestTech = 0   
            set @CACSCell =   
                (Case   
                    when @Age < 18 then '620'  
                    when @Age >= 18 and @Age < 45 then '630'  
                    when @Age >= 45 then '640'  
                    else @CACSCell  
                end)  
        goto FinalStep
    end  
    if @MAC = '7' and @MinorInvestTech = 0
    begin  
        set @CACSCell = '710'  
        goto FinalStep
    end
  
    if @MAC = '8'  
    Begin
        if @CACSCell = '800' and @MinorInvestTech = 0
            set @CACSCell = '810'
        else if @CACSCell = '820' and @MinorInvestTech = 1 and @Age >= 18
            set @CACSCell = '825'
        else if @CACSCell = '820' and @MinorInvestTech = 0 and @Age < 18
            set @CACSCell = '830'
        else if @CACSCell = '820' and @MinorInvestTech = 0 and @Age >= 18
            set @CACSCell = '835'
        else if @CACSCell = '840' and @MinorInvestTech = 0 
            set @CACSCell = '850'
        else if @CACSCell = '860' and @MinorInvestTech = 0 
            set @CACSCell = '870'
        goto FinalStep
    end  
    if @MAC = '9' and @MinorInvestTech = 0 and @CACSBranch = '900'
    begin  
        if @Age < 18  
            set @CACSCell = '910'  
        else  
            set @CACSCell = '915'
        goto FinalStep
    end  
  
    if @MAC = '10' 
    begin
--         print 'Inside mac 10....'
--         print '@mac = ' + cast(@MAC_Return as varchar(100))
--         print '@CACSCell = ' + cast(@CACSCell as varchar(100))
--         print '@MinorInvestTech = ' + cast(@MinorInvestTech as varchar(100))
--         print '@Age = ' + cast(@Age as varchar(100))
--         print ''
        if @CACSCell = '1000' and @MinorInvestTech = 1 and @Age >= 18
            set @CACSCell = '1005'
        else if @CACSCell = '1000' and @MinorInvestTech = 0 and @Age < 6
            set @CACSCell = '1010'
        else if @CACSCell = '1000' and @MinorInvestTech = 0 and @Age >= 6
            set @CACSCell = '1015'
        else if @CACSCell = '1020' and @MinorInvestTech = 1 and @Age < 18
            set @CACSCell = '1000'
        else if @CACSCell = '1020' and @MinorInvestTech = 1 and @Age >= 18
            set @CACSCell = '1005' 
        else if @CACSCell = '1020' and @MinorInvestTech = 0 and @Age >= 18
            set @CACSCell = '1025' 
        goto FinalStep
    end
    if @MAC = '11'
    begin
--         print 'Inside mac 11....'
--         print '@mac = ' + cast(@MAC_Return as varchar(100))
--         print '@CACSCell = ' + cast(@CACSCell as varchar(100))
--         print '@MinorInvestTech = ' + cast(@MinorInvestTech as varchar(100))
--         print '@Age = ' + cast(@Age as varchar(100))
--         print '@Gender = ' + @Gender
--         print ''
        if @CACSCell = '1100' and @MinorInvestTech = 0 and @Age < 18 and @Gender = 'F'
            set @CACSCell = '1110'
        else if @CACSCell = '1100' and @MinorInvestTech = 0 and @Age >= 18 and @Gender = 'F'
            set @CACSCell = '1115'
        else if @CACSCell = '1130' and @MinorInvestTech = 0 and @Age < 18 and @Gender = 'F'
            set @CACSCell = '1110'
        else if @CACSCell = '1130' and @MinorInvestTech = 0 and @Age >= 18 and @Gender = 'F'
            set @CACSCell = '1115'
        else if @CACSCell = '1100' and @MinorInvestTech = 0 and @Age < 18 and @Gender = 'M'
            set @CACSCell = '1140'
        else if @CACSCell = '1100' and @MinorInvestTech = 0 and @Age >= 18 and @Gender = 'M'
            set @CACSCell = '1145'
        else if @CACSCell = '1130' and @MinorInvestTech = 0 and @Age < 18 and @Gender = 'M'
            set @CACSCell = '1140'
        else if @CACSCell = '1130' and @MinorInvestTech = 0 and @Age >= 18 and @Gender = 'M'
            set @CACSCell = '1145'
        else if @CACSCell = '1150' and @MinorInvestTech = 1 and @Age >= 18
            set @CACSCell = '1155'
        else if @CACSCell = '1150' and @MinorInvestTech = 0 and @Age < 18
            set @CACSCell = '1160'
        else if @CACSCell = '1150' and @MinorInvestTech = 0 and @Age >= 18
            set @CACSCell = '1165'
        goto FinalStep
    end
  
    if @MAC = '14' and @MinorInvestTech = 0
    begin 
        set @CACSCell =   
            (Case @CACSCell  
                when '1420' then '1430'  
                when '1490' then '1495'  
                else @CACSCell  
            end)
        goto FinalStep
    end
  
    if @MAC = '16' and @MinorInvestTech = 0
    begin  
        set @CACSCell =   
            (Case   
                when @Age < 18 then '1610'  
                when @Age >= 18 and @Age < 65 then '1615'  
                when @Age >= 65 then '1620'  
                else @CACSCell  
            end)
        goto FinalStep
    end
  
    if @MAC = '17' and @MinorInvestTech = 0 and @CACSBranch = '1700'
    begin  
        set @CACSCell = '1710'
        goto FinalStep
    end
 
    if @MAC = '18'
    begin  
        if @CACSCell = '1800' and @MinorInvestTech = 0 and @Age < 18
            set @CACSCell = '1810'
        if @CACSCell = '1800' and @MinorInvestTech = 0 and @Age >= 18
            set @CACSCell = '1815'
        if @CACSCell = '1820' and @MinorInvestTech = 0 and @Age < 18
            set @CACSCell = '1830'
        if @CACSCell = '1820' and @MinorInvestTech = 0 and @Age >= 18
            set @CACSCell = '1835'
        goto FinalStep
    end
    if @MAC = '20'
    begin
        if @CACSCell = '2000' and @MinorInvestTech = 0
            set @CACSCell = '2005'
        else if @MinorInvestTech = 1 and @CACSBranch in ('2030','2035','2040','2045','2050','2055')
            set @CACSCell = '2000'
        goto FinalStep
    end
FinalStep:
--     print '@MinorInvestTech = ' + cast(@MinorInvestTech as varchar(20))
    set @MajorInvestTech = isnull((
        select top 1 InvestigativeTechnologyType
        from dbo.LU_CACS_MITCCI_2003
        where CCICode in (
            select IntervCode from LU_CACS_Temp_2004 
            where isnull(OOHIndicator, '') <> 'Y')
        order by Hierarchy), '')
--     print '@MajorInvestTech = ' + cast(@MajorInvestTech as varchar(100))
    -- Return numeric values...  
    set @MAC_Return = cast(@mac as int)  
    set @CACSCell_Return = cast(@CACSCell as decimal(5,1))  
    select 
        @ACW = ACW,
        @CACSDescription = CACSDesc
    from LU_CACS_ACW_2004 
    where CACSBranch = @CACSCell
    and isnull(VisitDisposition, '') = @DispositionCode
    and isnull(InvestigativeTechnologyType, '') = isnull(@MajorInvestTech, '')
--     print '@mac = ' + cast(@MAC_Return as varchar(100))
--     print '@CACSCell = ' + cast(@CACSCell_Return as varchar(100))
--     print '@CACSDescription = ' + cast(@CACSDescription as varchar(100))
--     print '@DispositionCode = ' + cast(@DispositionCode as varchar(100))
--     print '@Age = ' + cast(@Age as varchar(100))

	--Ticket 11969 Enhancement for CACS Auditing
	If isnull(@AbstractID, 0) > 0
	Begin
		Declare @AUMAC as Varchar(6)
		Declare @AUCACSCell as VarChar(20)
		Declare @AUACW as VarChar(20)
		Declare @AUAid as int
		SELECT @AUAid = Abstractid, @AUMAC = MAC, @AUCACSCell = CACSCell, @AUACW = ACW
		FROM AB_CACS where AbstractID = @AbstractID and OccurrenceNumber = 1 and CACS_Year = 2004
		If isnull(@AUAid, 0) > 0
		Begin
			If @AUMAC <> @MAC_Return
				Insert into AB_GrouperAudit Values (@AbstractID, 2004, 'MAC', @AUMAC, @MAC_Return, GetDate())
			If @AUCACSCell <> @CACSCell_Return
				Insert into AB_GrouperAudit Values (@AbstractID, 2004, 'CACSCell', @AUCACSCell, @CACSCell_Return, GetDate())
			If @AUACW <> @ACW
				Insert into AB_GrouperAudit Values (@AbstractID, 2004, 'ACW', @AUACW, @ACW, GetDate())
		End
	End

    -- For batch processing use...update the CACS table here.  Otherwise update it from vb.  
    if isnull(@AbstractID, 0) > 0  
    begin
        delete AB_CACS where Abstractid = @Abstractid and CACS_Year = 2004 and OccurrenceNumber = 1  
        if IsNull(@MAC, '') <> ''  
        begin  
            insert into [dbo].[AB_CACS] (AbstractID, OccurrenceNumber, CACS_Year, MAC, CACSCell, ACW, CACSDescription, InterventionCode) values   
            (@AbstractID, 1, 2004, @MAC_Return, @CACSCell_Return, @ACW, @CACSDescription, @IntervCode)  
        end  
    end  

    -- For DPG Ontario calculation...
    declare @CACSValue int
    declare @CACSDPGONValid int
    declare @HospCode int
    -- Set a arbitrary constant to determine if client has access to this calculation...
    set @CACSDPGONValid = 66101
    select @CACSValue = CACSDPGONValue from CACS_DPGON where CACSYear = 2004
    --select top 1 @HospCode = code from H_HospitalProfile order by code
    -- Criteria: Constant = HospitalCode + CACSValue
    --if (@AbstractID > 0) and  (@CACSValue + @HospCode = @CACSDPGONValid)
    if (@AbstractID > 0) and exists(select code from H_HospitalProfile where code + @CACSValue = 66101) --PR - 00993
    begin
        -- Check for 'abandon' intervention...
        if @Status1 = 'A'
            set @Procedure1 = 'Abandon'
		--PR - 02841 
		if exists (select abstractid from ab_Abstract where abstractid = @AbstractID and 
			miscode in (select code from lu_miscode where cihivalue like '7_262' or
			cihivalue like '7_34020%' or cihivalue like '7_34025%' or cihivalue like '7_34055' or
			cihivalue like '7_260%' or cihivalue like '7_265%'))
		Begin
	        exec P_LookupDPGON  @ICDType, 2004, @Procedure1, @Location1, @AbstractID
		End
    end

DoNothing:
return 0





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE  PROCEDURE [CACS_Grouping_2005]
    -- The methodology is identical to CACS 2003.
    -- Uses the same 2003 CACS LU tables except for these two:
    -- 1) LU_CACS_ACW_2005...from CIHI with new 2005 ACW values
    -- 2) LU_CACS_Temp_2005...temp table for calculation
    @ICDType varchar(1),  
    @AnesTech1 varchar(1),  
    @Age int,  
    @Gender varchar(1),  
    @Diagnosis1 varchar(10),  
    @Procedure1 varchar(10),  
    @Procedure2 varchar(10),  
    @Procedure3 varchar(10),  
    @Procedure4 varchar(10),  
    @Procedure5 varchar(10),  
    @Procedure6 varchar(10),  
    @Procedure7 varchar(10),  
    @Procedure8 varchar(10),  
    @Procedure9 varchar(10),  
    @Procedure10 varchar(10),  
    @EncounterNumber varchar(50),  
    @MAC_Return int output,  
    @CACSCell_Return decimal(5,1) output,     
    @ACW decimal(6,4) output,  
    @CACSDescription varchar(150) output,  
    @AbstractID int,  
    @IntervCode int,             -- Added...New, 2002/06/25, it is the code value of @Procedure1 above.  
    @DispositionCode varchar(2),  -- Added...new, 2002/06/25, the CIHI value. 
    -- Added for the new 2003 CACS specs, 2004/02/20
    @AgeCode varchar(1),    -- CIHI value
    @Program varchar(12),   -- CIHI value
    @OOH1 varchar(12),    -- CIHI value
    @OOH2 varchar(12),    -- CIHI value
    @OOH3 varchar(12),    -- CIHI value
    @OOH4 varchar(12),    -- CIHI value
    @OOH5 varchar(12),    -- CIHI value
    @OOH6 varchar(12),    -- CIHI value
    @OOH7 varchar(12),    -- CIHI value
    @OOH8 varchar(12),    -- CIHI value
    @OOH9 varchar(12),    -- CIHI value
    @OOH10 varchar(12),    -- CIHI value
    @Status1 varchar(12),    -- CIHI value
    @Status2 varchar(12),    -- CIHI value
    @Status3 varchar(12),    -- CIHI value
    @Status4 varchar(12),    -- CIHI value
    @Status5 varchar(12),    -- CIHI value
    @Status6 varchar(12),    -- CIHI value
    @Status7 varchar(12),    -- CIHI value
    @Status8 varchar(12),    -- CIHI value
    @Status9 varchar(12),    -- CIHI value
    @Status10 varchar(12),    -- CIHI value
    @Location1 varchar(12),    -- CIHI value
    @Location2 varchar(12),    -- CIHI value
    @Location3 varchar(12),    -- CIHI value
    @Location4 varchar(12),    -- CIHI value
    @Location5 varchar(12),    -- CIHI value
    @Location6 varchar(12),    -- CIHI value
    @Location7 varchar(12),    -- CIHI value
    @Location8 varchar(12),    -- CIHI value
    @Location9 varchar(12),    -- CIHI value
    @Location10 varchar(12),    -- CIHI value
    @Extent1 varchar(12),    -- CIHI value
    @Extent2 varchar(12),    -- CIHI value
    @Extent3 varchar(12),    -- CIHI value
    @Extent4 varchar(12),    -- CIHI value
    @Extent5 varchar(12),    -- CIHI value
    @Extent6 varchar(12),    -- CIHI value
    @Extent7 varchar(12),    -- CIHI value
    @Extent8 varchar(12),   -- CIHI value
    @Extent9 varchar(12),    -- CIHI value
    @Extent10 varchar(12)    -- CIHI value
as  
    
--     print '@Procedure1: ' + @Procedure1 
--     print '@Diagnosis1: ' + @Diagnosis1 
--     print '@AbstractID: ' + cast(@AbstractID as varchar(10))
--     print '@Gender = ' + @Gender
--     print '-----------------'
    declare @CACSBranch varchar(4)  
    declare @DPGNumber varchar(16)   
    declare @ICode varchar(50)
    declare @IAttribStatusCIHI varchar(50)
    declare @IAttribLocationCIHI varchar(50)
    declare @IAttribExtentCIHI varchar(50)
    declare @IOOHIndicatorCIHI varchar(50)
    declare @CACSCell varchar(6)  
    declare @IProgramCIHI varchar(50)
    declare @RehabCategory varchar(10)
    declare @FilteredStatus varchar(2)
    declare @FilteredExtent varchar(2)
    declare @FilteredProgram varchar(2)
    declare @FilteredLocation varchar(12)
    declare @CACS_Temp varchar(10)
    declare @MHIntType varchar(30)
    declare @MajorInvestTech varchar(10)
    declare @MinorInvestTech int  
    declare @Mac int  
    declare @Occ int
    declare @RehabCount int
    declare @MentHlthCount int
    declare @PhysicalCount int
    declare @CognitiveCount int
    declare @InterventionCount int
    -- NB: Incoming Parameters are CIHI values.  
    set @AnesTech1   = isnull(@AnesTech1, '')
    set @Diagnosis1  = isnull(@Diagnosis1, '')
    set @Procedure1  = isnull(@Procedure1, '')
    set @Procedure2  = isnull(@Procedure2, '')
    set @Procedure3  = isnull(@Procedure3, '')
    set @Procedure4  = isnull(@Procedure4, '')
    set @Procedure5  = isnull(@Procedure5, '')
    set @Procedure6  = isnull(@Procedure6, '')
    set @Procedure7  = isnull(@Procedure7, '')
    set @Procedure8  = isnull(@Procedure8, '')
    set @Procedure9  = isnull(@Procedure9, '')
    set @Procedure10 = isnull(@Procedure10, '')
    set @OOH1  = isnull(@OOH1, '')
    set @OOH2  = isnull(@OOH2, '')
    set @OOH3  = isnull(@OOH3, '')
    set @OOH4  = isnull(@OOH4, '')
    set @OOH5  = isnull(@OOH5, '')
    set @OOH6  = isnull(@OOH6, '')
    set @OOH7  = isnull(@OOH7, '')
    set @OOH8  = isnull(@OOH8, '')
    set @OOH9  = isnull(@OOH9, '')
    set @OOH10  = isnull(@OOH10, '')
    set @Status1  = isnull(@Status1, '')
    set @Status2  = isnull(@Status2, '')
    set @Status3  = isnull(@Status3, '')
    set @Status4  = isnull(@Status4, '')
    set @Status5  = isnull(@Status5, '')
    set @Status6  = isnull(@Status6, '')
    set @Status7  = isnull(@Status7, '')
    set @Status8  = isnull(@Status8, '')
    set @Status9  = isnull(@Status9, '')
    set @Status10  = isnull(@Status10, '')
    set @Location1  = isnull(@Location1, '')
    set @Location2  = isnull(@Location2, '')
    set @Location3  = isnull(@Location3, '')
    set @Location4  = isnull(@Location4, '')
    set @Location5  = isnull(@Location5, '')
    set @Location6  = isnull(@Location6, '')
    set @Location7  = isnull(@Location7, '')
    set @Location8  = isnull(@Location8, '')
    set @Location9  = isnull(@Location9, '')
    set @Location10  = isnull(@Location10, '')
    set @Extent1  = isnull(@Extent1, '')
    set @Extent2  = isnull(@Extent2, '')
    set @Extent3  = isnull(@Extent3, '')
    set @Extent4  = isnull(@Extent4, '')
    set @Extent5  = isnull(@Extent5, '')
    set @Extent6  = isnull(@Extent6, '')
    set @Extent7  = isnull(@Extent7, '')
    set @Extent8  = isnull(@Extent8, '')
    set @Extent9  = isnull(@Extent9, '')
    set @Extent10  = isnull(@Extent10, '')
    set @Age = (case @AgeCode when 'Y' then @Age else 0 end)
    set @MAC = ''  
    set @CACSCell = ''  
    set @CACSBranch = ''  
    set @MajorInvestTech = ''
    set @MinorInvestTech = 0  
    set @PhysicalCount = 0
    set @CognitiveCount = 0
    set @RehabCount = 0
    set @MentHlthCount = 0
    -- Assign MAC based on Main Problem...  
    if @Diagnosis1 = ''  
    begin  
        -- Ungroupable when no diagnosis code.
        set @CACSCell = '9999'  
        set @MAC = '99'  
        goto FinalStep  
    end  
    else  
    begin  
        select @MAC = MAC, @CACSBranch = CACSBranch  
        from dbo.LU_CACS_I10DX_2003
        where (ICD10CACode = @Diagnosis1)    
      
        -- Consider it ungroupable if the diagnosis code is not in the CACS table  
        if isnull(@MAC, '') = ''
        begin  
            set @CACSCell = '9999'  
            set @MAC = '99'  
            goto FinalStep  
        end
        set @CACSCell = @CACSBranch  
    end  
    -- Check for Dead On Arrival (DOA) or Left without being seen...  
    set @CACSCell =   
        (case   
            when @DispositionCode = '11' then '9900' -- DOA  
            when @DispositionCode = '02' then '9905' -- Left without being seen  
            else @CACSCell  
        end)
    if @CACSCell in ('9900','9905') goto FinalStep  
    truncate table LU_CACS_Temp_2005
    
    if @Procedure1 <> ''
        insert LU_CACS_Temp_2005 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (1, @Procedure1, @Status1, @Extent1, @Location1, @OOH1, @Program)
    if @Procedure2 <> ''
        insert LU_CACS_Temp_2005 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (2, @Procedure2, @Status2, @Extent2, @Location2, @OOH2, @Program)
    if @Procedure3 <> ''
        insert LU_CACS_Temp_2005 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (3, @Procedure3, @Status3, @Extent3, @Location3, @OOH3, @Program)
    if @Procedure4 <> ''
        insert LU_CACS_Temp_2005 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (4, @Procedure4, @Status4, @Extent4, @Location4, @OOH4, @Program)
    if @Procedure5 <> ''
        insert LU_CACS_Temp_2005 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (5, @Procedure5, @Status5, @Extent5, @Location5, @OOH5, @Program)
    if @Procedure6 <> ''
        insert LU_CACS_Temp_2005 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (6, @Procedure6, @Status6, @Extent6, @Location6, @OOH6, @Program)
    if @Procedure7 <> ''
        insert LU_CACS_Temp_2005 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (7, @Procedure7, @Status7, @Extent7, @Location7, @OOH7, @Program)
    if @Procedure8 <> ''
        insert LU_CACS_Temp_2005 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (8, @Procedure8, @Status8, @Extent8, @Location8, @OOH8, @Program)
    if @Procedure9 <> ''
        insert LU_CACS_Temp_2005 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (9, @Procedure9, @Status9, @Extent9, @Location9, @OOH9, @Program)
    if @Procedure10 <> ''
        insert LU_CACS_Temp_2005 (Occ, IntervCode, IntervAttStatus, IntervAttExtent, IntervAttLocation, OOHIndicator, ProgramArea)
        values (10, @Procedure10, @Status10, @Extent10, @Location10, @OOH10, @Program)
    
    -- Filter the data...
    declare cur_Interv cursor local fast_forward for  
        select 
            Occ, -- i.IntervOccurrence,
            IntervCode,        -- i.IntervCode,
            IntervAttStatus,        -- i.IntervAttribStatus,
            IntervAttLocation,        -- i.IntervAttribLocation,
            IntervAttExtent,        -- i.IntervAttribExtent,
            OOHIndicator,        -- i.IntervOOHIndicator,
            ProgramArea         -- a.Program
        from LU_CACS_Temp_2005
        order by Occ
    open cur_Interv 
    while (1 = 1) 
    begin  
        fetch next from cur_Interv  
        into @Occ, @ICode, @IAttribStatusCIHI, @IAttribLocationCIHI, 
            @IAttribExtentCIHI, @IOOHIndicatorCIHI, @IProgramCIHI
    
        if (@@fetch_status <> 0) break 
    
        if isnull(@IOOHIndicatorCIHI, '') = 'Y' or isnull(@IAttribStatusCIHI, '') = 'A'
            update LU_CACS_Temp_2005
            set IgnoreData = 'Y'
    
            where occ = @Occ
        else
        begin
            -- Filter the IntervAttribStatus...
            if not exists (select * from LU_CACS_CACSTA_2003 where CCICode = @ICode and isnull(CCIStatusAttribute, '') = @IAttribStatusCIHI)
                set @FilteredStatus = ''
            else
                set @FilteredStatus = @IAttribStatusCIHI
            -- Filter the IntervAttribExtent...
            if not exists (select * from LU_CACS_CACEXT_2003 where CCICode = @ICode and isnull(CCIExtentAttribute, '') = @IAttribExtentCIHI)
                set @FilteredExtent = ''
            else
                set @FilteredExtent = @IAttribExtentCIHI
            -- Filter the IntervAttriLocation
            if not exists (select * from LU_CACS_DPGLOC_2003 where CCICode = @ICode and isnull(CCILocationAttribute, '') = @IAttribLocationCIHI)
                set @FilteredLocation = ''
            else
                set @FilteredLocation = @IAttribLocationCIHI
            -- Filter the Program...
            if not exists (select * from LU_CACS_CACPGM_2003 where CCICode = @ICode and isnull(ProgramArea, '') = @IProgramCIHI)
                set @FilteredProgram = ''
            else
                set @FilteredProgram = @IProgramCIHI
    
            update LU_CACS_Temp_2005
            set FilteredAttStatus = @FilteredStatus, 
                FilteredAttExtent = @FilteredExtent, 
                FilteredProgramArea = @FilteredProgram, 
                FilteredAttLocation = @FilteredLocation
            where Occ = @Occ
    
            -- Compute the MentalHealth count...
            if exists (select * from LU_CACS_INTMHCCI_2003 where CCICode = @ICode and isnull(CCIStatusAttribute, '') = @FilteredStatus and isnull(ProgramArea, '') = @FilteredProgram and isnull(CCIExtentAttribute, '') = @FilteredExtent)
            begin
                set @MentHlthCount = @MentHlthCount + 1
                update LU_CACS_Temp_2005 set IsMentalHealth = 'Y' where Occ = @Occ
            end
    
            -- Compute the Rehab count...
            set @RehabCategory = isnull((select RehabInterventionCategory from LU_CACS_INTRHCCI_2003 where CCICode = @ICode and isnull(CCIStatusAttribute, '') = @FilteredStatus and isnull(ProgramArea, '') = @FilteredProgram), '')
            if @RehabCategory <> ''
            begin
                set @RehabCount = @RehabCount + 1
                update LU_CACS_Temp_2005 
                set RehabCategory = @RehabCategory,
                    IsRehab = 'Y' 
                where Occ = @Occ        
            end
    
            if @RehabCategory = 'prhab'                  
                set @PhysicalCount = @PhysicalCount + 1  
            else if @RehabCategory = 'crhab'                  
                set @CognitiveCount = @CognitiveCount + 1 
        end
    end 
    
    close cur_Interv  
    deallocate cur_Interv  
    -- Retrieve the InterventionCount...
    select @InterventionCount = count(*) from LU_CACS_Temp_2005 --where isnull(IgnoreData, '') <> 'Y'
--     print '@InterventionCount = ' + cast(@InterventionCount as varchar(500))
    -- Retrieve info for Day Procedure...
    set @FilteredLocation = ''
    set @ICode = ''
    set @DPGNumber = ''
    -- Examine patient abstract for any Day Procedure in occurrence one...
    select 
        @FilteredLocation = isnull(FilteredAttLocation, ''),
        @ICode = isnull(IntervCode, '')
    from LU_CACS_Temp_2005 
    where Occ = 1 
    and isnull(IgnoreData, '') <> 'Y'
    -- Retrieve the DPG cell.
    select 
        @DPGNumber = isnull(DPGNumber, '')
    from dbo.LU_CACS_DPGCCI_2003
    where CCICode = @ICode
    and isnull(CCILocationAttribute, '') = @FilteredLocation 
    -- Is it Day Procedure???
    if (isnull(@DPGNumber, '') <> '')  
    begin  
--         print '@FilteredLocation = ' + cast(@FilteredLocation as varchar(500))
--         print '@ICode = ' + cast(@ICode as varchar(500))
--         print '@DPGNumber = ' + cast(@DPGNumber as varchar(500))
--         print '@AnesTech1 = ' + cast(@AnesTech1 as varchar(500))
        -- Further split the DPG cell
        if isnull(@DPGNumber, '') <> ''  
        begin  
--             print 'BEFORE: @CACSCell = ' + cast(@CACSCell as varchar(500))
            set @CACSCell = @DPGNumber  
            if @DPGNumber in ('1','15','48','50','52','65')  
                set @CACSCell =   
                    (Case  
                        when @AnesTech1 >= '1' And @AnesTech1 <= '4' then @CACSCell + '.1'  
                        when @AnesTech1 >= '5' And @AnesTech1 <= '6' then @CACSCell + '.2'  
                        when @AnesTech1 >= '7' And @AnesTech1 <= '9' then @CACSCell + '.3'  
                        else @CACSCell  
                    end)  
--             print 'AFTER: @CACSCell = ' + cast(@CACSCell as varchar(500))
            Goto FinalStep  
        end  
    end  
    -- Rehab and Mental Health...
    if exists (select * from LU_CACS_Temp_2005 where isnull(IgnoreData, '') <> 'Y')  
    Begin
--         print 'inside: Rehab and Mental Health...'
--         print '@MentHlthCount = ' + cast(@MentHlthCount as varchar(10))
--         print '@RehabCount = ' + cast(@RehabCount as varchar(10))
        if @MentHlthCount > @RehabCount
        begin
--             print 'inside: MentHlthCount > RehabCount'
            -- More MentalHealth than Rehab...
            set @MAC = '19'
            set @MHIntType = ''
            set @CACS_Temp = ''
            set @ICode = ''
            -- Find the first CACS for mental health intervention code and intervention type.
            declare cur_Mental cursor local fast_forward for
                select IntervCode, FilteredAttStatus, FilteredAttExtent, FilteredProgramArea
                from LU_CACS_Temp_2005
                where isnull(IsMentalHealth, '') = 'Y'
                and isnull(IgnoreData, '') <> 'Y'
                order by Occ
            open cur_Mental
            While (1 = 1) 
            begin  
                -- Loop through all mental health interventions and get the first availble CACS
                fetch next from cur_Mental  
                into @ICode, @FilteredStatus, @FilteredExtent, @FilteredProgram
                if (@@fetch_status <> 0) break 
    
                set @MHIntType = isnull((
                    select MentalHealthInterventionType 
                    from LU_CACS_INTMHCCI_2003 
                    where CCICode = @ICode 
                    and isnull(CCIStatusAttribute, '') = @FilteredStatus
                    and isnull(CCIExtentAttribute, '') = @FilteredExtent
                    and isnull(ProgramArea, '') = @FilteredProgram), '')
                -- Once the MentalHealthInterventionType is found, get the CACS. Otherwise, get the next mental health intervention.
                if isnull(@MHIntType, '') <> ''
                begin
                    -- Retrieve the MAC 19 CACS from the table, otherwise assign the default value for this MentalHealthInterventionType.
                    set @CACS_Temp = isnull((select CACS from dbo.LU_CACS_Mac19_2003 where ICD10CACode = @Diagnosis1 and IntervCode = @ICode and isnull(MHIntType, '') = @MHIntType), '')
                    if isnull(@CACS_Temp, '') = ''
                        set @CACSCell =  
                            (case  
                                when @MHIntType = 'LEGAL ASSESSMENT FULL DAY' then '1961'  
                                when @MHIntType = 'PSYCHOTHERAPY COUPLE' then '1962'  
                                when @MHIntType = 'INITIAL ASSESSMENT MH' then '1963'  
                                when @MHIntType = 'PSYCHOTHERAPY FAMILY'then '1964'  
                                when @MHIntType = 'PATIENT SPECIFIC HEARINGS' then '1965'  
                                when @MHIntType = 'RE-ASSESSMENT MG' then '1966'
                                when @MHIntType = 'SCREENING ASSESSMENT MH' then '1967'  
                                when @MHIntType = 'MED ADMIN/MANAGEMENT' then '1968'  
                                when @MHIntType = 'PSYCHOTHERAPY IND' then '1969'  
                                when @MHIntType = 'SERVICE PLANNING' then '1971'  
                                when @MHIntType = 'CRISIS INTERVENTION CALL' then '1972'  
                                when @MHIntType = 'LEGAL ASSESSMENT HALF DAY' then '1974'  
                                when @MHIntType = 'COUNSELLING EXT' then '1975'  
                                when @MHIntType = 'COUNSELLING INT' then '1976'
                                when @MHIntType = 'COUNSELLING BRIEF' then '1977'  
                                when @MHIntType = 'EDUCATION MH' then '1978'  
                                when @MHIntType = 'PSYCHOTHERAPY GROUP' then '1979'  
                                else @CACSCell
                            end)
                    else
                        set @CACSCell = @CACS_Temp
                    -- Exit loop...CACS found
                    break
                end
            end 
            close cur_Mental
            deallocate cur_mental
            goto FinalStep  
        end
        else if @RehabCount >= @MentHlthCount and @RehabCount <> 0
        begin
            -- print 'Inside: RehabCount >= MentHlthCount and RehabCount <> 0'
            -- Rehab >= MentalHealth...
            declare cur_Rehab cursor local fast_forward for
                select IntervCode, FilteredAttStatus, FilteredAttLocation, FilteredAttExtent, FilteredProgramArea, RehabCategory
                from LU_CACS_Temp_2005
                where isnull(IsRehab, '') = 'Y'
                and isnull(IgnoreData, '') <> 'Y'
                order by Occ
            open cur_Rehab
            
            while (1 = 1)
            begin
                fetch next from cur_Rehab
                into @ICode, @FilteredStatus, @FilteredLocation, @FilteredExtent, @FilteredProgram, @RehabCategory
                if (@@fetch_status <> 0) break
--             print '@RehabCategory = ' + @RehabCategory + '  ' + cast(len(@RehabCategory) as varchar(10))
--             The LU_CACS_RH_Diagnosis_2003 and LU_CACS_RH_Intervention_2003 are built from the html.
--             The following CCICode is not in the html but added manually to the table:
--             6AA30ZZZZ, 6KA50MD, 6KA50ME, 6KA50MP, 6KA50MR, 6KA50MZ.
--             They belong to the Cognitive Rehabilitation Interventions.
--             Wonder what other CCICode is missing from the html...
                set @CACS_Temp = isnull((
                    select d.CACS
                    from LU_CACS_RH_Diagnosis_2003 d
                        join LU_CACS_RH_Intervention_2003 i
                            on d.CACS = i.CACS
                    where d.ICD10CACode = @Diagnosis1
                    and i.CCICode = @ICode
                    and isnull(i.CCIStatus, '') = @FilteredStatus
--                     and isnull(i.CCILocation, '') = @FilteredLocation
--                     and isnull(i.CCIExtent, '') = @FilteredExtent
                    and isnull(i.CCIProgram, '') = @FilteredProgram), '')
--                 print '@Diagnosis1 = ' + @Diagnosis1 
--                 print '@ICode = ' + @ICode 
--                 print '@FilteredStatus = ' + @FilteredStatus 
--                 print '@FilteredLocation = ' + @FilteredLocation 
--                 print '@FilteredExtent = ' + @FilteredExtent 
--                 print '@FilteredProgram = ' + @FilteredProgram 
--                 print '@CACS_Temp = ' + @CACS_Temp 
                if isnull(@CACS_Temp, '') <> ''
                begin
                    -- Exit loop upon CACS found...
                    if @CACS_Temp in ('9400','9410','9420','9430','9440','9450',
                        '9460','9470','9480','9492','9510','9522') break
                    if @CACS_Temp = '9490' and @RehabCount < 3 break
                    if @CACS_Temp = '9496' and @RehabCount < 6  break
                    if @CACS_Temp = '9497' and @RehabCount > 1  break
                    if @CACS_Temp = '9498' and @RehabCount <= 1  break
                    if @CACS_Temp = '9500' and @RehabCount < 3  break
                    if @CACS_Temp = '9501' and @RehabCount < 6  break
                    if @CACS_Temp = '9502' and @PhysicalCount >= @CognitiveCount break
                    if @CACS_Temp = '9504' and @RehabCount > 1  break
                    if @CACS_Temp = '9506' and @RehabCount < 6  break
                    if @CACS_Temp = '9507' and @RehabCount > 1  break
                    if @CACS_Temp = '9508' and @RehabCount <= 1  break
                    if @CACS_Temp = '9512' and @RehabCount < 3  break
                    if @CACS_Temp = '9513' and @RehabCategory = 'commling' and @RehabCount < 6  break
                    if @CACS_Temp = '9513' and @RehabCategory = 'crhab' break
                    if @CACS_Temp = '9514' and @PhysicalCount >= @CognitiveCount  break
                    if @CACS_Temp = '9516' and @InterventionCount < 6  break
                    if @CACS_Temp = '9517' and @RehabCount > 1  break
                    if @CACS_Temp = '9518' and @RehabCount <= 1  break
                    if @CACS_Temp = '9520' and @RehabCount < 3  break
                    if @CACS_Temp = '9521' and @RehabCount < 6  break
                    if @CACS_Temp = '9526' and @RehabCount < 6  break
                    if @CACS_Temp = '9527' and @RehabCount > 1  break
                    if @CACS_Temp = '9528' and @RehabCount <= 1  break
                    if @CACS_Temp = '9530' and @RehabCount < 3  break
                    if @CACS_Temp = '9531' and @RehabCount < 6  break
                    if @CACS_Temp = '9532' and @PhysicalCount >= @CognitiveCount  break
                    if @CACS_Temp = '9534' and @RehabCategory = 'crhab' and @RehabCount < 1  break
                    if @CACS_Temp = '9534' and @RehabCategory = 'orhab' and  @RehabCount < 1  break
                    if @CACS_Temp = '9535' and @RehabCount <= 1  break
                    if @CACS_Temp = '9536' and @RehabCount < 6  break
                    if @CACS_Temp = '9534' and @RehabCount < 3  break
                    if @CACS_Temp = '9538' and @RehabCount <= 1  break
                    if @CACS_Temp = '9540' and @RehabCount < 3  break
                    if @CACS_Temp = '9541' and @RehabCount < 6  break
                    if @CACS_Temp = '9542' and @PhysicalCount >= @CognitiveCount  break
                    if @CACS_Temp = '9544' and @RehabCategory = 'crhab' and @RehabCount > 1  break
                    if @CACS_Temp = '9544' and @RehabCategory = 'orhab' and  @RehabCount > 1  break
                    if @CACS_Temp = '9545' and @RehabCategory = 'crhab' and @RehabCount <= 1  break
                    if @CACS_Temp = '9545' and @RehabCategory = 'orhab' and  @RehabCount <= 1  break
                    if @CACS_Temp = '9546' and @RehabCount < 6  break
                    if @CACS_Temp = '9550' and @RehabCount < 3  break
                    if @CACS_Temp = '9551' and @RehabCount < 6  break
                    if @CACS_Temp = '9552' and @RehabCategory = 'prhab' and @PhysicalCount >= @CognitiveCount and @RehabCount > 2  break
                    if @CACS_Temp = '9552' and @RehabCategory = 'orhab' and @RehabCount > 1  break
                    if @CACS_Temp = '9553' and @PhysicalCount >= @CognitiveCount and @RehabCount <= 2  break
                    if @CACS_Temp = '9556' and @RehabCount < 6  break
                    if @CACS_Temp = '9558' and @RehabCount <= 1  break
                    if @CACS_Temp = '9560'
                    begin 
                        set @CACS_Temp = 
                            (case
                                when @Age < 40 then '9560'
                                when @Age < 60 then '9562'
                                when @Age < 80 then '9564'
                                else '9566'
                            end)
                        break
                    end
                    if @CACS_Temp = '9570' and @RehabCount < 3  break
                    if @CACS_Temp = '9571' and @RehabCount < 6  break
                    if @CACS_Temp = '9572' and @PhysicalCount >= @CognitiveCount break
                    if @CACS_Temp = '9576' and @RehabCount < 6  break
                end
            end
            -- Keep the new CACS.
            if isnull(@CACS_Temp, '') <> ''
                set @CACSCell = @CACS_Temp
            close cur_Rehab
            deallocate cur_Rehab
--             print '@CACSCell = ' + cast (@CACSCell as varchar(20))
--             print '@CACS_Temp = ' + cast (@CACS_Temp as varchar(20))
--             print '@CACSCell = ' + cast (@CACSCell as varchar(20))
--             print 'Exiting... RehabCount >= MentHlthCount and RehabCount <> 0'
            goto FinalStep  
        end  
    end  
    -- Identify the Standard Investigative Technologies
    if exists (select * from LU_CACS_INVTECHCCI_2003
                where CCICode in (select IntervCode from LU_CACS_Temp_2005 where isnull(OOHIndicator, '') <> 'Y'))
        set @MinorInvestTech = 1           
    -- Assign diagnosis driven CACS based on interventions, gender and age.
    if @MAC = '1' 
    begin
        if @CACSCell = '100' and @MinorInvestTech = 0
            if @Age < 65
                set @CACSCell = '105'
            else
                set @CACSCell = '110'
        if @CACSCell = '160' and @MinorInvestTech = 0
            set @CACSCell = '165'
        if @CACSCell = '170' and @MinorInvestTech = 0
            set @CACSCell = '175'
        goto FinalStep
    end
    if @MAC = '2'
    begin
        if @CACSCell = '200' and @MinorInvestTech = 0
            if @Age < 45
                set @CACSCell = '210'
            else
                set @CACSCell = '215'
        goto FinalStep
    end
         
    if @MAC = '3'
    begin
--     print 'mac 3'
--     print '@MinorInvestTech = ' + cast (@MinorInvestTech as varchar(10))
        if @CACSCell = '300' and @MinorInvestTech = 0 
            set @CACSCell = '310'  
        goto FinalStep
    end
    if @MAC = '4' 
    begin  
        if @CACSCell = '400'
            if @MinorInvestTech = 1
            begin 
                if @Age >= 18
                    set @CACSCell = '410'
            end
            else
                if @Age < 65
                    set @CACSCell = '420'
                else
                    set @CACSCell = '430'
        goto FinalStep
    end  
    if @MAC = '5'
    begin
        if @CACSCell = '500' and @MinorInvestTech = 0
            set @CACSCell = '510'
        if @CACSCell = '570' and @MinorInvestTech = 0
            set @CACSCell = '580'
        goto FinalStep
    end
    if @MAC = '6' and @CACSBranch = '600'  
    begin  
        if @MinorInvestTech = 1 and @Age >= 18  
            set @CACSCell = '610'  
        if @MinorInvestTech = 0   
            set @CACSCell =   
                (Case   
                    when @Age < 18 then '620'  
                    when @Age >= 18 and @Age < 45 then '630'  
                    when @Age >= 45 then '640'  
                    else @CACSCell  
                end)  
        goto FinalStep
    end  
    if @MAC = '7' and @MinorInvestTech = 0
    begin  
        set @CACSCell = '710'  
        goto FinalStep
    end
  
    if @MAC = '8'  
    Begin
        if @CACSCell = '800' and @MinorInvestTech = 0
            set @CACSCell = '810'
        else if @CACSCell = '820' and @MinorInvestTech = 1 and @Age >= 18
            set @CACSCell = '825'
        else if @CACSCell = '820' and @MinorInvestTech = 0 and @Age < 18
            set @CACSCell = '830'
        else if @CACSCell = '820' and @MinorInvestTech = 0 and @Age >= 18
            set @CACSCell = '835'
        else if @CACSCell = '840' and @MinorInvestTech = 0 
            set @CACSCell = '850'
        else if @CACSCell = '860' and @MinorInvestTech = 0 
            set @CACSCell = '870'
        goto FinalStep
    end  
    if @MAC = '9' and @MinorInvestTech = 0 and @CACSBranch = '900'
    begin  
        if @Age < 18  
            set @CACSCell = '910'  
        else  
            set @CACSCell = '915'
        goto FinalStep
    end  
  
    if @MAC = '10' 
    begin
--         print 'Inside mac 10....'
--         print '@mac = ' + cast(@MAC_Return as varchar(100))
--         print '@CACSCell = ' + cast(@CACSCell as varchar(100))
--         print '@MinorInvestTech = ' + cast(@MinorInvestTech as varchar(100))
--         print '@Age = ' + cast(@Age as varchar(100))
--         print ''
        if @CACSCell = '1000' and @MinorInvestTech = 1 and @Age >= 18
            set @CACSCell = '1005'
        else if @CACSCell = '1000' and @MinorInvestTech = 0 and @Age < 6
            set @CACSCell = '1010'
        else if @CACSCell = '1000' and @MinorInvestTech = 0 and @Age >= 6
            set @CACSCell = '1015'
        else if @CACSCell = '1020' and @MinorInvestTech = 1 and @Age < 18
            set @CACSCell = '1000'
        else if @CACSCell = '1020' and @MinorInvestTech = 1 and @Age >= 18
            set @CACSCell = '1005' 
        else if @CACSCell = '1020' and @MinorInvestTech = 0 and @Age >= 18
            set @CACSCell = '1025' 
        goto FinalStep
    end
    if @MAC = '11'
    begin
--         print 'Inside mac 11....'
--         print '@mac = ' + cast(@MAC_Return as varchar(100))
--         print '@CACSCell = ' + cast(@CACSCell as varchar(100))
--         print '@MinorInvestTech = ' + cast(@MinorInvestTech as varchar(100))
--         print '@Age = ' + cast(@Age as varchar(100))
--         print '@Gender = ' + @Gender
--         print ''
        if @CACSCell = '1100' and @MinorInvestTech = 0 and @Age < 18 and @Gender = 'F'
            set @CACSCell = '1110'
        else if @CACSCell = '1100' and @MinorInvestTech = 0 and @Age >= 18 and @Gender = 'F'
            set @CACSCell = '1115'
        else if @CACSCell = '1130' and @MinorInvestTech = 0 and @Age < 18 and @Gender = 'F'
            set @CACSCell = '1110'
        else if @CACSCell = '1130' and @MinorInvestTech = 0 and @Age >= 18 and @Gender = 'F'
            set @CACSCell = '1115'
        else if @CACSCell = '1100' and @MinorInvestTech = 0 and @Age < 18 and @Gender = 'M'
            set @CACSCell = '1140'
        else if @CACSCell = '1100' and @MinorInvestTech = 0 and @Age >= 18 and @Gender = 'M'
            set @CACSCell = '1145'
        else if @CACSCell = '1130' and @MinorInvestTech = 0 and @Age < 18 and @Gender = 'M'
            set @CACSCell = '1140'
        else if @CACSCell = '1130' and @MinorInvestTech = 0 and @Age >= 18 and @Gender = 'M'
            set @CACSCell = '1145'
        else if @CACSCell = '1150' and @MinorInvestTech = 1 and @Age >= 18
            set @CACSCell = '1155'
        else if @CACSCell = '1150' and @MinorInvestTech = 0 and @Age < 18
            set @CACSCell = '1160'
        else if @CACSCell = '1150' and @MinorInvestTech = 0 and @Age >= 18
            set @CACSCell = '1165'
        goto FinalStep
    end
  
    if @MAC = '14' and @MinorInvestTech = 0
    begin 
        set @CACSCell =   
            (Case @CACSCell  
                when '1420' then '1430'  
                when '1490' then '1495'  
                else @CACSCell  
            end)
        goto FinalStep
    end
  
    if @MAC = '16' and @MinorInvestTech = 0
    begin  
        set @CACSCell =   
            (Case   
                when @Age < 18 then '1610'  
                when @Age >= 18 and @Age < 65 then '1615'  
                when @Age >= 65 then '1620'  
                else @CACSCell  
            end)
        goto FinalStep
    end
  
    if @MAC = '17' and @MinorInvestTech = 0 and @CACSBranch = '1700'
    begin  
        set @CACSCell = '1710'
        goto FinalStep
    end
 
    if @MAC = '18'
    begin  
        if @CACSCell = '1800' and @MinorInvestTech = 0 and @Age < 18
            set @CACSCell = '1810'
        if @CACSCell = '1800' and @MinorInvestTech = 0 and @Age >= 18
            set @CACSCell = '1815'
        if @CACSCell = '1820' and @MinorInvestTech = 0 and @Age < 18
            set @CACSCell = '1830'
        if @CACSCell = '1820' and @MinorInvestTech = 0 and @Age >= 18
            set @CACSCell = '1835'
        goto FinalStep
    end
    if @MAC = '20'
    begin
        if @CACSCell = '2000' and @MinorInvestTech = 0
            set @CACSCell = '2005'
        else if @MinorInvestTech = 1 and @CACSBranch in ('2030','2035','2040','2045','2050','2055')
            set @CACSCell = '2000'
        goto FinalStep
    end
FinalStep:
--     print '@MinorInvestTech = ' + cast(@MinorInvestTech as varchar(20))
    set @MajorInvestTech = isnull((
        select top 1 InvestigativeTechnologyType
        from dbo.LU_CACS_MITCCI_2003
        where CCICode in (
            select IntervCode from LU_CACS_Temp_2005 
            where isnull(OOHIndicator, '') <> 'Y')
        order by Hierarchy), '')
--     print '@MajorInvestTech = ' + cast(@MajorInvestTech as varchar(100))
    -- Return numeric values...  
    set @MAC_Return = cast(@mac as int)  
    set @CACSCell_Return = cast(@CACSCell as decimal(5,1))  
    select 
        @ACW = ACW,
        @CACSDescription = CACSDesc
    from LU_CACS_ACW_2005 
    where CACSBranch = @CACSCell
    and isnull(VisitDisposition, '') = @DispositionCode
    and isnull(InvestigativeTechnologyType, '') = isnull(@MajorInvestTech, '')
-- 
--     print '@MajorInvestTech = ' + isnull(cast(@MajorInvestTech as varchar(100)), '')
--     print '@mac = ' + isnull(cast(@MAC_Return as varchar(100)), '')
--     print '@CACSCell = ' + isnull(cast(@CACSCell_Return as varchar(100)), '')
--     print '@CACSDescription = ' + isnull(cast(@CACSDescription as varchar(100)), '')
--     print '@DispositionCode = ' + isnull(cast(@DispositionCode as varchar(100)), '')
--     print '@Age = ' + isnull(cast(@Age as varchar(100)), '')
--     print '@ACW = ' + isnull(cast(@ACW as varchar(100)), '')
-- 

	--Ticket 11969 Enhancement for CACS Auditing
	If isnull(@AbstractID, 0) > 0
	Begin
		Declare @AUMAC as Varchar(6)
		Declare @AUCACSCell as VarChar(20)
		Declare @AUACW as VarChar(20)
		Declare @AUAid as int
		SELECT @AUAid = Abstractid, @AUMAC = MAC, @AUCACSCell = CACSCell, @AUACW = ACW
		FROM AB_CACS where AbstractID = @AbstractID and OccurrenceNumber = 1 and CACS_Year = 2005
		If isnull(@AUAid, 0) > 0
		Begin
			If @AUMAC <> @MAC_Return
				Insert into AB_GrouperAudit Values (@AbstractID, 2005, 'MAC', @AUMAC, @MAC_Return, GetDate())
			If @AUCACSCell <> @CACSCell_Return
				Insert into AB_GrouperAudit Values (@AbstractID, 2005, 'CACSCell', @AUCACSCell, @CACSCell_Return, GetDate())
			If @AUACW <> @ACW
				Insert into AB_GrouperAudit Values (@AbstractID, 2005, 'ACW', @AUACW, @ACW, GetDate())
		End
	End

    -- For batch processing use...update the CACS table here.  Otherwise update it from vb.  
    if isnull(@AbstractID, 0) > 0  
    begin
        delete AB_CACS where Abstractid = @Abstractid and CACS_Year = 2005 and OccurrenceNumber = 1  
        if IsNull(@MAC, '') <> ''  
        begin  
            insert into [dbo].[AB_CACS] (AbstractID, OccurrenceNumber, CACS_Year, MAC, CACSCell, ACW, CACSDescription, InterventionCode) values   
            (@AbstractID, 1, 2005, @MAC_Return, @CACSCell_Return, @ACW, @CACSDescription, @IntervCode)  
        end  
    end  

    -- For DPG Ontario calculation...
    declare @CACSValue int
    declare @CACSDPGONValid int
    declare @HospCode int
    -- Set a arbitrary constant to determine if client has access to this calculation...
    set @CACSDPGONValid = 66101
    select @CACSValue = CACSDPGONValue from CACS_DPGON where CACSYear = 2005
    --select top 1 @HospCode = code from H_HospitalProfile order by code
    -- Criteria: Constant = HospitalCode + CACSValue
    --if (@AbstractID > 0) and  (@CACSValue + @HospCode = @CACSDPGONValid)
    if (@AbstractID > 0) and exists(select code from H_HospitalProfile where code + @CACSValue = 66101) --PR - 00993
    begin
        -- Check for 'abandon' intervention...
        if @Status1 = 'A'
            set @Procedure1 = 'Abandon'
		--PR - 02841 
		if exists (select abstractid from ab_Abstract where abstractid = @AbstractID and 
			miscode in (select code from lu_miscode where cihivalue like '7_262' or
			cihivalue like '7_34020%' or cihivalue like '7_34025%' or cihivalue like '7_34055' or
			cihivalue like '7_260%' or cihivalue like '7_265%'))
		Begin
	        exec P_LookupDPGON  @ICDType, 2004, @Procedure1, @Location1, @AbstractID
		End
    end

DoNothing:
return 0





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE   PROCEDURE [CACS_Grouping_2006]
    @ICDType varchar(1),  
    @AnesTech1 varchar(1),  
    @Age int,  
    @Gender varchar(1),  
    @Diagnosis1 varchar(10),  
    @Procedure1 varchar(10),  
    @Procedure2 varchar(10),  
    @Procedure3 varchar(10),  
    @Procedure4 varchar(10),  
    @Procedure5 varchar(10),  
    @Procedure6 varchar(10),  
    @Procedure7 varchar(10),  
    @Procedure8 varchar(10),  
    @Procedure9 varchar(10),  
    @Procedure10 varchar(10),  
    @EncounterNumber varchar(50),  
    @MAC_Return int output,  
    @CACSCell_Return decimal(5,1) output,     
    @ACW decimal(6,4) output,  
    @CACSDescription varchar(150) output,  
    @AbstractID int,  
    @IntervCode int,             
    @DispositionCode varchar(2), 
    @AgeCode varchar(1),    -- CIHI value
    @Program varchar(12),   -- CIHI value
    @OOH1 varchar(12),    -- CIHI value
    @OOH2 varchar(12),    -- CIHI value
    @OOH3 varchar(12),    -- CIHI value
    @OOH4 varchar(12),    -- CIHI value
    @OOH5 varchar(12),    -- CIHI value
    @OOH6 varchar(12),    -- CIHI value
    @OOH7 varchar(12),    -- CIHI value
    @OOH8 varchar(12),    -- CIHI value
    @OOH9 varchar(12),    -- CIHI value
    @OOH10 varchar(12),    -- CIHI value
    @Status1 varchar(12),    -- CIHI value
    @Status2 varchar(12),    -- CIHI value
    @Status3 varchar(12),    -- CIHI value
    @Status4 varchar(12),    -- CIHI value
    @Status5 varchar(12),    -- CIHI value
    @Status6 varchar(12),    -- CIHI value
    @Status7 varchar(12),    -- CIHI value
    @Status8 varchar(12),    -- CIHI value
    @Status9 varchar(12),    -- CIHI value
    @Status10 varchar(12),    -- CIHI value
    @Location1 varchar(12),    -- CIHI value
    @Location2 varchar(12),    -- CIHI value
    @Location3 varchar(12),    -- CIHI value
    @Location4 varchar(12),    -- CIHI value
    @Location5 varchar(12),    -- CIHI value
    @Location6 varchar(12),    -- CIHI value
    @Location7 varchar(12),    -- CIHI value
    @Location8 varchar(12),    -- CIHI value
    @Location9 varchar(12),    -- CIHI value
    @Location10 varchar(12),    -- CIHI value
    @Extent1 varchar(12),    -- CIHI value
    @Extent2 varchar(12),    -- CIHI value
    @Extent3 varchar(12),    -- CIHI value
    @Extent4 varchar(12),    -- CIHI value
    @Extent5 varchar(12),    -- CIHI value
    @Extent6 varchar(12),    -- CIHI value
    @Extent7 varchar(12),    -- CIHI value
    @Extent8 varchar(12),   -- CIHI value
    @Extent9 varchar(12),    -- CIHI value
    @Extent10 varchar(12)    -- CIHI value
as  
    declare @CACSCell varchar(6)  
    declare @cMajorInvestTech varchar(10)
    declare @Mac int  
	Declare @CACSCellHolding Varchar(6)
	declare @GYear as varchar(4)
	set @GYear = '2006'
    set @AnesTech1   = isnull(@AnesTech1, '')
    set @Diagnosis1  = isnull(@Diagnosis1, '')
    set @Procedure1  = isnull(@Procedure1, '')
    set @Procedure2  = isnull(@Procedure2, '')
    set @Procedure3  = isnull(@Procedure3, '')
    set @Procedure4  = isnull(@Procedure4, '')
    set @Procedure5  = isnull(@Procedure5, '')
    set @Procedure6  = isnull(@Procedure6, '')
    set @Procedure7  = isnull(@Procedure7, '')
    set @Procedure8  = isnull(@Procedure8, '')
    set @Procedure9  = isnull(@Procedure9, '')
    set @Procedure10 = isnull(@Procedure10, '')
    set @OOH1  = isnull(@OOH1, '')
    set @OOH2  = isnull(@OOH2, '')
    set @OOH3  = isnull(@OOH3, '')
    set @OOH4  = isnull(@OOH4, '')
    set @OOH5  = isnull(@OOH5, '')
    set @OOH6  = isnull(@OOH6, '')
    set @OOH7  = isnull(@OOH7, '')
    set @OOH8  = isnull(@OOH8, '')
    set @OOH9  = isnull(@OOH9, '')
    set @OOH10  = isnull(@OOH10, '')
    set @Status1  = isnull(@Status1, '')
    set @Status2  = isnull(@Status2, '')
    set @Status3  = isnull(@Status3, '')
    set @Status4  = isnull(@Status4, '')
    set @Status5  = isnull(@Status5, '')
    set @Status6  = isnull(@Status6, '')
    set @Status7  = isnull(@Status7, '')
    set @Status8  = isnull(@Status8, '')
    set @Status9  = isnull(@Status9, '')
    set @Status10  = isnull(@Status10, '')
    set @Location1  = isnull(@Location1, '')
    set @Location2  = isnull(@Location2, '')
    set @Location3  = isnull(@Location3, '')
    set @Location4  = isnull(@Location4, '')
    set @Location5  = isnull(@Location5, '')
    set @Location6  = isnull(@Location6, '')
    set @Location7  = isnull(@Location7, '')
    set @Location8  = isnull(@Location8, '')
    set @Location9  = isnull(@Location9, '')
    set @Location10  = isnull(@Location10, '')
    set @Extent1  = isnull(@Extent1, '')
    set @Extent2  = isnull(@Extent2, '')
    set @Extent3  = isnull(@Extent3, '')
    set @Extent4  = isnull(@Extent4, '')
    set @Extent5  = isnull(@Extent5, '')
    set @Extent6  = isnull(@Extent6, '')
    set @Extent7  = isnull(@Extent7, '')
    set @Extent8  = isnull(@Extent8, '')
    set @Extent9  = isnull(@Extent9, '')
    set @Extent10  = isnull(@Extent10, '')
    set @Age = (case @AgeCode when 'Y' then @Age else 0 end)
    set @MAC = ''  
    set @CACSCell = ''  
    set @cMajorInvestTech = ''

	--Initialize Intervention Table
	--Declare #IntervAll table (Occ int, IntervCode Varchar(10))
	Create Table #IntervAll  
		(Occ int, IntervCode Varchar(10) COLLATE Latin1_General_CI_AS)

    if @Procedure1 <> '' and @Status1 <> 'A' and @OOH1 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (1, @Procedure1)
    if @Procedure2 <> '' and @Status2 <> 'A' and @OOH2 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (2, @Procedure2)
    if @Procedure3 <> '' and @Status3 <> 'A' and @OOH3 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (3, @Procedure3)
    if @Procedure4 <> '' and @Status4 <> 'A' and @OOH4 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (4, @Procedure4)
    if @Procedure5 <> '' and @Status5 <> 'A' and @OOH5 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (5, @Procedure5)
    if @Procedure6 <> '' and @Status6 <> 'A' and @OOH6 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (6, @Procedure6)
    if @Procedure7 <> '' and @Status7 <> 'A' and @OOH7 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (7, @Procedure7)
    if @Procedure8 <> '' and @Status8 <> 'A' and @OOH8 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (8, @Procedure8)
    if @Procedure9 <> '' and @Status9 <> 'A' and @OOH9 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (9, @Procedure9)
    if @Procedure10 <> '' and @Status10 <> 'A' and @OOH10 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (10, @Procedure10)

    -- 4.4 Assign MAC based on Main Problem...  
    if @Diagnosis1 = ''  
    begin  
        -- Ungroupable when no diagnosis code.
        set @CACSCell = '9990'  
        set @MAC = '99'  
        goto IdentifyMajorInvestigativeTech  
    end  
    else  
    begin  
		Declare @cDiagGender as VarChar(1)
		Declare @cCACSSplit1 as VarChar(4)
        select @MAC = MAC, @cCACSSplit1 = CACSSplit1, @cDiagGender = ValidGender
        from dbo.Grouper_CACS_I10DX
        Where GYear = @GYear and  (ICD10CACode = @Diagnosis1) 
		--and ValidGender in ('B', @Gender)   
      
        -- Consider it ungroupable if the diagnosis code is not in the CACS table  
        if isnull(@MAC, '') = ''
        begin  
            set @CACSCell = '9990'  
            set @MAC = '99'  
            goto IdentifyMajorInvestigativeTech  
        end
    end  
	-- 4.5 Assign Intervention Cells
	-- 4.5.1-4.5.3
	declare @cIntervGender as Varchar(1)
	declare @cAnaesFlag as Varchar(1)
	declare @cIntervSplit as Varchar(4)
--check 1YM89LA and 1YM91LA here
	select top 1 @cAnaesFlag = AnaesFlag, @cIntervSplit = IntervSplit, @cIntervGender = IntervGender from [Grouper_CACS_IntervAss] Where GYear = @GYear and  ((IntervCode = @Procedure1 and LocAttribute = '98') or
	(IntervCode = @Procedure1 and LocAttribute = @Location1))
	order by LocAttribute desc
	-- 4.5.4
	if @cAnaesFlag is null
	Begin
		Set @cAnaesFlag = '8'
		Set @cIntervSplit = '3000'
	End

	-- 4.5.5
	if @cAnaesFlag = 'Y' and isnull(@AnesTech1, '') = ''
		Set @cIntervSplit = '9990'
	--4.5.6
	set @CACSCellHolding = ''
	select @CACSCellHolding = CACSCode from [Grouper_CACS_InterAnaesSplit] Where GYear = @GYear and  IntervSplit = @cIntervSplit and AnaesTech = @AnesTech1 and AnaesFlag = @cAnaesFlag
	set @CACSCell = @CACSCellHolding
	--4.5.7
	if isnull(@CACSCell, '') = ''
		set @CACSCell = @cIntervSplit 

	--4.5.8
	if isnull(@CACSCell, '') <> '3000' and @Status1 = 'A'
		set @CACSCell = '9990'
	--4.5.9
	Else if isnull(@CACSCell, '') <> '3000' and @OOH1 = 'Y'
		set @CACSCell = '3000'
	--4.5.10
	Else if isnull(@CACSCell, '') not in ('3000', '9990') and @cIntervGender <> @Gender and @Gender <> 'O'
		and @cIntervGender <> 'B'
		set @CACSCell = '9990'

	--4.6.1
	If @DispositionCode = '02'
	Begin
		set @CACSCell = '7010'
		Goto IdentifyMajorInvestigativeTech
	End
	--4.6.2
	Else If @DispositionCode = '11'
	Begin
		set @CACSCell = '7000'
		Goto IdentifyMajorInvestigativeTech
	End
	--4.7 Assign Rehab
/*--Rehab Debug Code
print 'Rehab Debug - CACS, Procedure1, Status1, ProgramCode: [Grouper_CACS_RehabInterv]'
print @CACSCell
Print @Procedure1
print @Status1
print @Program
*/
	--4.7.1
	If isnull(@CACSCell, '') <> '3000'
		goto AssignMentalHealth
	--4.7.2
	If @OOH1 = 'Y' or @Status1 = 'A'
		goto AssignMentalHealth
	--4.7.3
	Declare @cRehabIntervCat as Varchar(1)
	select top 1 @cRehabIntervCat = IntervCat from [Grouper_CACS_RehabInterv] 
	Where GYear = @GYear and  (IntervCode = @Procedure1 and StatusAttribute = @Status1 and ProgramArea = @Program)
	--4.7.4
	if isnull(@cRehabIntervCat, '') = ''
		select top 1 @cRehabIntervCat = IntervCat from [Grouper_CACS_RehabInterv] 
		Where GYear = @GYear and  (IntervCode = @Procedure1 and StatusAttribute = '98' and ProgramArea = @Program)
	--4.7.5
	if isnull(@cRehabIntervCat, '') = ''
		select top 1 @cRehabIntervCat = IntervCat from [Grouper_CACS_RehabInterv] 
		Where GYear = @GYear and  (IntervCode = @Procedure1 and StatusAttribute = '98' and ProgramArea = '98')
	--4.7.6
	if isnull(@cRehabIntervCat, '') = ''
		goto AssignMentalHealth
	--4.7.7

	Declare @cRehabSplit as Varchar(4)
	select @cRehabSplit = RehabDiagSplit from Grouper_CACS_RehabDiagSplitAss
	Where GYear = @GYear and  DiagCode = @Diagnosis1
	--4.7.8
	if isnull(@cRehabSplit, '') = ''
		print 'Troy Do Exception Flow 1'
	--4.7.9
	set @CACSCellHolding = ''
	select @CACSCellHolding = CACSCode from Grouper_CACS_RehabIntervCatAss 
	Where GYear = @GYear and  DiagSplit = @cRehabSplit and IntervCat = @cRehabIntervCat
	set @CACSCell = @CACSCellHolding
	--4.7.10
	if isnull(@CACSCell, '') = ''
		set @CACSCell = @cRehabSplit
	--4.7.11
	goto IdentifyMajorInvestigativeTech

	--4.8 Assign Mental
	AssignMentalHealth:
/*--MH Debug Code
print 'MH Debug - CACS, Procedure1, @Status1, @Extent1, ProgramCode: Grouper_CACS_MHIntervAss'
print @CACSCell
Print @Procedure1
print @Status1
print @Extent1
print @Program
*/
	--4.8.1, 4.8.3
	If isnull(@CACSCell, '') <> '3000' or @OOH1 = 'Y' or @Status1 = 'A'
		goto AssignCACSonMainProblem
	--4.8.4
	Declare @cMHIntervSplit as Varchar(4)
	select top 1 @cMHIntervSplit = MHIntervSplit from Grouper_CACS_MHIntervAss 
	Where GYear = @GYear and  (IntervCode = @Procedure1 and ProgramArea = @Program)

	--4.8.5
	if isnull(@cMHIntervSplit, '') = ''
		select top 1 @cMHIntervSplit = MHIntervSplit from Grouper_CACS_MHIntervAss 
		Where GYear = @GYear and  (IntervCode = @Procedure1 and ExtentAttribute = @Extent1)
	--4.8.6
	if isnull(@cMHIntervSplit, '') = ''
		select top 1 @cMHIntervSplit = MHIntervSplit from Grouper_CACS_MHIntervAss 
		Where GYear = @GYear and  (IntervCode = @Procedure1 and StatusAttribute = @Status1)
	--4.8.7
	if isnull(@cMHIntervSplit, '') = ''
		select top 1 @cMHIntervSplit = MHIntervSplit from Grouper_CACS_MHIntervAss 
		Where GYear = @GYear and  (IntervCode = @Procedure1 and StatusAttribute = '98' and ExtentAttribute = '98' and ProgramArea = '98')
	--4.8.8
	if isnull(@cMHIntervSplit, '') = ''
		goto AssignCACSonMainProblem
	--4.8.9
	set @CACSCellHolding = ''
	select @CACSCellHolding = CACSCode from Grouper_CACS_MHDiagTypeAss
	Where GYear = @GYear and  DiagCode = @Diagnosis1 and MHIntervSplit = @cMHIntervSplit
	set @CACSCell = @CACSCellHolding
	--4.8.10
	if isnull(@CACSCell, '') = ''
		Set @CACSCell = @cMHIntervSplit
	--4.8.11
	set @MAC = 19
	--4.8.12
	goto IdentifyMajorInvestigativeTech

	--4.9
	AssignCACSonMainProblem:

	--4.9.1
	If isnull(@CACSCell, '') <> '3000'
		goto IdentifyMajorInvestigativeTech
	--4.9.2
	if @cDiagGender in ('M', 'F') and @Gender <> @cDiagGender
	Begin
		Set @CACSCell = '9990'
		goto IdentifyMajorInvestigativeTech
	End
	--4.9.3
	Declare @cMinorInvTechFlag as VarChar(1)
	Set @cMinorInvTechFlag = 'N'
	Declare @cCACSSplit2 as Varchar(4)
	Set @cCACSSplit2 = ''
	--4.9.4, 4.9.5
	if exists (select * from Grouper_CACS_MinorInvestTech 
			Where GYear = @GYear and  IntervCode in (select IntervCode from #IntervAll))
		Set @cMinorInvTechFlag = 'Y'
	--4.9.6
	if @cMinorInvTechFlag = 'Y'
	Begin
		Select @cCACSSplit2 = CACSSplit2 from Grouper_CACS_MinorInvestTechSplit
		Where GYear = @GYear and  CACSSplit1 = @cCACSSplit1
		--4.9.7
		If isnull(@cCACSSplit2, '') = ''
			set @cCACSSplit2 = @cCACSSplit1
	End
	--4.9.8
	if @cMinorInvTechFlag <> 'Y'
		set @cCACSSplit2 = @cCACSSplit1
	--4.9.9
	set @CACSCellHolding = ''
	Select @CACSCellHolding = CACSCode from Grouper_CACS_AgeSplit
	Where GYear = @GYear and  CACSSplit2 = @cCACSSplit2 and AgeYears = @Age
	set @CACSCell = @CACSCellHolding
	--4.9.10
	if isnull(@CACSCell, '') = ''
		set @CACSCell = @cCACSSplit2

	--4.10 Identify Major Investigative Technology
	IdentifyMajorInvestigativeTech:
/*--IdentifyMajorInvestigativeTech Debug Code
print 'IdentifyMajorInvestigativeTech Debug - @CACSCell, Procedure1, @Procedure2, @Procedure3, @Procedure4: Grouper_CACS_MajorInvestTech'
print @CACSCell
Print @Procedure1
print @Procedure2
print @Procedure3
print @Procedure4
--End Debug
*/
	--4.10.2
	select top 1 @cMajorInvestTech = MajorInvTech from Grouper_CACS_MajorInvestTech
	Where GYear = @GYear and  IntervCode in (select IntervCode from #IntervAll) order by MajorInvTechRank
	--4.10.3
	if isnull(@cMajorInvestTech, 0) = 0
		Set @cMajorInvestTech = 0
	--4.10.4
	if @CACSCell in ('7000', '7010') and @cMajorInvestTech <> 0
		set @CACSCell = '9990'

	--4.11 Assign Weight
	set @CACSCell_Return = @CACSCell
	Set @MAC_Return = @MAC
	Select @ACW = CACSRIW, @CACSDescription = CACSDescription from Grouper_CACS_WeightAss
		Where GYear = @GYear and  CACSCode = @CACSCell_Return and VisitDisposition = @DispositionCode and
		MajorInvestTech = @cMajorInvestTech
/*
--Assign Weight Debug Code
print 'Assign Weight Debug - @cMajorInvestTech, @DispositionCode, @CACSCell_Return: Grouper_CACS_WeightAss'
print @cMajorInvestTech
print @DispositionCode
print @CACSCell_Return
--End Debug
*/
	If @CACSCell_Return = '9990' and isnull(@ACW, 0) = 0
		set @ACW = '0.0000'

	--Ticket 11969 Enhancement for CACS Auditing
	If isnull(@AbstractID, 0) > 0
	Begin
		Declare @AUMAC as Varchar(6)
		Declare @AUCACSCell as VarChar(20)
		Declare @AUACW as VarChar(20)
		Declare @AUAid as int
		SELECT @AUAid = Abstractid, @AUMAC = MAC, @AUCACSCell = CACSCell, @AUACW = ACW
		FROM AB_CACS Where AbstractID = @AbstractID and OccurrenceNumber = 1 and CACS_Year = @GYear
		If isnull(@AUAid, 0) > 0
		Begin
			If @AUMAC <> @MAC_Return
				Insert into AB_GrouperAudit Values (@AbstractID, @GYear, 'MAC', @AUMAC, @MAC_Return, GetDate())
			If @AUCACSCell <> @CACSCell_Return
				Insert into AB_GrouperAudit Values (@AbstractID, @GYear, 'CACSCell', @AUCACSCell, @CACSCell_Return, GetDate())
			If @AUACW <> @ACW
				Insert into AB_GrouperAudit Values (@AbstractID, @GYear, 'ACW', @AUACW, @ACW, GetDate())
		End
	End

    -- For batch processing use...update the CACS table here.  Otherwise update it from vb.  
    if isnull(@AbstractID, 0) > 0  
    begin
        delete AB_CACS Where Abstractid = @Abstractid and CACS_Year = @GYear and OccurrenceNumber = 1  
        if IsNull(@MAC, '') <> ''  
        begin  
            insert into [dbo].[AB_CACS] (AbstractID, OccurrenceNumber, CACS_Year, MAC, CACSCell, ACW, CACSDescription, InterventionCode) values   
            (@AbstractID, 1, @GYear, @MAC_Return, @CACSCell_Return, @ACW, @CACSDescription, @IntervCode)  
        end  
    end  

    -- For DPG Ontario calculation...
    declare @CACSValue int
    declare @CACSDPGONValid int
    declare @HospCode int
    -- Set a arbitrary constant to determine if client has access to this calculation...
    set @CACSDPGONValid = 66101
    select @CACSValue = CACSDPGONValue from CACS_DPGON Where CACSYear = @GYear
    --select top 1 @HospCode = code from H_HospitalProfile order by code
    -- Criteria: Constant = HospitalCode + CACSValue
    --if (@AbstractID > 0) and  (@CACSValue + @HospCode = @CACSDPGONValid)
    if (@AbstractID > 0) and exists(select code from H_HospitalProfile Where code + @CACSValue = 66101) --PR - 00993
    begin
		--EN - 00354
        -- Check for 'abandon' intervention...
        --if @Status1 = 'A'
        --    set @Procedure1 = 'Abandon'
        --exec P_LookupDPGON  @ICDType, 2006, @Procedure1, @Location1, @AbstractID
		--PR - 02841 
		if exists (select abstractid from ab_Abstract where abstractid = @AbstractID and 
			miscode in (select code from lu_miscode where cihivalue like '7_262' or
			cihivalue like '7_34020%' or cihivalue like '7_34025%' or cihivalue like '7_34055' or
			cihivalue like '7_260%' or cihivalue like '7_265%'))
		Begin
			Declare @CACSPAC10 as varchar(20)
			select top 1 @CACSPAC10 = CACSPAC10 from tGrouper_CACS_PAC10 where CACS = @CACSCell_Return 
				and VisitDisposition = @DispositionCode and cacs_year = CACS_Year
			delete AB_CACSON where abstractid = @AbstractID and cacs_year = @GYear
			insert into AB_CACSON (abstractid, CACS_Year, ACWON) values (@AbstractID, @GYear, @CACSPAC10)
		end
    end






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [CACS_Grouping_2007]
    @ICDType varchar(1),  
    @AnesTech1 varchar(1),  
    @Age int,  
    @Gender varchar(1),  
    @Diagnosis1 varchar(10),  
    @Procedure1 varchar(10),  
    @Procedure2 varchar(10),  
    @Procedure3 varchar(10),  
    @Procedure4 varchar(10),  
    @Procedure5 varchar(10),  
    @Procedure6 varchar(10),  
    @Procedure7 varchar(10),  
    @Procedure8 varchar(10),  
    @Procedure9 varchar(10),  
    @Procedure10 varchar(10),  
    @EncounterNumber varchar(50),  
    @MAC_Return int output,  
    @CACSCell_Return decimal(5,1) output,     
    @ACW decimal(6,4) output,  
    @CACSDescription varchar(150) output,  
    @AbstractID int,  
    @IntervCode int,             
    @DispositionCode varchar(2), 
    @AgeCode varchar(1),    -- CIHI value
    @Program varchar(12),   -- CIHI value
    @OOH1 varchar(12),    -- CIHI value
    @OOH2 varchar(12),    -- CIHI value
    @OOH3 varchar(12),    -- CIHI value
    @OOH4 varchar(12),    -- CIHI value
    @OOH5 varchar(12),    -- CIHI value
    @OOH6 varchar(12),    -- CIHI value
    @OOH7 varchar(12),    -- CIHI value
    @OOH8 varchar(12),    -- CIHI value
    @OOH9 varchar(12),    -- CIHI value
    @OOH10 varchar(12),    -- CIHI value
    @Status1 varchar(12),    -- CIHI value
    @Status2 varchar(12),    -- CIHI value
    @Status3 varchar(12),    -- CIHI value
    @Status4 varchar(12),    -- CIHI value
    @Status5 varchar(12),    -- CIHI value
    @Status6 varchar(12),    -- CIHI value
    @Status7 varchar(12),    -- CIHI value
    @Status8 varchar(12),    -- CIHI value
    @Status9 varchar(12),    -- CIHI value
    @Status10 varchar(12),    -- CIHI value
    @Location1 varchar(12),    -- CIHI value
    @Location2 varchar(12),    -- CIHI value
    @Location3 varchar(12),    -- CIHI value
    @Location4 varchar(12),    -- CIHI value
    @Location5 varchar(12),    -- CIHI value
    @Location6 varchar(12),    -- CIHI value
    @Location7 varchar(12),    -- CIHI value
    @Location8 varchar(12),    -- CIHI value
    @Location9 varchar(12),    -- CIHI value
    @Location10 varchar(12),    -- CIHI value
    @Extent1 varchar(12),    -- CIHI value
    @Extent2 varchar(12),    -- CIHI value
    @Extent3 varchar(12),    -- CIHI value
    @Extent4 varchar(12),    -- CIHI value
    @Extent5 varchar(12),    -- CIHI value
    @Extent6 varchar(12),    -- CIHI value
    @Extent7 varchar(12),    -- CIHI value
    @Extent8 varchar(12),   -- CIHI value
    @Extent9 varchar(12),    -- CIHI value
    @Extent10 varchar(12)    -- CIHI value
as  
    declare @CACSCell varchar(6)  
    declare @cMajorInvestTech varchar(10)
    declare @Mac int  
	Declare @CACSCellHolding Varchar(6)
	declare @GYear as varchar(4)
	set @GYear = '2007'
    set @AnesTech1   = isnull(@AnesTech1, '')
    set @Diagnosis1  = isnull(@Diagnosis1, '')
    set @Procedure1  = isnull(@Procedure1, '')
    set @Procedure2  = isnull(@Procedure2, '')
    set @Procedure3  = isnull(@Procedure3, '')
    set @Procedure4  = isnull(@Procedure4, '')
    set @Procedure5  = isnull(@Procedure5, '')
    set @Procedure6  = isnull(@Procedure6, '')
    set @Procedure7  = isnull(@Procedure7, '')
    set @Procedure8  = isnull(@Procedure8, '')
    set @Procedure9  = isnull(@Procedure9, '')
    set @Procedure10 = isnull(@Procedure10, '')
    set @OOH1  = isnull(@OOH1, '')
    set @OOH2  = isnull(@OOH2, '')
    set @OOH3  = isnull(@OOH3, '')
    set @OOH4  = isnull(@OOH4, '')
    set @OOH5  = isnull(@OOH5, '')
    set @OOH6  = isnull(@OOH6, '')
    set @OOH7  = isnull(@OOH7, '')
    set @OOH8  = isnull(@OOH8, '')
    set @OOH9  = isnull(@OOH9, '')
    set @OOH10  = isnull(@OOH10, '')
    set @Status1  = isnull(@Status1, '')
    set @Status2  = isnull(@Status2, '')
    set @Status3  = isnull(@Status3, '')
    set @Status4  = isnull(@Status4, '')
    set @Status5  = isnull(@Status5, '')
    set @Status6  = isnull(@Status6, '')
    set @Status7  = isnull(@Status7, '')
    set @Status8  = isnull(@Status8, '')
    set @Status9  = isnull(@Status9, '')
    set @Status10  = isnull(@Status10, '')
    set @Location1  = isnull(@Location1, '')
    set @Location2  = isnull(@Location2, '')
    set @Location3  = isnull(@Location3, '')
    set @Location4  = isnull(@Location4, '')
    set @Location5  = isnull(@Location5, '')
    set @Location6  = isnull(@Location6, '')
    set @Location7  = isnull(@Location7, '')
    set @Location8  = isnull(@Location8, '')
    set @Location9  = isnull(@Location9, '')
    set @Location10  = isnull(@Location10, '')
    set @Extent1  = isnull(@Extent1, '')
    set @Extent2  = isnull(@Extent2, '')
    set @Extent3  = isnull(@Extent3, '')
    set @Extent4  = isnull(@Extent4, '')
    set @Extent5  = isnull(@Extent5, '')
    set @Extent6  = isnull(@Extent6, '')
    set @Extent7  = isnull(@Extent7, '')
    set @Extent8  = isnull(@Extent8, '')
    set @Extent9  = isnull(@Extent9, '')
    set @Extent10  = isnull(@Extent10, '')
    set @Age = (case @AgeCode when 'Y' then @Age else 0 end)
    set @MAC = ''  
    set @CACSCell = ''  
    set @cMajorInvestTech = ''

	--Initialize Intervention Table
	--Declare #IntervAll table (Occ int, IntervCode Varchar(10))
	Create Table #IntervAll  
		(Occ int, IntervCode Varchar(10))

    if @Procedure1 <> '' and @Status1 <> 'A' and @OOH1 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (1, @Procedure1)
    if @Procedure2 <> '' and @Status2 <> 'A' and @OOH2 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (2, @Procedure2)
    if @Procedure3 <> '' and @Status3 <> 'A' and @OOH3 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (3, @Procedure3)
    if @Procedure4 <> '' and @Status4 <> 'A' and @OOH4 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (4, @Procedure4)
    if @Procedure5 <> '' and @Status5 <> 'A' and @OOH5 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (5, @Procedure5)
    if @Procedure6 <> '' and @Status6 <> 'A' and @OOH6 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (6, @Procedure6)
    if @Procedure7 <> '' and @Status7 <> 'A' and @OOH7 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (7, @Procedure7)
    if @Procedure8 <> '' and @Status8 <> 'A' and @OOH8 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (8, @Procedure8)
    if @Procedure9 <> '' and @Status9 <> 'A' and @OOH9 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (9, @Procedure9)
    if @Procedure10 <> '' and @Status10 <> 'A' and @OOH10 <> 'Y'
        insert #IntervAll (Occ, IntervCode) values (10, @Procedure10)

    -- 4.4 Assign MAC based on Main Problem...  
    if @Diagnosis1 = ''  
    begin  
        -- Ungroupable when no diagnosis code.
        set @CACSCell = '9990'  
        set @MAC = '99'  
        goto IdentifyMajorInvestigativeTech  
    end  
    else  
    begin  
		Declare @cDiagGender as VarChar(1)
		Declare @cCACSSplit1 as VarChar(4)
        select @MAC = MAC, @cCACSSplit1 = CACSSplit1, @cDiagGender = ValidGender
        from dbo.Grouper_CACS_I10DX
        Where GYear = @GYear and  (ICD10CACode = @Diagnosis1) 
		--and ValidGender in ('B', @Gender)   
      
        -- Consider it ungroupable if the diagnosis code is not in the CACS table  
        if isnull(@MAC, '') = ''
        begin  
            set @CACSCell = '9990'  
            set @MAC = '99'  
            goto IdentifyMajorInvestigativeTech  
        end
    end  
	-- 4.5 Assign Intervention Cells
	-- 4.5.1-4.5.3
	declare @cIntervGender as Varchar(1)
	declare @cAnaesFlag as Varchar(1)
	declare @cIntervSplit as Varchar(4)
--check 1YM89LA and 1YM91LA here
	select top 1 @cAnaesFlag = AnaesFlag, @cIntervSplit = IntervSplit, @cIntervGender = IntervGender from [Grouper_CACS_IntervAss] Where GYear = @GYear and  (IntervCode = @Procedure1 and LocAttribute = '98') or
	(IntervCode = @Procedure1 and LocAttribute = @Location1)
	order by LocAttribute desc
	-- 4.5.4
	if @cAnaesFlag is null
	Begin
		Set @cAnaesFlag = '8'
		Set @cIntervSplit = '3000'
	End

	-- 4.5.5
	if @cAnaesFlag = 'Y' and isnull(@AnesTech1, '') = ''
		Set @cIntervSplit = '9990'
	--4.5.6
	set @CACSCellHolding = ''
	select @CACSCellHolding = CACSCode from [Grouper_CACS_InterAnaesSplit] Where GYear = @GYear and  IntervSplit = @cIntervSplit and AnaesTech = @AnesTech1 and AnaesFlag = @cAnaesFlag
	set @CACSCell = @CACSCellHolding
	--4.5.7
	if isnull(@CACSCell, '') = ''
		set @CACSCell = @cIntervSplit 

	--4.5.8
	if isnull(@CACSCell, '') <> '3000' and @Status1 = 'A'
		set @CACSCell = '9990'
	--4.5.9
	Else if isnull(@CACSCell, '') <> '3000' and @OOH1 = 'Y'
		set @CACSCell = '3000'
	--4.5.10
	Else if isnull(@CACSCell, '') not in ('3000', '9990') and @cIntervGender <> @Gender and @Gender <> 'O'
		and @cIntervGender <> 'B'
		set @CACSCell = '9990'

	--4.6.1
	If @DispositionCode = '02'
	Begin
		set @CACSCell = '7010'
		Goto IdentifyMajorInvestigativeTech
	End
	--4.6.2
	Else If @DispositionCode = '11'
	Begin
		set @CACSCell = '7000'
		Goto IdentifyMajorInvestigativeTech
	End
	--4.7 Assign Rehab
--Rehab Debug Code
/*print 'Rehab Debug - CACS, Procedure1, Status1, ProgramCode: [Grouper_CACS_RehabInterv]'
print @CACSCell
Print @Procedure1
print @Status1
print @Program
*/
	--4.7.1
	If isnull(@CACSCell, '') <> '3000'
		goto AssignMentalHealth
	--4.7.2
	If @OOH1 = 'Y' or @Status1 = 'A'
		goto AssignMentalHealth
	--4.7.3
	Declare @cRehabIntervCat as Varchar(1)
	select top 1 @cRehabIntervCat = IntervCat from [Grouper_CACS_RehabInterv] 
	Where GYear = @GYear and  (IntervCode = @Procedure1 and StatusAttribute = @Status1 and ProgramArea = @Program)
	--4.7.4
	if isnull(@cRehabIntervCat, '') = ''
		select top 1 @cRehabIntervCat = IntervCat from [Grouper_CACS_RehabInterv] 
		Where GYear = @GYear and  (IntervCode = @Procedure1 and StatusAttribute = '98' and ProgramArea = @Program)
	--4.7.5
	if isnull(@cRehabIntervCat, '') = ''
		select top 1 @cRehabIntervCat = IntervCat from [Grouper_CACS_RehabInterv] 
		Where GYear = @GYear and  (IntervCode = @Procedure1 and StatusAttribute = '98' and ProgramArea = '98')
	--4.7.6
	if isnull(@cRehabIntervCat, '') = ''
		goto AssignMentalHealth
	--4.7.7

	Declare @cRehabSplit as Varchar(4)
	select @cRehabSplit = RehabDiagSplit from Grouper_CACS_RehabDiagSplitAss
	Where GYear = @GYear and  DiagCode = @Diagnosis1
	--4.7.8
	if isnull(@cRehabSplit, '') = ''
		print 'Troy Do Exception Flow 1'
	--4.7.9
	set @CACSCellHolding = ''
	select @CACSCellHolding = CACSCode from Grouper_CACS_RehabIntervCatAss 
	Where GYear = @GYear and  DiagSplit = @cRehabSplit and IntervCat = @cRehabIntervCat
	set @CACSCell = @CACSCellHolding
	--4.7.10
	if isnull(@CACSCell, '') = ''
		set @CACSCell = @cRehabSplit
	--4.7.11
	goto IdentifyMajorInvestigativeTech

	--4.8 Assign Mental
	AssignMentalHealth:
--MH Debug Code
/*print 'MH Debug - CACS, Procedure1, @Status1, @Extent1, ProgramCode: Grouper_CACS_MHIntervAss'
print @CACSCell
Print @Procedure1
print @Status1
print @Extent1
print @Program
*/
	--4.8.1, 4.8.3
	If isnull(@CACSCell, '') <> '3000' or @OOH1 = 'Y' or @Status1 = 'A'
		goto AssignCACSonMainProblem
	--4.8.4
	Declare @cMHIntervSplit as Varchar(4)
	select top 1 @cMHIntervSplit = MHIntervSplit from Grouper_CACS_MHIntervAss 
	Where GYear = @GYear and  (IntervCode = @Procedure1 and ProgramArea = @Program)

	--4.8.5
	if isnull(@cMHIntervSplit, '') = ''
		select top 1 @cMHIntervSplit = MHIntervSplit from Grouper_CACS_MHIntervAss 
		Where GYear = @GYear and  (IntervCode = @Procedure1 and ExtentAttribute = @Extent1)
	--4.8.6
	if isnull(@cMHIntervSplit, '') = ''
		select top 1 @cMHIntervSplit = MHIntervSplit from Grouper_CACS_MHIntervAss 
		Where GYear = @GYear and  (IntervCode = @Procedure1 and StatusAttribute = @Status1)
	--4.8.7
	if isnull(@cMHIntervSplit, '') = ''
		select top 1 @cMHIntervSplit = MHIntervSplit from Grouper_CACS_MHIntervAss 
		Where GYear = @GYear and  (IntervCode = @Procedure1 and StatusAttribute = '98' and ExtentAttribute = '98' and ProgramArea = '98')
	--4.8.8
	if isnull(@cMHIntervSplit, '') = ''
		goto AssignCACSonMainProblem
	--4.8.9
	set @CACSCellHolding = ''
	select @CACSCellHolding = CACSCode from Grouper_CACS_MHDiagTypeAss
	Where GYear = @GYear and  DiagCode = @Diagnosis1 and MHIntervSplit = @cMHIntervSplit
	set @CACSCell = @CACSCellHolding
	--4.8.10
	if isnull(@CACSCell, '') = ''
		Set @CACSCell = @cMHIntervSplit
	--4.8.11
	set @MAC = 19
	--4.8.12
	goto IdentifyMajorInvestigativeTech

	--4.9
	AssignCACSonMainProblem:

	--4.9.1
	If isnull(@CACSCell, '') <> '3000'
		goto IdentifyMajorInvestigativeTech
	--4.9.2
	if @cDiagGender in ('M', 'F') and @Gender <> @cDiagGender
	Begin
		Set @CACSCell = '9990'
		goto IdentifyMajorInvestigativeTech
	End
	--4.9.3
	Declare @cMinorInvTechFlag as VarChar(1)
	Set @cMinorInvTechFlag = 'N'
	Declare @cCACSSplit2 as Varchar(4)
	Set @cCACSSplit2 = ''
	--4.9.4, 4.9.5

	if exists (select * from Grouper_CACS_MinorInvestTech 
			Where GYear = @GYear and  IntervCode in (select IntervCode from #IntervAll))
		Set @cMinorInvTechFlag = 'Y'
	--4.9.6
	if @cMinorInvTechFlag = 'Y'
	Begin
		Select @cCACSSplit2 = CACSSplit2 from Grouper_CACS_MinorInvestTechSplit
		Where GYear = @GYear and  CACSSplit1 = @cCACSSplit1
		--4.9.7
		If isnull(@cCACSSplit2, '') = ''
			set @cCACSSplit2 = @cCACSSplit1
	End
	--4.9.8
	if @cMinorInvTechFlag <> 'Y'
		set @cCACSSplit2 = @cCACSSplit1
	--4.9.9
	set @CACSCellHolding = ''
	Select @CACSCellHolding = CACSCode from Grouper_CACS_AgeSplit
	Where GYear = @GYear and  CACSSplit2 = @cCACSSplit2 and AgeYears = @Age
	set @CACSCell = @CACSCellHolding
	--4.9.10
	if isnull(@CACSCell, '') = ''
		set @CACSCell = @cCACSSplit2

	--4.10 Identify Major Investigative Technology
	IdentifyMajorInvestigativeTech:
--IdentifyMajorInvestigativeTech Debug Code
/*print 'IdentifyMajorInvestigativeTech Debug - @CACSCell, Procedure1, @Procedure2, @Procedure3, @Procedure4: Grouper_CACS_MajorInvestTech'
print @CACSCell
Print @Procedure1
print @Procedure2
print @Procedure3
print @Procedure4*/
--End Debug

	--4.10.2
	select top 1 @cMajorInvestTech = MajorInvTech from Grouper_CACS_MajorInvestTech
	Where GYear = @GYear and  IntervCode in (select IntervCode from #IntervAll) order by MajorInvTechRank
	--4.10.3
	if isnull(@cMajorInvestTech, 0) = 0
		Set @cMajorInvestTech = 0
	--4.10.4
	if @CACSCell in ('7000', '7010') and @cMajorInvestTech <> 0
		set @CACSCell = '9990'

	--4.11 Assign Weight
	set @CACSCell_Return = @CACSCell
	Set @MAC_Return = @MAC
	Select @ACW = CACSRIW, @CACSDescription = CACSDescription from Grouper_CACS_WeightAss
		Where GYear = @GYear and  CACSCode = @CACSCell_Return and VisitDisposition = @DispositionCode and
		MajorInvestTech = @cMajorInvestTech
/*--Assign Weight Debug Code
print 'Assign Weight Debug - @cMajorInvestTech, @DispositionCode, @CACSCell_Return: Grouper_CACS_WeightAss'
print @cMajorInvestTech
print @DispositionCode
print @CACSCell_Return
--End Debug
*/	
	If @CACSCell_Return = '9990' and isnull(@ACW, 0) = 0
		set @ACW = '0.0000'

	--Ticket 11969 Enhancement for CACS Auditing
	If isnull(@AbstractID, 0) > 0
	Begin
		Declare @AUMAC as Varchar(6)
		Declare @AUCACSCell as VarChar(20)
		Declare @AUACW as VarChar(20)
		Declare @AUAid as int
		SELECT @AUAid = Abstractid, @AUMAC = MAC, @AUCACSCell = CACSCell, @AUACW = ACW
		FROM AB_CACS Where AbstractID = @AbstractID and OccurrenceNumber = 1 and CACS_Year = @GYear
		If isnull(@AUAid, 0) > 0
		Begin
			If @AUMAC <> @MAC_Return
				Insert into AB_GrouperAudit Values (@AbstractID, @GYear, 'MAC', @AUMAC, @MAC_Return, GetDate())
			If @AUCACSCell <> @CACSCell_Return
				Insert into AB_GrouperAudit Values (@AbstractID, @GYear, 'CACSCell', @AUCACSCell, @CACSCell_Return, GetDate())
			If @AUACW <> @ACW
				Insert into AB_GrouperAudit Values (@AbstractID, @GYear, 'ACW', @AUACW, @ACW, GetDate())
		End
	End

    -- For batch processing use...update the CACS table here.  Otherwise update it from vb.  
    if isnull(@AbstractID, 0) > 0  
    begin
        delete AB_CACS Where Abstractid = @Abstractid and CACS_Year = @GYear and OccurrenceNumber = 1  
        if IsNull(@MAC, '') <> ''  
        begin  
            insert into [dbo].[AB_CACS] (AbstractID, OccurrenceNumber, CACS_Year, MAC, CACSCell, ACW, CACSDescription, InterventionCode) values   
            (@AbstractID, 1, @GYear, @MAC_Return, @CACSCell_Return, @ACW, @CACSDescription, @IntervCode)  
        end  
    end  

    -- For DPG Ontario calculation...
    declare @CACSValue int
    declare @CACSDPGONValid int
    declare @HospCode int
    -- Set a arbitrary constant to determine if client has access to this calculation...
    set @CACSDPGONValid = 66101
    select @CACSValue = CACSDPGONValue from CACS_DPGON Where CACSYear = @GYear
    --select top 1 @HospCode = code from H_HospitalProfile order by code
    -- Criteria: Constant = HospitalCode + CACSValue

    --if (@AbstractID > 0) and  (@CACSValue + @HospCode = @CACSDPGONValid)
    if (@AbstractID > 0) and exists(select code from H_HospitalProfile Where code + @CACSValue = 66101) --PR - 00993
    begin
        -- Check for 'abandon' intervention...
        if @Status1 = 'A'
            set @Procedure1 = 'Abandon'
        exec P_LookupDPGON  @ICDType, 2006, @Procedure1, @Location1, @AbstractID
    end




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [cmdDiagFile10Select]
AS
	SET NOCOUNT ON;
SELECT Code, DisplayCode, UserDescription, DefaultDescription, CIHIValue, ValidFrom, ValidTo, ICD9, ICD9cm, Sector, CIHIFlag, MRDxFlag, NewbornFlag, TypeCode, DiagnosisGender, AgeLow, AgeHigh, InterfaceIn, ICDNotes, ProjectLink FROM ICD_DiagFile10


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [cmdIPCDiagFile10Select]
AS
	SET NOCOUNT ON;
SELECT Code, DisplayCode, UserDescription, DefaultDescription, CIHIValue, ValidFrom, ValidTo, ICD9, ICD9cm, Sector, CIHIFlag, MRDxFlag, NewbornFlag, TypeCode, DiagnosisGender, AgeLow, AgeHigh, InterfaceIn, ICDNotes, ProjectLink FROM ICD_DiagFile10


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [CS_Security]
	@UserName as varchar(200), 
	@ComputerName as varchar(200), 
	@HospitalID as int,
	@Coder as int,
	@Users as int,
	@YesNo as int output
AS

	--Clean the dead connection, Just assume coder use codersmart less than 30 minutes each time.
	Delete from M_CodeSmart where datediff(minute, LoginDate, getdate()) > 30
	
	set @YesNo = 0
	if @Coder <= 2 
		Set @YesNo = 1
	else
	begin
		If exists (select * from M_CodeSmart where UserName = @UserName and ComputerName = @ComputerName) 
		begin
			update M_CodeSmart set LoginDate = getdate() where UserName = @UserName and ComputerName = @ComputerName
		 	Set @YesNo = 1
		end
		Else If @Users > isnull((select count(*) from M_CodeSmart where isnull(HospitalID, 0) in (0, isnull(@HospitalID, 0)) or isnull(@HospitalID, 0) = 0) + 1, 0)
		Begin
			Insert into M_CodeSmart(UserName, ComputerName, HospitalID, LoginDate)
			select @UserName, @ComputerName, @HospitalID, getdate()
			Set @YesNo = 1
		End
	end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create procedure [D_AB_AB_QBP_Flag]
    @AbstractID int
as
    delete from dbo.AB_QBP_Flag where AbstractID = @AbstractID
    
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [D_AB_Abstract] 
	(@AbstractID 	[int], 
	 @AppID 	[int])
AS 

delete AB_Abstract where ([AbstractID] = @AbstractID)
delete AB_Ancillary where ([AbstractID] = @AbstractID)
delete AB_BasicOption where ([AbstractID] = @AbstractID)
delete AB_Blood where ([AbstractID] = @AbstractID)
delete AB_CACS where ([AbstractID] = @AbstractID)
delete AB_CACS_Investigative where ([AbstractID] = @AbstractID)

delete AB_CancerStaging where ([AbstractID] = @AbstractID)
delete AB_CCM_CancerCareInformation where ([AbstractID] = @AbstractID)
delete AB_CCM_Radiation where ([AbstractID] = @AbstractID)
delete AB_CCM_SystemicDrug where ([AbstractID] = @AbstractID)

delete AB_CIHIErrors where ([AbstractID] = @AbstractID)
delete AB_CMG where ([AbstractID] = @AbstractID)
delete AB_CMG_FI where ([AbstractID] = @AbstractID)
delete AB_Consult where ([AbstractID] = @AbstractID)
delete AB_DeathInformation where ([AbstractID] = @AbstractID)
delete AB_Diagnosis where ([AbstractID] = @AbstractID)
delete AB_DPG where ([AbstractID] = @AbstractID)
delete AB_DischargeDiagnosis where ([AbstractID] = @AbstractID)

delete AB_ErrorMessageFields where [AbstractID] = @AbstractID and ([AppID] = @AppID or (Appid = 200 and @AppID = 201))
delete AB_ErrorMessages where [AbstractID] = @AbstractID and ([AppID] = @AppID or (Appid = 200 and @AppID = 201))
delete AB_GrouperAudit where ([AbstractID] = @AbstractID)
delete AB_HIG where ([AbstractID] = @AbstractID)

delete AB_Intervention where ([AbstractID] = @AbstractID)
delete AB_Intervention_Replicate where ([AbstractID] = @AbstractID)
--PR - 05167 WinRecs send appid = 201 Inpatient instead of CCR 200.
delete AB_Main where ([AbstractID] = @AbstractID and ([AppID] = @AppID or (Appid = 200 and @AppID = 201)))   
--delete AB_Main where ([AppID] = @AppID and [AbstractID] = @AbstractID)
delete AB_MainHistory where ([AbstractID] = @AbstractID)
delete AB_Manitoba where ([AbstractID] = @AbstractID)
delete AB_MB_ALC where ([AbstractID] = @AbstractID)
delete AB_MB_FacilityStudy where ([AbstractID] = @AbstractID)
delete AB_MB_NonALC where ([AbstractID] = @AbstractID)
delete AB_MentalHealth where ([AbstractID] = @AbstractID)
delete AB_MIS where ([AbstractID] = @AbstractID)
delete AB_NACRS10_Errors where ([AbstractID] = @AbstractID)
delete AB_NACRS where ([AbstractID] = @AbstractID)

--delete AB_Notes where ([AbstractID] = @AbstractID) --The Notes are now stored in REC_Notes
delete AB_PatientService where ([AbstractID] = @AbstractID)
delete AB_PresentingComplaints where ([AbstractID] = @AbstractID)
delete AB_Project where ([AbstractID] = @AbstractID)
delete AB_Provider where ([AbstractID] = @AbstractID)
delete AB_ReproductiveCare where ([AbstractID] = @AbstractID)
delete AB_SpecialCareUnit where ([AbstractID] = @AbstractID)
delete AB_Therapeutic where ([AbstractID] = @AbstractID)
delete AB_TransferService where ([AbstractID] = @AbstractID)
delete AB_UDAbstracting where ([AbstractID] = @AbstractID) -- [RM 2006/04/03]
delete AB_UpdateAudit where [AbstractID] = @AbstractID and ([AppID] = @AppID or (Appid = 200 and @AppID = 201))
delete AB_UpdateHistory where ([AbstractID] = @AbstractID)
delete AB_VendorAssigned where ([AbstractID] = @AbstractID)
delete REC_Notes where AppID = @AppID and RecordID = @AbstractID

DELETE AB_Diagnosis_CodeSmart WHERE ([AbstractID] = @AbstractID)
DELETE AB_Intervention_CodeSmart WHERE ([AbstractID] = @AbstractID)
DELETE AB_SurgicalProcedure WHERE ([AbstractID] = @AbstractID)

delete [AB_UDFieldsDate] where ([AbstractID] = @AbstractID)
delete [AB_UDFieldsInteger] where ([AbstractID] = @AbstractID)
delete [AB_UDFieldsLookUp] where ([AbstractID] = @AbstractID)
delete [AB_UDFieldsSmallText] where ([AbstractID] = @AbstractID)
delete [AB_UDFieldsText] where ([AbstractID] = @AbstractID)
delete [AB_UDFieldsTime] where ([AbstractID] = @AbstractID)

delete AB_EDInterventionPicklist where ([AbstractID] = @AbstractID)
delete AB_InvestigativeTechnology where ([AbstractID] = @AbstractID)
delete AB_EDInterventionValueSet where ([AbstractID] = @AbstractID)

delete AB_QBP_Flag where ([AbstractID] = @AbstractID)
delete AB_CJRR where ([AbstractID] = @AbstractID)
delete AB_CJRR_Parts where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_AB_Ancillary]	(@AbstractID [int])
AS 

DELETE [AB_Ancillary] WHERE ([AbstractID] = @AbstractID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_AB_BasicOption] (@AbstractID [int])
AS
 
DELETE [AB_BasicOption] WHERE ([AbstractID] = @AbstractID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_AB_Blood] (@AbstractID [int])
AS 

DELETE [AB_Blood] WHERE ([AbstractID] = @AbstractID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [D_AB_CACS] 
	(@AbstractID 	[int])
AS 

Delete from dbo.AB_CACS_Investigative
from dbo.AB_CACS_Investigative AB_CACS_Investigative
    inner join AB_CACS 
    on AB_CACS_Investigative.AbstractID = AB_CACS.AbstractID 
        and AB_CACS_Investigative.OccurrenceNumber = AB_CACS.OccurrenceNumber 
        and AB_CACS_Investigative.CACS_Year = AB_CACS.CACS_Year
where AB_CACS_Investigative.[AbstractID] = @AbstractID and isnull(IsFixed , 0) <> 1    

DELETE AB_CACS WHERE ([AbstractID] = @AbstractID) and isnull(IsFixed , 0) <> 1
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE   PROCEDURE [D_AB_CACS_Single] 
	(@AbstractID 	[int],
	@CACS_Year	[int],
	@Occurance 	[int])
AS 

DELETE AB_CACS WHERE ([AbstractID] = @AbstractID) AND CACS_Year = @CACS_Year AND OccurrenceNumber = @Occurance
and isnull(IsFixed , 0) <> 1
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_AB_CancerStaging] (@AbstractID [int])
AS 

DELETE [AB_CancerStaging] WHERE ([AbstractID] = @AbstractID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [D_AB_CCM_CancerCareInformation]
    @AbstractID int
as
    delete from dbo.AB_CCM_CancerCareInformation where AbstractID = @AbstractID
    
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [D_AB_CCM_Radiation]
    @AbstractID int
as
    delete from dbo.AB_CCM_Radiation where AbstractID = @AbstractID
   
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [D_AB_CCM_SystemicDrug]
    @AbstractID int
as
    delete from dbo.AB_CCM_SystemicDrug where AbstractID = @AbstractID
   
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE   PROCEDURE [D_AB_CMG] 
	(@AbstractID 	[int])
AS 

DELETE AB_CMG WHERE ([AbstractID] = @AbstractID) and isnull(IsFixed , 0) <> 1
delete from ab_cmg_fi
from ab_cmg_fi left join ab_cmg on 
    AB_CMG.AbstractID = ab_cmg_fi.AbstractID and 
    AB_CMG.OccurrenceNumber = ab_cmg_fi.OccurrenceNumber and 
    AB_CMG.CMG_Year = ab_cmg_fi.CMG_Year  
WHERE (ab_cmg_fi.[AbstractID] = @AbstractID) and ab_cmg.AbstractID is null 

delete from AB_HIG WHERE [AbstractID] = @AbstractID and isnull(IsFixed , 0) <> 1
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE   PROCEDURE [D_AB_CMG_Single] 
	(@AbstractID 	[int],
	@CMG_Year	[int],
	@Occurance 	[int])
AS 

delete from ab_cmg_fi
from ab_cmg_fi inner join ab_cmg on 
    AB_CMG.AbstractID = ab_cmg_fi.AbstractID and 
    AB_CMG.OccurrenceNumber = ab_cmg_fi.OccurrenceNumber and 
    AB_CMG.CMG_Year = ab_cmg_fi.CMG_Year  
WHERE (ab_cmg_fi.[AbstractID] = @AbstractID) and ab_cmg_fi.CMG_Year = @CMG_Year AND ab_cmg_fi.OccurrenceNumber = @Occurance
and isnull(AB_CMG.IsFixed , 0) <> 1

DELETE AB_CMG WHERE ([AbstractID] = @AbstractID) AND CMG_Year = @CMG_Year AND OccurrenceNumber = @Occurance
and isnull(IsFixed , 0) <> 1
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
cREATE PROCEDURE [D_AB_Consult] (@AbstractID [int])
AS 

DELETE [dbo].[AB_Consult] WHERE ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_AB_DeathInformation] (@AbstractID [int])
AS 

DELETE [AB_DeathInformation] WHERE ([AbstractID]	= @AbstractID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_AB_Diagnosis] (@AbstractID [int])
AS 

DELETE [AB_Diagnosis] WHERE ([AbstractID] = @AbstractID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_AB_Diagnosis_CodeSmart] (@AbstractID[int])
AS 

DELETE AB_Diagnosis_CodeSmart WHERE ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

create PROCEDURE [D_AB_DischargeDiagnosis] (@AbstractID [int])
AS 

delete [AB_DischargeDiagnosis] where ([AbstractID] = @AbstractID)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [D_AB_DPG] 
	(@AbstractID 	[int])
AS 
DELETE AB_DPG WHERE ([AbstractID] = @AbstractID) and isnull(IsFixed , 0) <> 1
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE   PROCEDURE [D_AB_DPG_Single] 
	(@AbstractID 	[int],
	@DPG_Year	[int],
	@Occurance 	[int])
AS 

DELETE AB_DPG WHERE ([AbstractID] = @AbstractID) AND DPG_Year = @DPG_Year AND OccurrenceNumber = @Occurance
and isnull(IsFixed , 0) <> 1
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [D_AB_EDInterventionPicklist](
	@AbstractID int)
as
	delete from [dbo].[AB_EDInterventionPicklist] where AbstractID = @AbstractID
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create procedure [D_AB_EDInterventionValueSet]
	@AbstractID [int]
as
	delete AB_EDInterventionValueSet where [AbstractID] = @AbstractID
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_AB_Intervention] (@AbstractID [int])
AS 

DELETE [AB_Intervention] WHERE ([AbstractID] = @AbstractID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_AB_Intervention_CodeSmart] (@AbstractID[int])
AS 

DELETE AB_Intervention_CodeSmart WHERE ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [D_AB_InvestigativeTechnology](
	@AbstractID int)
as
	delete from [dbo].[AB_InvestigativeTechnology] where AbstractID = @AbstractID
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE  PROCEDURE [D_AB_Main] 
	(@UniversalID 	[int])
AS 
DELETE AB_Main WHERE ([UniversalID] = @UniversalID)
DELETE AB_MainHistory WHERE ([AbstractID] = @UniversalID)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_AB_Manitoba]
	(@AbstractID	[int])

AS 
DELETE [dbo].[AB_Manitoba] WHERE ( [AbstractID] = @AbstractID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_AB_MB_ALC] (@AbstractID [int])
AS 

DELETE [AB_MB_ALC] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_AB_MB_FacilityStudy] (@AbstractID [int])
AS 

DELETE [AB_MB_FacilityStudy] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_AB_MB_NonALC] (@AbstractID [int])
AS 

DELETE [AB_MB_NonALC] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_AB_MentalHealth] (@AbstractID [int])
AS 

DELETE [AB_MentalHealth] WHERE ([AbstractID] = @AbstractID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_AB_MIS] (@AbstractID [int])
AS 

DELETE [AB_MIS] WHERE ([AbstractID] = @AbstractID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

create PROCEDURE [D_AB_NACRS] (@AbstractID [int])
AS 

delete [AB_NACRS] where ([AbstractID] = @AbstractID)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_AB_PatientService] (@AbstractID[int])
AS 

DELETE [AB_PatientService] WHERE ([AbstractID] = @AbstractID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

create PROCEDURE [D_AB_PresentingComplaints] (@AbstractID [int])
AS 

DELETE [AB_PresentingComplaints] WHERE ([AbstractID] = @AbstractID)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_AB_Project] (@AbstractID [int])
AS 

DELETE [AB_Project] WHERE ([AbstractID] = @AbstractID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_AB_Provider] 	(@AbstractID [int])
AS 

DELETE [AB_Provider] WHERE ([AbstractID]	= @AbstractID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE PROCEDURE [D_AB_QBP_Flag] 	(@AbstractID [int])
AS 

DELETE [AB_QBP_Flag] WHERE ([AbstractID]	= @AbstractID)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_AB_ReproductiveCare] (@AbstractID [int])
AS 

DELETE [AB_ReproductiveCare] WHERE ([AbstractID] = @AbstractID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_AB_SpecialCareUnit] 	(@AbstractID [int])
AS 

DELETE [AB_SpecialCareUnit] WHERE ([AbstractID] = @AbstractID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [D_AB_SpecialProject](
	@AbstractID [int],
	@CareType [int])
as
	delete from dbo.AB_SpecialProjects
	where AbstractID = @AbstractID
		and CareType = @CareType
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE PROCEDURE [D_AB_SpecialProjects] (@AbstractID [int], @CareType int)
AS 

DELETE [AB_SpecialProjects] WHERE ([AbstractID] = @AbstractID) and Caretype = @Caretype





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_AB_SurgicalProcedure] (@AbstractID [int])
AS 

DELETE AB_SurgicalProcedure WHERE ([AbstractID] = @AbstractID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_AB_Therapeutic] (@AbstractID [int])
AS 

DELETE [AB_Therapeutic] WHERE ([AbstractID] = @AbstractID)




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_AB_TransferService] (@AbstractID[int])
AS 

DELETE [AB_TransferService] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_AB_UDAbstracting]
	(@AbstractID 	[int])

AS 
DELETE [dbo].[AB_UDAbstracting] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_AB_UDFieldsDate]
	(@AbstractID 	[int])
as
delete [dbo].[AB_UDFieldsDate] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_AB_UDFieldsInteger]
	(@AbstractID 	[int])
as
delete [dbo].[AB_UDFieldsInteger] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_AB_UDFieldsLookUp]
	(@AbstractID 	[int])
as
delete [dbo].[AB_UDFieldsLookUp] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_AB_UDFieldsSmallText]
	(@AbstractID 	[int])
as
delete [dbo].[AB_UDFieldsSmallText] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_AB_UDFieldsText]
	(@AbstractID 	[int])
as
delete [dbo].[AB_UDFieldsText] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_AB_UDFieldsTime]
	(@AbstractID 	[int])
as
delete [dbo].[AB_UDFieldsTime] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [D_CC_CancerStageDiag]
	(@AbstractID 	[int])

AS 
DELETE [dbo].[CC_CancerStageDiag]  WHERE ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [D_CC_CollaborateStageDiag]
	(@AbstractID 	[int])

AS 
	DELETE [dbo].[CC_CollaborateStageDiag]  WHERE ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [D_CC_Demographic]
	(@AbstractID	[int])

AS 
	--DELETE [dbo].[CC_Demographic]  WHERE ([AbstractID] = @AbstractID)
	update CC_RecordInfo set IsDeleted = 1 where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [D_CC_DischargeInfo]
	(@AbstractID 	[int])

AS 
	DELETE [dbo].[CC_DischargeInfo] WHERE ([AbstractID] = @AbstractID)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [D_CC_DiseaseRegister]
	(@AbstractID 	[int])

AS 
	DELETE [dbo].[CC_DiseaseRegister] WHERE ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [D_CC_HealthCareProf]
	(@AbstractID	[int])

AS 
	DELETE [dbo].[CC_HealthCareProf]  WHERE ([AbstractID]	 = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE     PROCEDURE [D_CC_Information]
	(@AbstractID	[int])
AS 

delete dbo.CC_CancerStageDiag  where ([AbstractID] = @AbstractID)
delete dbo.CC_CollaborateStageDiag where ([AbstractID] = @AbstractID)
delete dbo.CC_Demographic where ([AbstractID] = @AbstractID)
delete dbo.CC_DiseaseRegister where ([AbstractID] = @AbstractID)
delete dbo.CC_HealthCareProf where ([AbstractID] = @AbstractID)
delete dbo.CC_NDFP where ([AbstractID] = @AbstractID)
delete dbo.CC_RecordInfo where ([AbstractID] = @AbstractID)
delete dbo.CC_ReferralDate where ([AbstractID] = @AbstractID)
delete dbo.CC_UpdateHistory where ([AbstractID] = @AbstractID)
delete dbo.CC_DischargeInfo where ([AbstractID] = @AbstractID)  -- New table 03/13/2008
delete AB_MAIN WHERE APPID in (675, 676) and [AbstractID] = @AbstractID
delete AB_ErrorMessageFields where AppID in (675, 676) and [AbstractID] = @AbstractID
delete AB_ErrorMessages where AppID in (675, 676) and [AbstractID] = @AbstractID
delete AB_UpdateAudit where AppID in (675, 676) and [AbstractID] = @AbstractID
delete REC_Notes where AppID in (675, 676) and RecordID = @AbstractID

delete [CC_UDFieldsDate] where ([AbstractID] = @AbstractID)
delete [CC_UDFieldsTime] where ([AbstractID] = @AbstractID)
delete [CC_UDFieldsLookUp] where ([AbstractID] = @AbstractID)
delete [CC_UDFieldsInteger] where ([AbstractID] = @AbstractID)
delete [CC_UDFieldsText] where ([AbstractID] = @AbstractID)
delete [CC_UDFieldsSmallText] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [D_CC_NDFP]
	(@AbstractID 	[int])

AS 
DELETE [dbo].[CC_NDFP]  WHERE ( [AbstractID]	 = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [D_CC_RecordInfo]
	(@AbstractID 	[int])

AS 
	DELETE [dbo].[CC_RecordInfo]  WHERE ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [D_CC_ReferralDate]
	(@AbstractID 	[int])

AS 
	DELETE [dbo].[CC_ReferralDate]  WHERE ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--CM_UDFieldsDate
--CC_UDFieldsDate
--CC_UDFieldsDate
--CC_UDFieldsDate
--CC_UDFieldsDate
--CC_UDFieldsDate
--ROI_UDFieldsDate

create PROCEDURE [D_CC_UDFieldsDate]
	(@AbstractID 	[int])
as
delete [dbo].[CC_UDFieldsDate] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_CC_UDFieldsInteger]
	(@AbstractID 	[int])
as
delete [dbo].[CC_UDFieldsInteger] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_CC_UDFieldsLookUp]
	(@AbstractID 	[int])
as
delete [dbo].[CC_UDFieldsLookUp] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_CC_UDFieldsSmallText]
	(@AbstractID 	[int])
as
delete [dbo].[CC_UDFieldsSmallText] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_CC_UDFieldsText]
	(@AbstractID 	[int])
as
delete [dbo].[CC_UDFieldsText] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_CC_UDFieldsTime]
	(@AbstractID 	[int])
as
delete [dbo].[CC_UDFieldsTime] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [D_CC_UserDefined]
	(@AbstractID 	[int])

AS 
DELETE [dbo].[CC_UserDefined] WHERE ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [D_CJRR_Abstract] 
	( @RecordID 	[int]
	 --,@AppID 	[int]
	)
AS 

delete [CJRR_Abstract] where ([RecordID] = @RecordID)
delete [CJRR_FemoralComponent] where ([RecordID] = @RecordID)
delete [CJRR_FemoralHead] where ([RecordID] = @RecordID)
delete [CJRR_AcetabularComponent] where ([RecordID] = @RecordID)
delete [CJRR_AcetabularInsert] where ([RecordID] = @RecordID)
delete [CJRR_TibialComponent] where ([RecordID] = @RecordID)
delete [CJRR_TibialInsert] where ([RecordID] = @RecordID)
delete [CJRR_PatellarComponent] where ([RecordID] = @RecordID)
delete [CJRR_Cement] where ([RecordID] = @RecordID)

delete AB_Main where ([AbstractID] = @RecordID and (Appid = 40000 or AppID = 40001)) -- [AppID] = @AppID 
delete CJRR_UpdateHistory where ([RecordID] = @RecordID)

delete [CJRR_UDFieldsDate] where ([RecordID] = @RecordID)
delete [CJRR_UDFieldsTime] where ([RecordID] = @RecordID)
delete [CJRR_UDFieldsLookUp] where ([RecordID] = @RecordID)
delete [CJRR_UDFieldsInteger] where ([RecordID] = @RecordID)
delete [CJRR_UDFieldsText] where ([RecordID] = @RecordID)
delete [CJRR_UDFieldsSmallText] where ([RecordID] = @RecordID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





create PROCEDURE [D_CJRR_AcetabularComponent] (@RecordID	[int])
AS 

delete [CJRR_AcetabularComponent] where ([RecordID] = @RecordID)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





create PROCEDURE [D_CJRR_AcetabularInsert] (@RecordID	[int])
AS 

delete [CJRR_AcetabularInsert] where ([RecordID] = @RecordID)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





create PROCEDURE [D_CJRR_Cement] (@RecordID	[int])
AS 

delete [CJRR_Cement] where ([RecordID] = @RecordID)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





create PROCEDURE [D_CJRR_FemoralComponent] (@RecordID	[int])
AS 

delete [CJRR_FemoralComponent] where ([RecordID] = @RecordID)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





create PROCEDURE [D_CJRR_FemoralHead] (@RecordID	[int])
AS 

delete [CJRR_FemoralHead] where ([RecordID] = @RecordID)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





create PROCEDURE [D_CJRR_PatellarComponent] (@RecordID	[int])
AS 

delete [CJRR_PatellarComponent] where ([RecordID] = @RecordID)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





create PROCEDURE [D_CJRR_TibialComponent] (@RecordID	[int])
AS 

delete [CJRR_TibialComponent] where ([RecordID] = @RecordID)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





create PROCEDURE [D_CJRR_TibialInsert] (@RecordID	[int])
AS 

delete [CJRR_TibialInsert] where ([RecordID] = @RecordID)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--CJRR_UDFieldsDate
--CJRR_UDFieldsDate
--CJRR_UDFieldsDate
--CJRR_UDFieldsDate
--CJRR_UDFieldsDate
--CJRR_UDFieldsDate
--CJRR_UDFieldsDate

create PROCEDURE [D_CJRR_UDFieldsDate]
	(@RecordID 	[int])
as
delete [dbo].[CJRR_UDFieldsDate] where ([RecordID] = @RecordID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_CJRR_UDFieldsInteger]
	(@RecordID 	[int])
as
delete [dbo].[CJRR_UDFieldsInteger] where ([RecordID] = @RecordID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_CJRR_UDFieldsLookUp]
	(@RecordID 	[int])
as
delete [dbo].[CJRR_UDFieldsLookUp] where ([RecordID] = @RecordID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_CJRR_UDFieldsSmallText]
	(@RecordID 	[int])
as
delete [dbo].[CJRR_UDFieldsSmallText] where ([RecordID] = @RecordID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_CJRR_UDFieldsText]
	(@RecordID 	[int])
as
delete [dbo].[CJRR_UDFieldsText] where ([RecordID] = @RecordID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_CJRR_UDFieldsTime]
	(@RecordID 	[int])
as
delete [dbo].[CJRR_UDFieldsTime] where ([RecordID] = @RecordID)
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CL_Activities]
--Delete all Chart Activity for a given Chart #
	@VolumeID as int
AS 
    declare @PID as int
    select @PID = PatientID from CM_CPI_Volume where VolumeID = @VolumeID	
    
    delete CL_Activity where VolumeID in (select VolumeID from CM_CPI_Volume where PatientID = @PID)
    
	Return (@@rowcount)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [D_CL_Activities_Chart]
	--Delete all Deficiency Activities
	@PatientID AS INT
AS 
	--NP-00025: and (DefStatus = 8 or DefStatus = 11)
-- 	if not exists(select * from Def_Activity where DefID in (select DefID from Def_SlipMain where DefPatientID = @PatientID))
-- 		delete Def_SlipMain where DefPatientID = @PatientID

    --EN-00183: HeaderDefID and DefeciencyID with DefID 
	delete Def_Activity where DefID in (select DefID from Def_SlipMain where DefPatientID = @PatientID)
	and (DefStatus = 8 or DefStatus = 11)	

    Delete from Def_SlipMain  
    from Def_SlipMain left join Def_Activity on Def_SlipMain.DefID = Def_Activity.DefID
    where DefPatientID = @PatientID
        and Def_Activity.DefID is null

    Delete from Def_UpdateHistory 
    from  Def_UpdateHistory left join Def_SlipMain on Def_UpdateHistory.DefID = Def_SlipMain.DefID 
    where Def_SlipMain.DefID is null


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE PROCEDURE [D_CL_Activity]
--Delete a specific Chart Activity
	@ActivityID as int
AS 

	Delete CL_Activity where CLActivityID = @ActivityID

	Return @@rowcount



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CM_Address]
	(@PatientID 	[int])

AS 
DELETE [dbo].[CM_Address] WHERE ([PatientID]	 = @PatientID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_CM_Alert] (@PatientID [int])
AS 

DELETE [CM_Alert] WHERE ([PatientID] = @PatientID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_CM_Alias] (@PatientID [int])
AS 

DELETE [CM_Alias] WHERE 	([PatientID] = @PatientID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_CM_BabyChart] (@PatientID [int])
AS 

DELETE [CM_BabyChart] WHERE ([PatientID]	 = @PatientID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_CM_ChartLink] (@PatientID [int])
AS 

DELETE [CM_ChartLink] WHERE ([PatientID]	= @PatientID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO










CREATE      PROCEDURE [D_CM_CPI] 
	(@PatientID 	[int],
	 @AppID 	[int])
AS 

delete CM_Address where ([PatientID] = @PatientID)
delete CM_Alert where ([PatientID] = @PatientID)
delete CM_Alias where ([PatientID] = @PatientID)
delete CM_BabyChart where ([PatientID] = @PatientID)
delete CM_ChartLink where ([PatientID] = @PatientID)
delete CM_CPI where ([PatientID] = @PatientID)
--delete CM_CPI_Merge where ??
delete CM_FamilyHistory where ([PatientID] = @PatientID)
delete CM_Files where ([PatientID] = @PatientID)
delete CM_LabHistory where ([PatientID] = @PatientID)
--delete CM_Notes where ([PatientID] = @PatientID) --The Notes are now stored in REC_Notes
delete CM_RiskFactors where ([PatientID] = @PatientID)
delete CM_Terminal where ([PatientID] = @PatientID)
delete CM_UpdateHistory where ([PatientID] = @PatientID)
delete CM_UserDefined where ([PatientID] = @PatientID)
delete CM_Volume_UpdateHistory where (VolumeID in (select VolumeID from CM_CPI_Volume where [PatientID] = @PatientID))
delete CM_CPI_Volume where ([PatientID] = @PatientID) 
delete AB_UpdateAudit where ([AppID] = @AppID and [AbstractID] = @PatientID)
delete AB_Main where AppID = 0 and PatientID = @PatientID
delete AB_ErrorMessageFields where ([AppID] = 0 and [AbstractID] = @PatientID)
delete AB_ErrorMessages where ([AppID] = 0 and [AbstractID] = @PatientID)
delete REC_Notes where AppID = @AppID and RecordID = @PatientID

delete [CM_UDFieldsDate] where ([PatientID] = @PatientID)
delete [CM_UDFieldsTime] where ([PatientID] = @PatientID)
delete [CM_UDFieldsLookUp] where ([PatientID] = @PatientID)
delete [CM_UDFieldsInteger] where ([PatientID] = @PatientID)
delete [CM_UDFieldsText] where ([PatientID] = @PatientID)
delete [CM_UDFieldsSmallText] where ([PatientID] = @PatientID)

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE   PROCEDURE [D_CM_CPI_Volume] (@VolumeID [int])
AS 

DELETE [CM_CPI_Volume] WHERE ([VolumeID]	= @VolumeID)
delete [CM_Volume_UpdateHistory] where ([VolumeID]	= @VolumeID)
--PR - 01962
Delete dbo.CL_PullList  where ([VolumeID]	= @VolumeID)
Delete dbo.CL_PullList_Purged  where ([VolumeID]	= @VolumeID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CM_FamilyHistory]
	(@PatientID	[int])
AS 
DELETE [dbo].[CM_FamilyHistory] WHERE ([PatientID] = @PatientID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CM_Files]
	(@PatientID 	[int])
AS 
DELETE [dbo].[CM_Files] WHERE ([PatientID] = @PatientID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CM_LabHistory]
	(@PatientID 	[int])

AS 
DELETE [dbo].[CM_LabHistory] WHERE ([PatientID] = @PatientID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CM_RiskFactors]
	(@PatientID 	[int])

AS 
DELETE [dbo].[CM_RiskFactors] WHERE ([PatientID] = @PatientID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--CM_UDFieldsDate
--CM_UDFieldsDate
--CM_UDFieldsDate
--CM_UDFieldsDate
--CM_UDFieldsDate
--CM_UDFieldsDate
--CM_UDFieldsDate

create PROCEDURE [D_CM_UDFieldsDate]
	(@PatientID 	[int])
as
delete [dbo].[CM_UDFieldsDate] where ([PatientID] = @PatientID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_CM_UDFieldsInteger]
	(@PatientID 	[int])
as
delete [dbo].[CM_UDFieldsInteger] where ([PatientID] = @PatientID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_CM_UDFieldsLookUp]
	(@PatientID 	[int])
as
delete [dbo].[CM_UDFieldsLookUp] where ([PatientID] = @PatientID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_CM_UDFieldsSmallText]
	(@PatientID 	[int])
as
delete [dbo].[CM_UDFieldsSmallText] where ([PatientID] = @PatientID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_CM_UDFieldsText]
	(@PatientID 	[int])
as
delete [dbo].[CM_UDFieldsText] where ([PatientID] = @PatientID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_CM_UDFieldsTime]
	(@PatientID 	[int])
as
delete [dbo].[CM_UDFieldsTime] where ([PatientID] = @PatientID)
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE PROCEDURE [D_CM_UserDefined]
	(@PatientID 	[int])

AS 
DELETE [CM_UserDefined] WHERE ( [PatientID] = @PatientID)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE PROCEDURE [D_CMV_ClinicalPathway]
	(@RecordID 	[int])

AS 
	DELETE [CMV_Variance] WHERE ( [RecordID] = @RecordID)
	DELETE [dbo].[CMV_ClinicalPathway]  WHERE ( [RecordID]  = @RecordID)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE PROCEDURE [D_CMV_Variance]
	(@RecordID 	[int])

AS 
	DELETE [CMV_Variance] WHERE ( [RecordID] = @RecordID)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CR_Demographic]
	(@AbstractID 	[int])

AS 
DELETE [dbo].[CR_Demographic] WHERE  ([AbstractID] = @AbstractID)
DELETE [dbo].[CR_Diagnosis] WHERE ([AbstractID] = @AbstractID)
DELETE [dbo].[CR_Intervention] WHERE ([AbstractID] = @AbstractID)
DELETE [dbo].[CR_Prescription] WHERE ([AbstractID] = @AbstractID)
DELETE [dbo].[CR_ProviderService] WHERE ([AbstractID] = @AbstractID)
DELETE [dbo].[CR_Supply] WHERE ([AbstractID] = @AbstractID)
DELETE [dbo].[CR_Visit] WHERE ([AbstractID] = @AbstractID)
DELETE [dbo].[CR_VitalSign] WHERE ([AbstractID] = @AbstractID)
DELETE [dbo].[CR_Immunization] WHERE ([AbstractID] = @AbstractID)
DELETE [dbo].[CR_DirectBilling] WHERE ([AbstractID] = @AbstractID)
DELETE [dbo].[CR_DirectBillingItems] WHERE ([AbstractID] = @AbstractID)
DELETE [dbo].[CR_DirectBillingPayments] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [D_CR_Diagnosis]
	(@AbstractID 	[int])
AS 
DELETE [dbo].[CR_Diagnosis] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CR_DirectBilling]
	(@AbstractID 	[int])
AS 
DELETE [dbo].[CR_DirectBilling] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CR_DirectBillingItems]
	(@AbstractID 	[int])
AS 
DELETE [dbo].[CR_DirectBillingItems] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CR_DirectBillingPayments]
	(@AbstractID 	[int])
AS 
DELETE [dbo].[CR_DirectBillingPayments] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CR_Immunization]
	(@AbstractID 	[int])

AS 
DELETE [dbo].[CR_Immunization] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [D_CR_Intervention]
	(@AbstractID	[int])

AS 
DELETE [dbo].[CR_Intervention] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [D_CR_Prescription]
	(@AbstractID 	[int])
AS 
DELETE [dbo].[CR_Prescription] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [D_CR_ProviderService]
	(@AbstractID 	[int])

AS 
DELETE [dbo].[CR_ProviderService] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [D_CR_Supply]
	(@AbstractID 	[int])

AS 
DELETE [dbo].[CR_Supply] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [D_CR_Visit]
	(@AbstractID 	[int])

AS 
DELETE [dbo].[CR_Visit] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [D_CR_VitalSign]
	(@AbstractID 	[int])

AS 
DELETE [dbo].[CR_VitalSign] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CRS_Admission] 
	(@AbstractID [int])
AS
DELETE [CRS_Admission] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CRS_Ancillary]	(@AbstractID [int])
AS 

DELETE [CRS_Ancillary] WHERE ([AbstractID] = @AbstractID)




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CRS_AssessFull1]	
(@AbstractID [int])
AS 

DELETE [CRS_AssessFull1] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CRS_AssessFull2]	
(@AbstractID [int])
AS 

DELETE [CRS_AssessFull2] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CRS_AssessShare1]	
(@AbstractID [int])
AS 

DELETE [CRS_AssessShare1] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CRS_AssessShare2]	
(@AbstractID [int])
AS 

DELETE [CRS_AssessShare2] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CRS_AssessShare3]	
(@AbstractID [int])
AS 

DELETE [CRS_AssessShare3] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CRS_AssessShare4]	
(@AbstractID [int])
AS 

DELETE [CRS_AssessShare4] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CRS_AssessShare5]	
(@AbstractID [int])
AS 

DELETE [CRS_AssessShare5] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CRS_BasicOption] (@AbstractID [int])
AS
 
DELETE [CRS_BasicOption] WHERE ([AbstractID] = @AbstractID)





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





create  PROCEDURE [D_CRS_CAPS]	
(@AbstractID [int])
AS 

delete [CRS_CAPS] WHERE ([AbstractID] = @AbstractID)




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [D_CRS_Demographic] 
	(@AbstractID 	[int], 
	 @AppID 	[int])
AS 

delete [dbo].[CRS_Admission] where ([AbstractID] = @AbstractID)
delete [dbo].[CRS_Ancillary] where ([AbstractID] = @AbstractID)
delete [dbo].[CRS_AssessFull1] where ([AbstractID] = @AbstractID)
delete [dbo].[CRS_AssessFull2] where ([AbstractID] = @AbstractID)
delete [dbo].[CRS_AssessShare1] where ([AbstractID] = @AbstractID)
delete [dbo].[CRS_AssessShare2] where ([AbstractID] = @AbstractID)
delete [dbo].[CRS_AssessShare3] where ([AbstractID] = @AbstractID)
delete [dbo].[CRS_AssessShare4] where ([AbstractID] = @AbstractID)
delete [dbo].[CRS_AssessShare5] where ([AbstractID] = @AbstractID)
delete [dbo].[CRS_BasicOption] where ([AbstractID] = @AbstractID)
delete [dbo].[CRS_Demographic] where ([AbstractID] = @AbstractID)
delete [dbo].[CRS_Diagnosis]  where  ([AbstractID] = @AbstractID)
delete [dbo].[CRS_Medication] where ([AbstractID] = @AbstractID)
delete [dbo].[CRS_Project] where ([AbstractID] = @AbstractID)
delete [dbo].[CRS_RAPS] where ([AbstractID] = @AbstractID)
delete [dbo].[CRS_RAPS2] where ([AbstractID] = @AbstractID)
delete [dbo].[CRS_RUGS] where ([AbstractID] = @AbstractID)
delete [dbo].[CRS_Signature] where ([AbstractID] = @AbstractID)
delete [dbo].[CRS_UDAbstracting] where ([AbstractID] = @AbstractID)
delete [dbo].[CRS_UpdateHistory] where ([AbstractID] = @AbstractID)
delete REC_Notes where AppID = @AppID and RecordID = @AbstractID
delete AB_Main where AbstractID = @AbstractID and (AppID = @AppID or AppID between 470 and 476)
delete AB_ErrorMessageFields where ([AppID] = @AppID and [AbstractID] = @AbstractID)
delete AB_ErrorMessages where ([AppID] = @AppID and [AbstractID] = @AbstractID)
delete AB_UpdateAudit where ([AppID] = @AppID and [AbstractID] = @AbstractID)

delete [dbo].[CRS_Hobic] where ([AbstractID] = @AbstractID)

delete [CRS_UDFieldsDate] where ([AbstractID] = @AbstractID)
delete [CRS_UDFieldsTime] where ([AbstractID] = @AbstractID)
delete [CRS_UDFieldsLookUp] where ([AbstractID] = @AbstractID)
delete [CRS_UDFieldsInteger] where ([AbstractID] = @AbstractID)
delete [CRS_UDFieldsText] where ([AbstractID] = @AbstractID)
delete [CRS_UDFieldsSmallText] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CRS_Diagnosis]	
(@AbstractID [int])
AS 

DELETE [CRS_Diagnosis] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [D_CRS_Hobic] (@AbstractID [int])
AS
 
DELETE from CRS_Hobic WHERE ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CRS_Medication]	
(@AbstractID [int])
AS 

DELETE [CRS_Medication] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create  PROCEDURE [D_CRS_OutcomeScale] (@AbstractID [int])
AS
 
delete CRS_OutcomeScale where ([AbstractID] = @AbstractID)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CRS_Project] (@AbstractID [int])
AS 

DELETE [CRS_Project] WHERE ([AbstractID] = @AbstractID)





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CRS_RAPS2]	
(@AbstractID [int])
AS 

DELETE [CRS_RAPS2] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [D_CRS_Signature]
	(@AbstractID [int])
AS 
DELETE [dbo].[CRS_Signature] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_CRS_UDAbstracting]
	(@AbstractID 	[int])

AS 
DELETE [dbo].[CRS_UDAbstracting] WHERE ([AbstractID] = @AbstractID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--CM_UDFieldsDate
--CRS_UDFieldsDate
--CRS_UDFieldsDate
--CRS_UDFieldsDate
--OMHRS_UDFieldsDate
--CC_UDFieldsDate
--ROI_UDFieldsDate

create PROCEDURE [D_CRS_UDFieldsDate]
	(@AbstractID 	[int])
as
delete [dbo].[CRS_UDFieldsDate] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_CRS_UDFieldsInteger]
	(@AbstractID 	[int])
as
delete [dbo].[CRS_UDFieldsInteger] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_CRS_UDFieldsLookUp]
	(@AbstractID 	[int])
as
delete [dbo].[CRS_UDFieldsLookUp] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_CRS_UDFieldsSmallText]
	(@AbstractID 	[int])
as
delete [dbo].[CRS_UDFieldsSmallText] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_CRS_UDFieldsText]
	(@AbstractID 	[int])
as
delete [dbo].[CRS_UDFieldsText] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_CRS_UDFieldsTime]
	(@AbstractID 	[int])
as
delete [dbo].[CRS_UDFieldsTime] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO







create PROCEDURE [D_CRS_UpdateRecord]	
(@AbstractID [int])
AS 

DELETE [CRS_UpdateRecord] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE   PROCEDURE [D_Def_Activities]
	--Delete all Deficiency Activities
	--@HeaderDefID AS INT
	@DefID AS INT
AS 
    --EN-00183
	--DELETE Def_Activity WHERE HeaderDefID = @HeaderDefID
	DELETE Def_Activity WHERE DefID = @DefID

	RETURN 0




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


--EN-00183 Add DefID
CREATE PROCEDURE [D_Def_Activity]
--Delete a specific Deficiency Activity
	@ActivityID as int,
    @DefID        int
AS 

--NP-00025: and (DefStatus = 8 or DefStatus = 11)
--EN-00183
--delete Def_Activity where DefeciencyID = @ActivityID and (DefStatus = 8 or DefStatus = 11) 

delete Def_Activity where DefeciencyID = @ActivityID and (DefStatus = 8 or DefStatus = 11) and DefID = @DefID
if not exists (select * from Def_SlipMain where DefID = @DefID)
begin
    Delete from Def_SlipMain where DefID = @DefID
    Delete from Def_UpdateHistory where DefID = @DefID
end
return 0




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

-- Sets the def status to cancel
--PR - 02842
Create PROCEDURE [D_DEF_Main] (@DefID [int], @Coder varchar(50))
AS 
    insert into dbo.REC_Purge(AppID, RecordID, CareType, InstNumber, ChartNumber, FullName, EncounterNumber, 
        VisitDate, VisitTime, DeleteCoder, DeleteDate, DeleteTime)
    select 15, DefeciencyID, d.DefAbstractID, 
        (select top 1 h.cihivalue from h_InstitutionProfile h where d.DefInstNumber = h.code), 
        (select c.ChartNumber from cm_cpi c where d.DefPatientID = c.patientid), 
        isnull(DefPatFirstName, '') + ' ' + isnull( DefPatLastName, ''), 
        (select top 1 p.CIHIValue + isnull(' - ' + p.UserDescription, '') from lu_provider p where d.DefDrNumber = p.code),
        isnull(m.DischargeDate, m.AdmitDate), isnull(m.DischargeTime, m.AdmitTime),
        @Coder, getdate(), getdate()
    from dbo.Def_SlipMain d
        left join ab_main m on d.DefAbstractID = m.UniversalID
    WHERE ([DefID] = @DefID)

	Delete from dbo.Def_SlipMain
    WHERE ([DefID] = @DefID)

	delete from dbo.Def_Activity
    WHERE ([DefID] = @DefID)

    Delete from Def_UpdateHistory 
    WHERE ([DefID] = @DefID)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [D_H_HospitalProfile_Message] (@Code 	[int])
AS 

delete H_HospitalProfile_Message where (Code = @Code)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [D_H_RegionProfile_Message] (@Code 	[int])
AS 

delete H_RegionProfile_Message where (Code = @Code)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_LLU_Provider_Schedule]
	(@ProviderID	[int])
AS 
DELETE [LLU_Provider_Schedule] WHERE [ProviderID] = @ProviderID



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_LLU_Provider_Suspention]
	(@ProviderID	[int])
AS 

DELETE [LLU_Provider_Suspention] WHERE [ProviderID] = @ProviderID




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE PROCEDURE [D_LLU_Provider_UnAvailable]
	(@ProviderID 	[int])

AS 
DELETE [dbo].[LLU_Provider_UnAvailable] WHERE ( [ProviderID]	 = @ProviderID)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_LLU_Provider_Vacation]
	(@ProviderID	[int])
AS 

DELETE [LLU_Provider_Vacation] WHERE [ProviderID] = @ProviderID




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE PROCEDURE [D_LLU_ProviderPrivileges]
	(@ProviderID	[int])

AS 
DELETE [LLU_ProviderPrivileges] WHERE ([ProviderID] = @ProviderID)

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE PROCEDURE [D_LLU_ProviderServices]
	(@ProviderID	[int])
AS 
DELETE [LLU_ProviderServices] WHERE [AssociationID] = @ProviderID

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE PROCEDURE [D_LLU_ProviderSpecialty]
	(@ProviderID	[int])
AS 
DELETE [LLU_ProviderSpecialty] WHERE [AssociationID] = @ProviderID

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_LLU_ReportDistribution]
	(@Code		[int])
AS 
DELETE [dbo].[LLU_ReportDistribution] WHERE ([Code] = @Code)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- Deletes Basic Option Look Ups where the Institutions is destroyed (ONLY: New Records that get cancelled).
CREATE PROCEDURE [D_LU_InstitutionBOPs] 
	(@AssociateID	[int])

AS 
	DELETE [LU_BasicOption1] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_BasicOption2] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_BasicOption3] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_BasicOption4] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_BasicOption5] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_BasicOption6] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_BasicOption7] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_BasicOption8] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_BasicOption9] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_BasicOption10] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_BasicOption11] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_BasicOption12] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_BasicOption13] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_BasicOption14] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_BasicOption15] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_BasicOption16] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_BasicOption17] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_BasicOption18] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_BasicOption19] WHERE ([AssociationID] = @AssociateID)




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- Deletes Project Question Look Ups where the Project is destroyed (ONLY: New Records that get cancelled).
CREATE PROCEDURE [D_LU_ProjectQuestions] 
	(@AssociateID	[int])

AS 

	DELETE [LU_ProjectQuestion1] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_ProjectQuestion2] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_ProjectQuestion3] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_ProjectQuestion4] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_ProjectQuestion5] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_ProjectQuestion6] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_ProjectQuestion7] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_ProjectQuestion8] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_ProjectQuestion9] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_ProjectQuestion10] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_ProjectQuestion11] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_ProjectQuestion12] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_ProjectQuestion13] WHERE ([AssociationID] = @AssociateID)
	/*DELETE [LU_ProjectQuestion14] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_ProjectQuestion15] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_ProjectQuestion16] WHERE ([AssociationID] = @AssociateID)
	DELETE [LU_ProjectQuestion17] WHERE ([AssociationID] = @AssociateID)*/




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- Deletes Provider Services Look Ups where the Provider is destroyed (ONLY: New Records that get cancelled).
CREATE PROCEDURE [D_LU_ProviderServices] 
	(@AssociateID	[int])

AS 

	DELETE [LLU_ProviderServices] WHERE ([AssociationID] = @AssociateID)




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- Deletes Provider Services Look Ups where the Provider is destroyed (ONLY: New Records that get cancelled).
CREATE PROCEDURE [D_LU_ProviderSpecialty] 
	(@AssociateID	[int])

AS 

	DELETE [LLU_ProviderSpecialty] WHERE ([AssociationID] = @AssociateID)




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO





-- Deletes ROI Requester Contacts Look Ups where the Requester is destroyed (ONLY: New Records that get cancelled).
CREATE PROCEDURE [D_LU_ROIRequesterContacts] 
	(@AssociateID	[int])

AS 

	DELETE [LU_ROI_Contacts] WHERE ([AssociationID] = @AssociateID)




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE  PROCEDURE [D_MultiCMG]
AS

	delete ab_HIG
	from ab_HIG inner join ab_cmg on ab_HIG.AbstractID = ab_cmg.AbstractID and ab_HIG.OccurrenceNumber = ab_cmg.OccurrenceNumber and ab_HIG.GrouperYear = ab_cmg.CMG_Year
	where ab_HIG.occurrencenumber > 1 and
	ExpiryDate < getdate()

	delete ab_cmg_FI 
	from ab_cmg_FI inner join ab_cmg on ab_cmg_FI.AbstractID = ab_cmg.AbstractID and ab_cmg_FI.OccurrenceNumber = ab_cmg.OccurrenceNumber and ab_cmg_FI.CMG_Year = ab_cmg.CMG_Year
	where ab_cmg_FI.occurrencenumber > 1 and
	ExpiryDate < getdate()

	delete ab_cmg where occurrencenumber > 1 and
	ExpiryDate < getdate()


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




Create Procedure [D_NU_Profile]
@ProfileID as int
AS

delete from nu_DProfile where profileid=@ProfileID
delete from nu_IntProfile where profileid=@ProfileID
delete from NU_profile where profileid=@ProfileID





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO







CREATE PROCEDURE [D_OMHRS_Ancillary]	(@AbstractID [int])
AS 

DELETE [OMHRS_Ancillary] WHERE ([AbstractID] = @AbstractID)






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO







CREATE PROCEDURE [D_OMHRS_BasicOption] (@AbstractID [int])
AS
 
DELETE [OMHRS_BasicOption] WHERE ([AbstractID] = @AbstractID)






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [D_OMHRS_Diagnosis_CodeSmart] (@AbstractID[int])
AS 

DELETE OMHRS_Diagnosis_CodeSmart WHERE ([AbstractID] = @AbstractID)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_OMHRS_DischargeDiagnosis] (@AbstractID [int])
AS 

delete [OMHRS_DischargeDiagnosis] where ([AbstractID] = @AbstractID)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [D_OMHRS_DSM_5]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_DSM_5] WHERE ([AbstractID] = @AbstractID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_DSM_Diag]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_DSM_Diag] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_OMHRS_DSM_Diag_II]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_DSM_Diag_II] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_OMHRS_IAR_CCIM]
	(@AbstractID int)

AS 
DELETE [OMHRS_IAR_CCIM] WHERE ( [AbstractID]	 = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO







CREATE PROCEDURE [D_OMHRS_Intervention] (@AbstractID [int])
AS 

DELETE [OMHRS_Intervention] WHERE ([AbstractID] = @AbstractID)






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [D_OMHRS_Intervention_CodeSmart] (@AbstractID[int])
AS 

DELETE OMHRS_Intervention_CodeSmart WHERE ([AbstractID] = @AbstractID)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_Med_Diag]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_Med_Diag] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_Medication]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_Medication] WHERE 	([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE PROCEDURE [D_OMHRS_MHAPS]
	(@AbstractID 	[int])

AS 
DELETE [dbo].[OMHRS_MHAPS] WHERE ( [AbstractID]	 = @AbstractID)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO







CREATE PROCEDURE [D_OMHRS_Project] (@AbstractID [int])
AS 

DELETE [OMHRS_Project] WHERE ([AbstractID] = @AbstractID)






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO







CREATE PROCEDURE [D_OMHRS_Provider] 	(@AbstractID [int])
AS 

DELETE [OMHRS_Provider] WHERE ([AbstractID]	= @AbstractID)






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [D_OMHRS_RecInfo]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_RecInfo] WHERE ( [AbstractID] = @AbstractID)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_SecA]
	(@AbstractID int)

AS 
DELETE [OMHRS_SecA] WHERE ( [AbstractID]	 = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [D_OMHRS_SecAA]
	(@Key 	[int])
AS 

delete [dbo].[OMHRS_Ancillary] where AbstractID = @Key
delete [dbo].[OMHRS_BasicOption] where AbstractID = @Key
delete [dbo].[OMHRS_DSM_Diag] where AbstractID = @Key 
delete [dbo].[OMHRS_DSM_Diag_II] where AbstractID = @Key 
delete [dbo].[OMHRS_DSM_5] where AbstractID = @Key 
delete [dbo].[OMHRS_Intervention] where AbstractID = @Key 
delete [dbo].[OMHRS_Med_Diag] where AbstractID = @Key 
delete [dbo].[OMHRS_Medication] where AbstractID = @Key 
delete [dbo].[OMHRS_MHAPS] where AbstractID = @Key
delete [dbo].[OMHRS_Project] where AbstractID = @Key 
delete [dbo].[OMHRS_Provider] where AbstractID = @Key
delete [dbo].[OMHRS_RecInfo] where AbstractID = @Key
delete [dbo].[OMHRS_SecA] where AbstractID = @Key
delete [dbo].[OMHRS_SecAA] where AbstractID = @Key
delete [dbo].[OMHRS_SecB] where AbstractID = @Key
delete [dbo].[OMHRS_SecBB] where AbstractID = @Key
delete [dbo].[OMHRS_SecC] where AbstractID = @Key
delete [dbo].[OMHRS_SecCC] where AbstractID = @Key
delete [dbo].[OMHRS_SecD] where AbstractID = @Key
delete [dbo].[OMHRS_SecDD] where AbstractID = @Key
delete [dbo].[OMHRS_SecE] where AbstractID = @Key
delete [dbo].[OMHRS_SecF] where AbstractID = @Key
delete [dbo].[OMHRS_SecG] where AbstractID = @Key
delete [dbo].[OMHRS_SecH] where AbstractID = @Key
delete [dbo].[OMHRS_SecI] where AbstractID = @Key
delete [dbo].[OMHRS_SecJ] where AbstractID = @Key
delete [dbo].[OMHRS_SecK] where AbstractID = @Key
delete [dbo].[OMHRS_SecL] where AbstractID = @Key
delete [dbo].[OMHRS_SecM] where AbstractID = @Key
delete [dbo].[OMHRS_SecN] where AbstractID = @Key
delete [dbo].[OMHRS_SecO] where AbstractID = @Key
delete [dbo].[OMHRS_SecP] where AbstractID = @Key
delete [dbo].[OMHRS_SecQ] where AbstractID = @Key
delete [dbo].[OMHRS_SecR] where AbstractID = @Key
delete [dbo].[OMHRS_SecS] where AbstractID = @Key
delete [dbo].[OMHRS_Serv_Interrupt] where AbstractID = @Key 
delete [dbo].[OMHRS_UpdateHistory] where AbstractID = @Key
delete [dbo].[OMHRS_UserDefined] where AbstractID = @Key
delete REC_Notes where AppID in (650, 651, 652, 653, 654, 655) and RecordID = @Key
delete AB_Main where AppID in (650, 651, 652, 653, 654, 655) and AbstractID = @Key
delete AB_ErrorMessageFields where AppID in (650, 651, 652, 653, 654, 655) and [AbstractID] = @Key
delete AB_ErrorMessages where AppID in (650, 651, 652, 653, 654, 655) and [AbstractID] = @Key
delete AB_UpdateAudit where AppID in (650, 651, 652, 653, 654, 655) and [AbstractID] = @Key
--EN-00047
delete [dbo].[OMHRS_CIHIErrors] where AbstractID = @Key
delete [OMHRS_IAR_CCIM] where AbstractID = @Key --EN-00526

delete [OMHRS_UDFieldsDate] where ([AbstractID] = @Key)
delete [OMHRS_UDFieldsTime] where ([AbstractID] = @Key)
delete [OMHRS_UDFieldsLookUp] where ([AbstractID] = @Key)
delete [OMHRS_UDFieldsInteger] where ([AbstractID] = @Key)
delete [OMHRS_UDFieldsText] where ([AbstractID] = @Key)
delete [OMHRS_UDFieldsSmallText] where ([AbstractID] = @Key)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_SecB]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_SecB] WHERE ( [AbstractID]	 = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_SecBB]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_SecBB] WHERE ( [AbstractID]	 = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_SecC]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_SecC] WHERE ( [AbstractID]	 = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_SecCC]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_SecCC] WHERE ( [AbstractID]	 = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_SecD]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_SecD] WHERE ( [AbstractID]	 = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_SecDD]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_SecDD] WHERE ( [AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_SecE]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_SecE] WHERE ( [AbstractID]	 = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_SecF]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_SecF] WHERE ( [AbstractID]	 = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_SecG]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_SecG] WHERE ( [AbstractID]	 = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_SecH]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_SecH] WHERE ( [AbstractID]	 = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_SecI]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_SecI] WHERE ( [AbstractID]	 = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_SecJ]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_SecJ] WHERE ( [AbstractID]	 = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_SecK]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_SecK] WHERE ( [AbstractID]	 = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_SecL]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_SecL] WHERE ( [AbstractID]	 = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_SecM]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_SecM] WHERE ( [AbstractID]	 = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_SecN]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_SecN] WHERE ( [AbstractID]	 = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_SecO]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_SecO] WHERE ( [AbstractID]	 = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_SecP]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_SecP] WHERE ( [AbstractID]	 = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_SecQ]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_SecQ] WHERE ( [AbstractID]	 = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_OMHRS_SecR]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_SecR] WHERE ( [AbstractID]	 = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [D_OMHRS_SecS]
	(@AbstractID 	[int])

AS 
DELETE [OMHRS_SecS] WHERE ( [AbstractID]	 = @AbstractID)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE  PROCEDURE [D_OMHRS_Serv_Interrupt]
	(@AbstractID 	[int])

AS 
--PR - 04398 reverse ED-01561
DELETE [OMHRS_Serv_Interrupt] WHERE ( [AbstractID] = @AbstractID) 
--ED-1561
--delete [OMHRS_Serv_Interrupt] where [AbstractID] in (select AbstractID from OMHRS_SecAA where LinkID = @AbstractID)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--CM_UDFieldsDate
--OMHRS_UDFieldsDate
--OMHRS_UDFieldsDate
--OMHRS_UDFieldsDate
--OMHRS_UDFieldsDate
--CC_UDFieldsDate
--ROI_UDFieldsDate

create PROCEDURE [D_OMHRS_UDFieldsDate]
	(@AbstractID 	[int])
as
delete [dbo].[OMHRS_UDFieldsDate] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_OMHRS_UDFieldsInteger]
	(@AbstractID 	[int])
as
delete [dbo].[OMHRS_UDFieldsInteger] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_OMHRS_UDFieldsLookUp]
	(@AbstractID 	[int])
as
delete [dbo].[OMHRS_UDFieldsLookUp] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_OMHRS_UDFieldsSmallText]
	(@AbstractID 	[int])
as
delete [dbo].[OMHRS_UDFieldsSmallText] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_OMHRS_UDFieldsText]
	(@AbstractID 	[int])
as
delete [dbo].[OMHRS_UDFieldsText] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_OMHRS_UDFieldsTime]
	(@AbstractID 	[int])
as
delete [dbo].[OMHRS_UDFieldsTime] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE PROCEDURE [D_OMHRS_UserDefined]
	(@AbstractID 	[int])

AS 
DELETE [dbo].[OMHRS_UserDefined] WHERE ([AbstractID] = @AbstractID)





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE   PROCEDURE [D_PullList_Item]
	@PullID as int, 
    @LoanNote as varchar(250),
    @Coder    as int
AS 
--13008
    INSERT INTO CL_PullListUpdateHistory (PullID, PullListID, VolumeID, Coder, Updated, UpdateType) 
    select PullID, PullListID, VolumeID, @Coder, getdate(), 'Purged'
    from CL_PullList
    where PullID = @PullID 

--13004
--EN-00183
    insert CL_PullList_Purged(PullID, PullListID, PullLocation, PullDate, PullTime, Puller, PullNotes, 
        VolumeID, PullListStatus, PullOutDate, PullOutTime, LoanDate, LoanTime, LoanNote, CLRequestPriority, HospitalID, LoanReason)
    select PullID,
        PullListID, PullLocation, PullDate, PullTime, Puller, PullNotes, VolumeID, 0, 
        PullOutDate, PullOutTime,
        convert(varchar(50), getdate(), 111), convert(varchar(50), getdate(), 108), 
        (case when isnull(@LoanNote, '') = '' then LoanNote else @LoanNote end),
        CLRequestPriority, HospitalID, LoanReason
    from CL_PullList
    where PullID = @PullID 

	DELETE FROM CL_PullList
	Where PullID = @PullID 

--     if isnull(@DeleteOnly, 0) = 0
--         insert CL_PullList_Purged(PullListID, PullLocation, PullDate, PullTime, Puller, PullNotes, 
--             VolumeID, PullListStatus, PullOutDate, PullOutTime, LoanDate, LoanTime, LoanNote, CLRequestPriority, HospitalID)
--         select 
--             PullListID, PullLocation, PullDate, PullTime, Puller, PullNotes, VolumeID, 0, 
--             PullOutDate, PullOutTime,
--             convert(varchar(50), getdate(), 111), convert(varchar(50), getdate(), 108), 
--             (case when isnull(@LoanNote, '') = '' then LoanNote else @LoanNote end),
--             CLRequestPriority, HospitalID
--         from CL_PullList
--         where PullListID = @PullID and VolumeID = @VolumeID 
--             AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)            
-- 
-- 	DELETE FROM CL_PullList
-- 	Where PullListID = @PullID and VolumeID = @VolumeID
--             AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)            
    return(@@rowcount)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE  PROCEDURE [D_PullList_Purge]
	@PullID as int, 
    @Coder    as int
AS 
    declare @DelCoder int
    declare @DelDate datetime    

--Judy thinks we don't need to add this:
--     insert into  REC_Purge(AppID, RecordID, CareType, ICDType, InstNumber, ChartNumber, FullName, 
--         VisitDate, VisitTime, DeleteCoder, DeleteDate, DeleteTime, PurgeCoder, PurgeDate, PurgeTime)
--     select 11, PullID, PullListID,  VolumeNumber, l.Displaycode, ChartNumber, 
--         left(isnull(c.LastName + ', ', '') + isnull(FirstName, ''), 100),
--         PullDate, pulltime, null, null, null, @coder, getdate(), getdate()
--     from CL_PullList p
--         inner join cm_cpi_volume v on p.VolumeID = v.VolumeID
--         inner join cm_cpi c on v.patientid = c.patientid
--         inner join LoanLU_Location l on p.pulllocation = l.code
--     where PullID = @PullID


    DELETE FROM CL_PullList	Where PullID = @PullID 

    if @@ROWCOUNT = 0 
    begin
--         select @DelDate = max(Updated) from dbo.CL_PullListUpdateHistory where PullID = @PullID and UpdateType like 'p%'
--         select @DelCoder = Coder from dbo.CL_PullListUpdateHistory where PullID = @PullID and UpdateType like 'p%' and @DelDate = Updated

--         insert into  REC_Purge(AppID, RecordID, CareType, ICDType, InstNumber, ChartNumber, FullName, 
--             VisitDate, VisitTime, DeleteCoder, DeleteDate, DeleteTime, PurgeCoder, PurgeDate, PurgeTime)
--         select 11, PullID, PullListID, VolumeNumber, l.Displaycode, ChartNumber, 
--             left(isnull(c.LastName + ', ', '') + isnull(FirstName, ''), 100),
--             PullDate, pulltime, @DelCoder, @DelDate, @DelDate, @coder, getdate(), getdate()
--         from CL_PullList_Purged p
--             inner join cm_cpi_volume v on p.VolumeID = v.VolumeID
--             inner join cm_cpi c on v.patientid = c.patientid
--             inner join LoanLU_Location l on p.pulllocation = l.code
--         where PullID = @PullID

        DELETE FROM CL_PullList_Purged Where PullID = @PullID 
    end

    delete from  CL_PullListUpdateHistory where PullID = @PullID 



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE  PROCEDURE [D_PullList_Purged]
	@Date as datetime,
    @HospID as int
AS 

	DELETE 
    FROM CL_PullList_Purged
	Where LoanDate <= @Date
        AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
    return(@@rowcount)


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_REC_Notes]
	(@AppID 	[int],
	 @RecordID 	[int])

AS
DELETE FROM  [dbo].[REC_Notes] WHERE [AppID] = @AppID AND [RecordID] = @RecordID



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [D_RH_Activity]
	(@AbstractID 	[int])
AS 
DELETE [dbo].[RH_Activity]  WHERE  ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [D_RH_Administrative]
	(@AbstractID 	[int])
AS 
DELETE [dbo].[RH_Administrative] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_RH_Ancillary]	(@AbstractID [int])
AS 

DELETE [RH_Ancillary] WHERE ([AbstractID] = @AbstractID)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE PROCEDURE [D_RH_BasicOption] (@AbstractID [int])
AS
 
DELETE [RH_BasicOption] WHERE ([AbstractID] = @AbstractID)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE    PROCEDURE [D_RH_ClientInfo]
	(@AbstractID	[int])
AS 

delete [dbo].[RH_Activity] where ([AbstractID] = @AbstractID)
delete [dbo].[RH_Administrative] where ([AbstractID] = @AbstractID)
delete [dbo].[RH_Ancillary] where ([AbstractID]	 = @AbstractID)
delete [dbo].[RH_BasicOption] where ([AbstractID] = @AbstractID)
delete [dbo].[RH_ClientInfo] where ([AbstractID] = @AbstractID)
delete [dbo].[RH_Demographic] where ([AbstractID] = @AbstractID)
delete [dbo].[RH_Diagnosis] where ([AbstractID] = @AbstractID)
delete [dbo].[RH_FollowUpAssess] where ([AbstractID] = @AbstractID)
delete [dbo].[RH_Health]  where ([AbstractID] = @AbstractID)
delete [dbo].[RH_Project] where ([AbstractID] = @AbstractID)
delete [dbo].[RH_Provider] where ([AbstractID] = @AbstractID)
delete [dbo].[RH_Rehabilitation] where ([AbstractID] = @AbstractID)
delete [dbo].[RH_ServiceInterupt] where ([AbstractID] = @AbstractID)
delete [dbo].[RH_UDAbstracting]  where ([AbstractID] = @AbstractID)
delete [dbo].[RH_UpdateHistory]  where ([AbstractID] = @AbstractID)
delete AB_Main where AppID in (250, 251, 252, 253) and AbstractID = @AbstractID
delete REC_Notes where AppID in (250, 251, 252, 253) and RecordID = @AbstractID
delete AB_ErrorMessageFields where AppID in (250, 251, 252, 253) and [AbstractID] = @AbstractID
delete AB_ErrorMessages where AppID in (250, 251, 252, 253) and [AbstractID] = @AbstractID
delete AB_UpdateAudit where AppID in (250, 251, 252, 253) and [AbstractID] = @AbstractID

Delete RH_FIM_RPG where LinkID = @AbstractID
Delete dbo.RH_Therapy where AbstractID = @AbstractID
Delete dbo.RH_FIM_Score where AbstractID = @AbstractID

delete [RH_UDFieldsDate] where ([AbstractID] = @AbstractID)
delete [RH_UDFieldsTime] where ([AbstractID] = @AbstractID)
delete [RH_UDFieldsLookUp] where ([AbstractID] = @AbstractID)
delete [RH_UDFieldsInteger] where ([AbstractID] = @AbstractID)
delete [RH_UDFieldsText] where ([AbstractID] = @AbstractID)
delete [RH_UDFieldsSmallText] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [D_RH_Demographic]
	(@AbstractID 	[int])
AS 
DELETE [dbo].[RH_Demographic] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [D_RH_Diagnosis]
	(@AbstractID 	[int])
AS 
DELETE [dbo].[RH_Diagnosis] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [D_RH_FollowUpAssess]
	(@AbstractID 	[int])
AS 
DELETE [dbo].[RH_FollowUpAssess] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [D_RH_Health]
	(@AbstractID 	[int])
AS DELETE [dbo].[RH_Health]  WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [D_RH_Intervention] (@AbstractID [int])
AS 

DELETE [RH_Intervention] WHERE ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE PROCEDURE [D_RH_Project] (@AbstractID [int])
AS 

DELETE [RH_Project] WHERE ([AbstractID] = @AbstractID)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [D_RH_Provider]
	(@AbstractID 	[int])

AS DELETE [dbo].[RH_Provider] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [D_RH_Rehabilitation]
	(@AbstractID 	[int])

AS 
DELETE [dbo].[RH_Rehabilitation] WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE  PROCEDURE [D_RH_ServiceInterupt]
	(@AbstractID 	[int])

AS 
--DELETE [dbo].[RH_ServiceInterupt] WHERE ([AbstractID]	 = @AbstractID) --ED-01557
delete [RH_ServiceInterupt] where [AbstractID] in (select AbstractID from RH_ClientInfo where LinkID = @AbstractID)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE PROCEDURE [D_RH_Therapy] (@AbstractID [int])
AS
 
DELETE [RH_Therapy] WHERE ([AbstractID] = @AbstractID)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [D_RH_UDAbstracting]
	(@AbstractID 	[int])

AS 
DELETE [dbo].[RH_UDAbstracting] WHERE ([AbstractID] = @AbstractID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--CM_UDFieldsDate
--RH_UDFieldsDate
--RH_UDFieldsDate
--CRS_UDFieldsDate
--OMHRS_UDFieldsDate
--CC_UDFieldsDate
--ROI_UDFieldsDate

create PROCEDURE [D_RH_UDFieldsDate]
	(@AbstractID 	[int])
as
delete [dbo].[RH_UDFieldsDate] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_RH_UDFieldsInteger]
	(@AbstractID 	[int])
as
delete [dbo].[RH_UDFieldsInteger] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_RH_UDFieldsLookUp]
	(@AbstractID 	[int])
as
delete [dbo].[RH_UDFieldsLookUp] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_RH_UDFieldsSmallText]
	(@AbstractID 	[int])
as
delete [dbo].[RH_UDFieldsSmallText] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_RH_UDFieldsText]
	(@AbstractID 	[int])
as
delete [dbo].[RH_UDFieldsText] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_RH_UDFieldsTime]
	(@AbstractID 	[int])
as
delete [dbo].[RH_UDFieldsTime] where ([AbstractID] = @AbstractID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






CREATE PROCEDURE [D_ROI_Actions]
	(@ROIID [int])
AS DELETE [ROI_Actions]  WHERE ([ROIID] = @ROIID)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [D_ROI_Document]
	(@ROIID [int])
AS DELETE [ROI_Document] WHERE ([ROIID] = @ROIID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [D_ROI_Main]
	(@ROIID [int])
AS 
DELETE [ROI_Main] WHERE ([ROIID] = @ROIID)
DELETE [ROI_Actions]  WHERE ([ROIID] = @ROIID)
DELETE [ROI_Payments] WHERE ([ROIID] = @ROIID)
DELETE ROI_RequesterInfo WHERE ([ROIID] = @ROIID)
DELETE [ROI_SentItems] WHERE ([ROIID] = @ROIID)
DELETE [ROI_UserDefined] WHERE ( [ROIID] = @ROIID)
delete [ROI_UpdateHistory] WHERE ( [ROIID] = @ROIID)

delete [ROI_UDFieldsDate] where ( [ROIID] = @ROIID)
delete [ROI_UDFieldsTime] where ( [ROIID] = @ROIID)
delete [ROI_UDFieldsLookUp] where ( [ROIID] = @ROIID)
delete [ROI_UDFieldsInteger] where ( [ROIID] = @ROIID)
delete [ROI_UDFieldsText] where ( [ROIID] = @ROIID)
delete [ROI_UDFieldsSmallText] where ( [ROIID] = @ROIID)

delete REC_Notes where AppID = 30 and RecordID = @ROIID --EN - 00533
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






CREATE PROCEDURE [D_ROI_Payments]
	(@ROIID [int])
AS DELETE [ROI_Payments] WHERE ([ROIID] = @ROIID)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [D_ROI_RequesterInfo]
	(@ROIID 	[int])

AS 
DELETE [dbo].[ROI_RequesterInfo]  WHERE ( [ROIID] = @ROIID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






CREATE PROCEDURE [D_ROI_SentItems]
	(@ROIID [int])
AS DELETE [ROI_SentItems] WHERE ([ROIID] = @ROIID)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--CM_UDFieldsDate
--ROI_UDFieldsDate
--ROI_UDFieldsDate
--ROI_UDFieldsDate
--ROI_UDFieldsDate
--ROI_UDFieldsDate
--ROI_UDFieldsDate

create PROCEDURE [D_ROI_UDFieldsDate]
	(@ROIID 	[int])
as
delete [dbo].[ROI_UDFieldsDate] where ([ROIID] = @ROIID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_ROI_UDFieldsInteger]
	(@ROIID 	[int])
as
delete [dbo].[ROI_UDFieldsInteger] where ([ROIID] = @ROIID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_ROI_UDFieldsLookUp]
	(@ROIID 	[int])
as
delete [dbo].[ROI_UDFieldsLookUp] where ([ROIID] = @ROIID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_ROI_UDFieldsSmallText]
	(@ROIID 	[int])
as
delete [dbo].[ROI_UDFieldsSmallText] where ([ROIID] = @ROIID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_ROI_UDFieldsText]
	(@ROIID 	[int])
as
delete [dbo].[ROI_UDFieldsText] where ([ROIID] = @ROIID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_ROI_UDFieldsTime]
	(@ROIID 	[int])
as
delete [dbo].[ROI_UDFieldsTime] where ([ROIID] = @ROIID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE PROCEDURE [D_ROI_UserDefined]
	(@ROIID 	[int])

AS 
DELETE [ROI_UserDefined] WHERE ( [ROIID] = @ROIID)


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE  PROCEDURE [D_SH_Appointments] 
	(@RecordID 	[int])
AS 

DELETE SH_Appointments WHERE ([AppointmentID] = @RecordID AND ISNULL([Status], 0) <> 11735)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [D_Transcription] (@TransID [int])
AS 

DELETE [TR_Main] WHERE ([TranscriptionID] = @TransID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [D_U_Permission] (@UserID [int])
AS
 	delete [U_Permission] WHERE ([UserID] = @UserID)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


Create procedure [DSS_Create_LinkServer]
    @ExecutionID   int, 
    @ServerName    varchar(50),    @Database    varchar(50),
    @UserName      varchar(50),    @Password    varchar(50),
    @Language      int,
	@Succeed 		char(1) output,	@Message		varchar(200) output
as
    declare @Result int
    declare @SQL nvarchar(1000)    
    set @Succeed = ''
    if ltrim( @ServerName ) = '' set @ServerName = null
    if ltrim( @Database ) = '' set @Database = null
    if ltrim( @UserName ) = '' set @UserName = null
    if ltrim( @Password ) = '' set @Password = null

    if @ServerName is null or @Database is null or @UserName is null or
        ( @UserName <> 'Med2020Main' and @Password is null )
    begin
        set @Succeed = 'E'
    	if @Succeed = 'E' set @Message = dbo.DSS_F_Load_Information( '800000-01', @Language )	
    end
    if @Succeed <> 'E'    --Add Link Server
    begin
        if not exists ( select * from master.dbo.sysservers where srvname = '_Med2020_MEDDSS' )
        begin
            set @Sql = N'sp_addlinkedserver @server=''_Med2020_MEDDSS' + cast(@ExecutionID as varchar(10)) +  ''', @srvproduct='''',
                           @provider=''SQLOLEDB'', @datasrc=''' + @ServerName + ''', @catalog = ''' + @Database + ''' '
            --print @sql
            exec sp_executesql @Sql
        
        	set @Succeed = ( case when @@Error <> 0 then 'E' else 'Y' end )
        	if @Succeed = 'E' set @Message = dbo.DSS_F_Load_Information( '860022-01', @Language )	
        end
    end
    if @Succeed <> 'E'    --Add Link Login
    begin
        if ( @UserName = 'Med2020Main' )
            set @Sql = N'sp_addlinkedsrvlogin  @rmtsrvname =  ''_Med2020_MEDDSS' + cast(@ExecutionID as varchar(10)) +  ''' 
             ,  @useself =  ''true'' '  
        else
            set @Sql = N'sp_addlinkedsrvlogin  @rmtsrvname =  ''_Med2020_MEDDSS' + cast(@ExecutionID as varchar(10)) +  ''' 
             ,  @useself =  ''false''  
             ,  @locallogin =  ''Med2020Main''  
             ,  @rmtuser =  ''' + @UserName + '''  
             ,  @rmtpassword =  ''' + @Password + '''  '
        exec sp_executesql @Sql
        --print @sql
    	set @Succeed = ( case when @@Error <> 0 then 'E' else 'Y' end )
    	if @Succeed = 'E' 
        begin
            set @Message = dbo.DSS_F_Load_Information( '860022-02', @Language )	
            exec DSS_Drop_LinkServer @Language, @Succeed, @Message
        end
    end 


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


Create procedure [DSS_Drop_LinkServer]
    @ExecutionID   int,
    @Language      int,
	@Succeed 	   char(1) output,	@Message		varchar(200) output
as
    declare @Sql Nvarchar(1000)
    set @Sql = N'sp_droplinkedsrvlogin  @rmtsrvname =  ''_Med2020_MEDDSS' + cast(@ExecutionID as varchar(10)) + ''' , @locallogin=''Med2020main'' '
    exec  sp_executesql @Sql
   	set @Succeed = ( case when @@Error <> 0 then 'E' else 'Y' end )

    set @Sql = '_Med2020_MEDDSS' + cast(@ExecutionID as varchar(10)) 
    exec sp_dropserver @server =  @sql
   	set @Succeed = ( case when @@Error <> 0 then 'E' else 'Y' end )
    if @Succeed = 'E' set @Message = dbo.DSS_F_Load_Information( '860023-01', @Language )	


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



Create procedure [DSS_I_Import_Category]
    @Category   varchar(50),
    @ServerName varchar(50),    @DatabaseName varchar(50),
    @UserName   varchar(50),    @Password     varchar(50),
    @IsEnabled  int = 1,        @HospitalID   int,
    @Language   int,            @CategoryID   int output,         
    @Succeed    char(1) output, @Message      varchar(200) output
as
    declare @UpdateDate datetime
    declare @EncryPassword varchar(100)
    set @Succeed = ''
    set @UpdateDate = getdate()
    if  @UserName <> 'med2020main' -- and @ServerName <> '(local)' 
    begin
        set @EncryPassword = dbo.DSS_F_FillIn( @Password, @UpdateDate )
        set @EncryPassword = rtrim( dbo.DSS_F_GetOut( @EncryPassword, @UpdateDate ))
        if isnull( @EncryPassword, '' ) <> @Password or @Password is null
        begin
            set @Succeed = 'E'
            set @Message = dbo.DSS_F_Load_Information( '870001-01', @Language )	
        end
    end
    else set @password = ''

    if exists (select * from DSS_Import_Category where HospitalID = @HospitalID )
    begin
        Update dbo.DSS_Import_Category
        set Category = @Category, 
            ServerName   = @ServerName, 
            DatabaseName = @DatabaseName, 
            UserName     = @UserName, 
            [Password]   = @Password, 
            UpdateDate   = @UpdateDate, 
            IsEnabled    = @IsEnabled
        where HospitalID = @HospitalID
    end
    else
    begin
        set @CategoryID = isnull((select max(CategoryID) from DSS_Import_Category), 0) + 1
        insert dbo.DSS_Import_Category( CategoryID, Category, ServerName, DatabaseName, UserName, [Password], UpdateDate, IsEnabled, HospitalID )
        values ( @CategoryID, @Category, @ServerName, @DatabaseName, @UserName, @Password, @UpdateDate, @IsEnabled, @HospitalID )
    end    
	set @Succeed = (case when @@Rowcount > 0 then 'Y' when @@Error <> 0 then 'E' else 'N' end )
	if @Succeed = 'E' set @Message = dbo.DSS_F_Load_Information( '800000-20', @Language )	




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE   procedure [DSS_Upload_GetRecords]
  @ExecutionID int
, @AppID     int
, @SubID     int
, @Hospital  int
, @CountVerify int output 
as 

set nocount on

declare 
  @txt varchar(1000) 
, @sql varchar(8000) 
 
--declare cur cursor local fast_forward for 
    select txt = SqlSegment 
    from dbo.DSS_F_GetQuery ( @ExecutionID, @AppID, @SubID, @Hospital )
    order by SegmentType, OrderBy 

-- open cur 
-- 
-- set @sql = '' 
--  
-- while (1=1) begin 
--     fetch next from cur into @txt 
--     if (@@fetch_status <> 0) break 
--     set @sql = @sql + ' ' + @txt 
-- end 
-- 
-- close cur
-- deallocate cur

set nocount off

--exec ( @sql ) 
set @CountVerify = @@rowcount 

--print @sql
return 0 




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE procedure [DSS_Upload_Init_Abstract]
    @ExecutionID  int,
    @HospitalID   int,
    @AppID        int,
    @ICDType      char(1),
    @InstNoCode   int,
    @DateFrom     datetime,
    @DateTo       datetime,
    @ServerName   varchar(50),
    @DatabaseName varchar(50),
    @CoderNumber  int = 999999,
    @RecordCount  int output,
    @ProvNoCIHI   varchar(1)   output,
    @InstNoCIHI   varchar(5)   output,
    @ErrorCode    varchar(12)  output
as

declare @DateSent datetime
declare @Local_Server varchar(50)
declare @Sql nvarchar(2000)
declare @MaxID int
declare @LinkServer varchar(100)

declare @Updated     datetime
declare @NewID       int
declare @IsCompleted int
declare @NewDate     datetime

--set @Local_Server = cast( SERVERPROPERTY('servername') as varchar(50) )
--if @ServerName = '(local)' or @ServerName = @Local_Server set @ServerName = null

set @ErrorCode = ''

create table #InsertRecords  ( LinkID int, OrderBy int identity(1,1) )
create table #UpdateRecords  ( AbstractID int, LinkID int )
create table #DeleteRecords  ( AbstractID int, LinkID int )

declare @InsertCount int
declare @UpdateCount int
declare @DeleteCount int

set @DateSent = GetDate()
set @LinkServer = dbo.DSS_F_Get_Database( @ExecutionID, @HospitalID )

-- get a list of AbstractID's that will be used to creat the submission file

------------------------------------------------------------------------------------
-- INPATIENT/SDS INSTITUTIONS ICD 9, 9CM, ICD 10
if (@AppID in (101, 102, 201, 202)) begin

    set @Sql = 'select ab.AbstractID 
    FROM AB_Main AB 
        inner join H_InstitutionProfile H on AB.InstitutionNumber = H.Code
        left join ' + @LinkServer + 'DSS_AB_Main DSS 
        on AB.UniversalID = DSS.LinkID 
            and (isnull(AB.HospitalID, 0) = 0 or AB.HospitalID = ' + cast(@HospitalID as varchar(10)) + ') 
            and DSS.AppID in ( 101, 102, 201, 202 ) 
            and DSS.HospitalID = ' + cast(@HospitalID as varchar(10)) + ' 
            and AB.ChartNumber = DSS.ChartNumber
        
    where DSS.LinkID is null
        and AB.DischargeDate between ''' + convert(varchar(10), @DateFrom, 111) + ''' and ''' + convert(varchar(10), @DateTo, 111) + ''' ' +
        (case when @InstNoCode > 0 then ' and AB.InstitutionNumber = ' + cast(@InstNoCode as varchar(10))  else '' end) +
        (case when @ICDType = 'T' 
              then ' and H.ValidFrom >= H.ICDTLive' 
              else ' and H.ValidTo < H.ICDTLive ' end) + ' and AB.AppType in (1, 2) '
        
--        + (case when @IsSubmited_CIHI = '1' then ' and (select top 1 CIHIValue from ' + dbo.DSS_F_Get_Database( @HospitalID ) + 'LU_YesNoSystem where Code = AB.IsSubmited ) = ''1'' ' else '' end )
 
    insert #InsertRecords( LinkID )
    exec (@sql)
    set @InsertCount = @@Rowcount

    set @Sql = 'select DSS.ABstractID, DSS.LinkID 
        FROM AB_Main AB 
            inner join H_InstitutionProfile H on AB.InstitutionNumber = H.Code
            inner join ' + @LinkServer + 'DSS_AB_Main DSS 
            on AB.UniversalID = DSS.LinkID 
                and (isnull(AB.HospitalID, 0) = 0 or AB.HospitalID = ' + cast(@HospitalID as varchar(10)) + ') 
                and DSS.AppID in ( 101, 102, 201, 202 )
                and AB.ChartNumber = DSS.ChartNumber
            inner join (select AbstractID, max( Updated ) as DateStamp from AB_UpdateHistory where UpdateType = ''saved'' group by AbstractID ) U on AB.AbstractID = U.AbstractID and AB.AppType in (1, 2)
        where AB.DischargeDate between ''' + convert(varchar(10), @DateFrom, 111) + ''' and ''' + convert(varchar(10), @DateTo, 111) + ''' ' +
            + ' and ( dbo.DSS_GET_Date_int( U.DateStamp ) > dbo.DSS_GET_Date_int( DSS.TSIDate ) or ( dbo.DSS_GET_Date_int( U.DateStamp ) = dbo.DSS_GET_Date_int( DSS.TSIDate ) and dbo.DSS_GET_TIME_int( U.DateStamp ) > dbo.DSS_GET_TIME_int( DSS.TSITime )))' +
            + ' and DSS.HospitalID = ' + cast(@HospitalID as varchar(10)) +  
            (case when @InstNoCode > 0 then ' and AB.InstitutionNumber = ' + cast(@InstNoCode as varchar(10))  else '' end) +
            (case when @ICDType = 'T' then ' and H.ValidFrom >= H.ICDTLive ' else ' and H.ValidTo < H.ICDTLive ' end)
            + ' and AB.AppType in (1, 2) '
--            + (case when @IsSubmited_CIHI = '1' then ' and (select top 1 CIHIValue from ' + dbo.DSS_F_Get_Database( @HospitalID ) + 'LU_YesNoSystem where Code = AB.IsSubmited ) = ''1'' ' else '' end )
--            + (case when @AbstractID is not null then ' and AB.AbstractID = ' + cast( @AbstractID as varchar(10)) + ' ' else '' end ) '
  
    insert #UpdateRecords( AbstractID, LinkID )
    exec (@sql)
    set @UpdateCount = @@Rowcount

    set @Sql = 'select DSS.ABstractID, DSS.LinkID 
        FROM ' + @LinkServer + 'DSS_AB_Main DSS 
            left join AB_Main AB 
                on AB.UniversalID = DSS.LinkID 
                and DSS.AppID in ( 101, 102, 201, 202 )
                and AB.ChartNumber = DSS.ChartNumber
        where DSS.DischargeDate between ''' + convert(varchar(10), @DateFrom, 111) + ''' and ''' + convert(varchar(10), @DateTo, 111) + '''  
            and AB.UniversalID is null 
            and DSS.HospitalID = ' + cast(@HospitalID as varchar(10)) +   
            (case when @InstNoCode > 0 then ' and DSS.InstitutionNumber = ' + cast(@InstNoCode as varchar(10)) else '' end) 
            + ' and DSS.AppType in (1, 2) '

    insert #DeleteRecords( AbstractID, LinkID )
    exec (@sql)
    set @DeleteCount = @@Rowcount


end
------------------------------------------------------------------------------------
-- AMCARE INSTITUTIONS, ICD 10 (AND ALBERTA)
else if (@AppID in (301, 401)) begin
    set @Sql = 'select ab.AbstractID 
    FROM AB_Main AB 
        inner join H_InstitutionProfile H on AB.InstitutionNumber = H.Code
        left join ' + @LinkServer + 'DSS_AB_Main DSS 
        on AB.UniversalID = DSS.LinkID and 
            (isnull(AB.HospitalID, 0) = 0 or AB.HospitalID = ' + cast(@HospitalID as varchar(10)) + ') 
            and DSS.AppType in ( 5, 9 ) 
            and DSS.HospitalID = ' + cast(@HospitalID as varchar(10)) + ' 
            and AB.ChartNumber = DSS.ChartNumber
    where DSS.LinkID is null
        and AB.AdmitDate between ''' + convert(varchar(10), @DateFrom, 111) + ''' and ''' + convert(varchar(10), @DateTo, 111) + ''' ' +
        (case when @InstNoCode > 0 then ' and AB.InstitutionNumber = ' + cast(@InstNoCode as varchar(10))  else '' end) +
        (case when @ICDType = 'T' then ' and H.ValidFrom >= H.ICDTLive ' else ' and H.ValidTo < H.ICDTLive ' end)
        + ' and AB.AppType in (5, 9) '
--        + (case when @IsSubmited_CIHI = '1' then ' and (select top 1 CIHIValue from ' + dbo.DSS_F_Get_Database( @HospitalID ) + 'LU_YesNoSystem where Code = AB.IsSubmited ) = ''1'' ' else '' end )
--print 'Amcare -----------------'
--print @sql 
    insert #InsertRecords( LinkID )
    exec (@sql)
    set @InsertCount = @@Rowcount

    set @Sql = 'select DSS.ABstractID, DSS.LinkID 
        FROM AB_Main AB 
            inner join H_InstitutionProfile H on AB.InstitutionNumber = H.Code
            inner join ' + @LinkServer + 'DSS_AB_Main DSS 
            on AB.UniversalID = DSS.LinkID 
                and (isnull(AB.HospitalID, 0) = 0 or AB.HospitalID = ' + cast(@HospitalID as varchar(10)) + ') 
                and DSS.AppType in ( 5, 9 ) 
                and AB.ChartNumber = DSS.ChartNumber
            inner join (select AbstractID, max( Updated ) as DateStamp from AB_UpdateHistory where UpdateType = ''saved'' group by AbstractID ) U on AB.AbstractID = U.AbstractID and AB.AppType in (1, 2)
        where AB.AdmitDate between ''' + convert(varchar(10), @DateFrom, 111) + ''' and ''' + convert(varchar(10), @DateTo, 111) + ''' ' +
            + ' and ( dbo.DSS_GET_Date_int( U.DateStamp ) > dbo.DSS_GET_Date_int( DSS.TSIDate ) or ( dbo.DSS_GET_Date_int( U.DateStamp ) = dbo.DSS_GET_Date_int( DSS.TSIDate ) and dbo.DSS_GET_TIME_int( U.DateStamp ) > dbo.DSS_GET_TIME_int( DSS.TSITime )))' +
            + ' and DSS.HospitalID = ' + cast(@HospitalID as varchar(10)) +  
            (case when @InstNoCode > 0 then ' and AB.InstitutionNumber = ' + cast(@InstNoCode as varchar(10))  else '' end) + 
            (case when @ICDType = 'T' then ' and H.ValidFrom >= H.ICDTLive ' else ' and H.ValidTo < H.ICDTLive ' end)
            + ' and AB.AppType in (5, 9) '

--            + (case when @IsSubmited_CIHI = '1' then ' and (select top 1 CIHIValue from ' + dbo.DSS_F_Get_Database( @HospitalID ) + 'LU_YesNoSystem where Code = AB.IsSubmited ) = ''1'' ' else '' end )
--            + (case when @AbstractID is not null then ' and AB.AbstractID = ' + cast( @AbstractID as varchar(10)) + ' ' else '' end ) '
  
--print @sql 

    insert #UpdateRecords( AbstractID, LinkID )
    exec (@sql)
    set @UpdateCount = @@Rowcount

    set @Sql = 'select DSS.ABstractID, DSS.LinkID 
        FROM ' + @LinkServer + 'DSS_AB_Main DSS 
            left join AB_Main AB 
                on AB.UniversalID = DSS.LinkID 
                    and DSS.AppType in ( 5, 9 )
                    and DSS.HospitalID = ' + cast(@HospitalID as varchar(10)) + ' 
                    and AB.ChartNumber = DSS.ChartNumber
        where DSS.AdmitDate between ''' + convert(varchar(10), @DateFrom, 111) + ''' and ''' + convert(varchar(10), @DateTo, 111) + '''  
            and AB.UniversalID is null 
            and DSS.HospitalID = ' + cast(@HospitalID as varchar(10)) +   
            (case when @InstNoCode > 0 then ' and DSS.InstitutionNumber = ' + cast(@InstNoCode as varchar(10))  else '' end)

--print @sql 

    insert #DeleteRecords( AbstractID, LinkID )
    exec (@sql)
    set @DeleteCount = @@Rowcount

end

------------------------------------------------------------------------------------
--Detemined the max id
delete DSS_Upload_RecordSelect where ExecutionID = @ExecutionID

set @sql = 'select @MaxID = max(AbstractID) from ' + @LinkServer + 'DSS_AB_Main '

exec sp_executesql @sql, N'@MaxID int output', @MaxID output

set @MaxID = isnull(@MaxID, 0) 

set @sql = 'select top 1 @NewID = AbstractID, @Updated = Updated, @IsCompleted = IsCompleted from ' + @LinkServer + 'DSS_AB_Completed '

exec sp_executesql @sql, N'@NewID int output, @Updated datetime output, @IsCompleted int output', @NewID output, @Updated output, @IsCompleted output

set @NewDate = getdate()
if @IsCompleted = 0 and datediff(minute, @Updated, @NewDate) < 5
    set @ErrorCode = 'DL000001' 
--print '1         ' + @ErrorCode

if @MaxID < @NewID 
    set @MaxID = @NewID

if @ErrorCode = ''
begin
    set @sql = 'update ' + @LinkServer + 'DSS_AB_Completed 
        set AbstractID = ' + cast(@MaxID as varchar(10)) + ',
            Updated = ''' + cast(@NewDate as varchar(50)) + ''', 
            IsCompleted = 0 
        where AbstractID = ' + cast(@NewID as varchar(10)) + ' and
              Updated = ''' + cast(@Updated as varchar(50)) + ''' and 
              IsCompleted = ' + cast(@IsCompleted as varchar(10)) 
    exec (@sql)
    
    if @@Rowcount = 0  set @ErrorCode = 'DL000001'

--    print '2         ' + @ErrorCode
 
    set @Updated = @NewDate
    set @IsCompleted = 0
    set @NewID = @MaxID

end
if @ErrorCode = ''
begin
    --------------------------------
    --Insert 
    insert DSS_Upload_RecordSelect ( 
        ExecutionID, 
        HospitalID, 
        AbstractID, 
        LinkID, 
        IsDeleted, 
        IsPurgeed,
        TSIDate, 
        TSITime)
    select 
        @ExecutionID   , 
        @HospitalID    ,
        r.OrderBy + @MaxID  ,
        m.AbstractID   , 
        a.IsDeleted    ,
        2,
        convert(varchar(50), @DateSent, 111),
        convert(varchar(50), @DateSent, 108)
    from #InsertRecords r join AB_Main m on r.LinkID = m.UniversalID
        inner join AB_Abstract a on m.AbstractID = a.AbstractID
    order by OrderBy
    set @MaxID = @MaxID + @@Rowcount

    -- Update
    insert DSS_Upload_RecordSelect ( 
        ExecutionID, 
        HospitalID, 
        AbstractID, 
        LinkID, 
        IsDeleted, 
        IsPurgeed,
        TSIDate, 
        TSITime)
    select 
        @ExecutionID   , 
        @HospitalID    ,
        r.AbstractID  ,
        m.AbstractID   , 
        a.IsDeleted    ,
        2,
        convert(varchar(50), @DateSent, 111),
        convert(varchar(50), @DateSent, 108)
    from #UpdateRecords r join AB_Main m on r.LinkID = m.UniversalID
        inner join AB_Abstract a on m.AbstractID = a.AbstractID
    -- Delete
    set @sql = 'select 
        ' + cast(@ExecutionID as varchar(10)) + '  , 
        ' + cast(@HospitalID as varchar(10)) + '   ,
        a.AbstractID   ,
        a.LinkID   , 
        1,
        1,
        ''' + convert(varchar(50), @DateSent, 111) + ''',
        ''' + convert(varchar(50), @DateSent, 108) + '''
    from #DeleteRecords r join ' + @LinkServer + 'DSS_AB_Main a on r.AbstractID = a.AbstractID '

--exec( @sql)
    
    insert DSS_Upload_RecordSelect ( 
        ExecutionID, 
        HospitalID, 
        AbstractID, 
        LinkID, 
        IsDeleted, 
        IsPurgeed,
        TSIDate, 
        TSITime)
    exec (@sql)
    
    DBCC DBREINDEX (DSS_Upload_RecordSelect)
    
    -- delete the DSS records for the update and purge
    exec DSS_UpLoad_Purge_Abstract @ExecutionID, @HospitalID  
    ------------------------------------------------------------------------------------
    
    select @ProvNoCIHI = CIHIValue from LU_Province where Code = (select top 1 ProvinceNumber from H_HospitalProfile where code = @HospitalID)
    select @InstNoCIHI = CIHIValue from H_InstitutionProfile where Code = @InstNoCode
    
    -----------------------------------------------------------------------------------
    -- UPDATE THE EXECUTION PROPERTIES TABLE WITH THE VARIOUS VALUES    
    update dbo.DSS_Upload_ExecProperties
    set ExecutionDate = @DateSent, 
        InsertCount = @InsertCount,
        UpdateCount = @UpdateCount,
        DeleteCount = @DeleteCount,    
        ProvNoCIHI  = @ProvNoCIHI ,
        InstNoCIHI  = @InstNoCIHI 
    where ExecutionID = @ExecutionID

    set @sql = 'update ' + @LinkServer + 'DSS_AB_Completed 
        set AbstractID = ' + cast(@MaxID as varchar(10)) + ',
            Updated = ''' + cast(getdate() as varchar(50)) + ''', 
            IsCompleted = 1 
        where AbstractID = ' + cast(@NewID as varchar(10)) + ' and
              Updated = ''' + cast(@Updated as varchar(50)) + ''' and 
              IsCompleted = ' + cast(@IsCompleted as varchar(10)) 
    exec (@sql)
    

    if @@Rowcount = 0 set @ErrorCode = 'DL000001' 

end

drop table #InsertRecords
drop table #UpdateRecords
drop table #DeleteRecords

EXIT_PROCEDURE_NORMAL:
    return 0


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE procedure [DSS_Upload_Initialize]
    @HospitalID   int,
    @AppID        int,
    @ICDType      char(1),
    @InstNoCode   int,
    @DateFrom     datetime,
    @DateTo       datetime,
    @ServerName   varchar(50),
    @DatabaseName varchar(50),
    @UserName     varchar(50),
    @Password     varchar(50),
    @CoderNumber  int = 999999,
    @Language     int,
    @ExecutionID  int output,
    @InstNoCIHI   varchar(5)   output,
    @Succeed      char(1) output,
    @Message      varchar(200) output
as

declare @Server   varchar(50)
declare @Database varchar(50)
declare @Local_Server varchar(50)

set @Local_Server = cast( SERVERPROPERTY('servername') as varchar(50) )

select top 1 
    @Server = ServerName, 
    @Database = @DatabaseName
from dbo.DSS_Import_Category
where HospitalID = @HospitalID

if isnull(@Server, '####') <> isnull(@ServerName, '@@@@') or
    isnull(@Database, '####') <> isnull(@DatabaseName, '@@@@')
begin
    set @Succeed = 'E'
    set @Message = 'Some one has changed the configure. Please redo the selection. '
end
else
begin
    insert dbo.DSS_Upload_ExecProperties(ExecutionDate, HospitalID, DateStart, DateEnd, InstNoCode, ICDType, AppID, ProvNoCIHI, InstNoCIHI, TerminateSuccess, ServerName, DatabaseName, CoderNumber)
    values( getdate(), @HospitalID, @DateFrom, @DateTo, @InstNoCode, @ICDType, @AppID, null, null, null, @ServerName, @DatabaseName, @CoderNumber)
    set @ExecutionID = @@IDENTITY
    
    if not (@ServerName = '(local)' or @ServerName = @Local_Server)
        exec DSS_Create_LinkServer @ExecutionID, @ServerName, @Database, @UserName, @Password, @Language, @Succeed output, @Message output
end


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE  procedure [DSS_UpLoad_Purge_Abstract] (
    @ExecutionID int, 
    @HospitalID  int
) 
as

declare @Sql  Nvarchar(2000)
declare @Table varchar(100)
declare @Database Nvarchar(100)

set @Database = dbo.DSS_F_Get_Database(@ExecutionID, @HospitalID )

set @sql = 'declare cur_dss_delete cursor for select distinct table_name from ' + 
    replace(@Database, '.dbo.', '.information_schema.columns') + 
    ' where table_name like ''DSS_AB%'' and column_name = ''AbstractID'' '

--print @sql
exec (@sql)

open cur_dss_delete

fetch next from cur_dss_delete into @Table

while(@@fetch_status = 0)
begin
    set @sql = 'delete from ' + @Database + @Table + 
        ' from ' + @Database + @Table + ' a inner join DSS_Upload_RecordSelect d ' +
        ' on a.AbstractID = d.AbstractID where d.ExecutionID = ' + cast(@ExecutionID as varchar(10))
--    print @sql
    exec (@sql)

    fetch next from cur_dss_delete into @Table
end
close cur_dss_delete
deallocate cur_dss_delete




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE   procedure [DSS_Upload_Steps]
    @IsICD10     int,
    @institution varchar(1000)
as

set nocount on
declare @AppID int
declare @Inst  int
declare @Total int
declare @InstCIHI varchar(12)
declare @Sql   varchar(2000)

declare @a table(
    AppID int,
    InstCode int,
    Total int,
    InstCIHI varchar(12)
)

if isnull(@institution, '') = ''
    set @sql = 'declare cur_sel_inst cursor for 
    select a.AppID, inst = 0, c.totalcount, ''''
    from
    (select AppID = (case when AssociationID = 1 and ValidTo < ICDTLive then 101 
                         when AssociationID = 2 and ValidTo < ICDTLive then 101 
                         when AssociationID = 5 and ValidTo < ICDTLive then 301 
                         when AssociationID = 1 and ValidFrom >= ICDTLive then 201 
                         when AssociationID = 2 and ValidFrom >= ICDTLive then 201 
                         when AssociationID = 3 and ValidFrom >= ICDTLive then 250 
                         when AssociationID = 4 and ValidFrom >= ICDTLive then 470 
                         when AssociationID = 5 and ValidFrom >= ICDTLive then 401 
                         else 401 end), Inst = min(code)
    from H_InstitutionProfile ' + (case when @IsICD10 = 1 then 'where ValidFrom >= ICDTLive ' else '' end) + 
    'group by (case when AssociationID = 1 and ValidTo < ICDTLive then 101 
                         when AssociationID = 2 and ValidTo < ICDTLive then 101 
                         when AssociationID = 5 and ValidTo < ICDTLive then 301 
                         when AssociationID = 1 and ValidFrom >= ICDTLive then 201 
                         when AssociationID = 2 and ValidFrom >= ICDTLive then 201 
                         when AssociationID = 3 and ValidFrom >= ICDTLive then 250 
                         when AssociationID = 4 and ValidFrom >= ICDTLive then 470 
                         when AssociationID = 5 and ValidFrom >= ICDTLive then 401 
                         else 401 end)) a inner join 
        (select AppID, count(*) as totalcount from
         (select distinct AppID, SubID
         from DSS_Upload_StructureFile) b group by AppID) c on a.AppID = c.AppID  '
else
    set @sql = 'declare cur_sel_inst cursor for 
    select a.AppID, a.inst, c.totalcount, CIHI = CIHIValue
    from
    (select AppID = (case when AssociationID = 1 and ValidTo < ICDTLive then 101 
                         when AssociationID = 2 and ValidTo < ICDTLive then 101 
                         when AssociationID = 5 and ValidTo < ICDTLive then 301 
                         when AssociationID = 1 and ValidFrom >= ICDTLive then 201 
                         when AssociationID = 2 and ValidFrom >= ICDTLive then 201 
                         when AssociationID = 3 and ValidFrom >= ICDTLive then 250 
                         when AssociationID = 4 and ValidFrom >= ICDTLive then 470 
                         when AssociationID = 5 and ValidFrom >= ICDTLive then 401 
                         else 401 end), Inst = code, CIHIValue
    from H_InstitutionProfile 
    where code in (' + @institution + ') ) a inner join 
        (select AppID, count(*) as totalcount from
         (select distinct AppID, SubID
         from DSS_Upload_StructureFile) b group by AppID) c on a.AppID = c.AppID  '
--print @sql

exec (@sql)

open cur_sel_inst

fetch next from cur_sel_inst into @AppID, @Inst, @Total, @InstCIHI
while(@@Fetch_status = 0)
begin
    insert @a values(@AppID, @Inst, @Total, @InstCIHI)
    fetch next from cur_sel_inst into @AppID, @Inst, @Total, @InstCIHI
end
close cur_sel_inst
deallocate cur_sel_inst

select * from @a
set nocount off



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE procedure [DSS_Upload_Terminate]
    @ExecutionID int,
    @IsTerminateWithError int
as
declare @cur cursor 
declare @AbstractID int
declare @sql nvarchar(200)

-- update the Execution Properties table with the completion status.
update DSS_Upload_ExecProperties 
set TerminateSuccess = case @IsTerminateWithError when 0 then 1 else 0 end
where ExecutionID = @ExecutionID

-- upon a successful submission file creation, this will 
-- update the appropriate fields in the AB_Abstract table.
if (@IsTerminateWithError = 0) begin

    -- REHAB SUBMISSION
    if exists(select * from DSS_Upload_ExecProperties where ExecutionID = @ExecutionID and AppID in (250, 251, 252, 253)) begin

        update RH_ClientInfo
        set TSIDate   = s.TSIDate   
          , TSITime   = s.TSITime
        from RH_ClientInfo a 
            join AB_Main m on a.AbstractID = m.AbstractID and m.AppType = 3
            join DSS_Upload_RecordSelect s on m.UniversalID = s.LinkID 
        where s.ExecutionID = @ExecutionID
    end
    -- CCRS SUBMISSION
    else 
    if exists(select * from DSS_Upload_ExecProperties where ExecutionID = @ExecutionID and AppID in (470, 471, 472, 473, 474, 475)) begin 

        update CRS_Demographic
        set TSIDate   = s.TSIDate   
          , TSITime   = s.TSITime
        from CRS_Demographic a 
            join AB_Main m on a.AbstractID = m.AbstractID and m.AppType = 4
            join DSS_Upload_RecordSelect s on m.UniversalID = s.LinkID 
        where s.ExecutionID = @ExecutionID

    end -- CCRS SUBMISSION

    -- REGULAR SUBMISSION
    else begin
        update AB_Abstract 
        set TSIDate   = s.TSIDate   
          , TSITime   = s.TSITime
        from AB_Abstract a 
            join AB_Main m on a.AbstractID = m.AbstractID and m.AppType not in  (3, 4, 6)
            join DSS_Upload_RecordSelect s on m.UniversalID = s.LinkID 
        where s.ExecutionID = @ExecutionID

    end -- REGULAR SUBMISSION

end

-- Store history of all records that were processed.
insert DSS_Upload_RecordHistory 
select * --ExecutionID, HospitalID, AbstractID, LinkID, OrderBy, IsCorrected, IsSubmited, IsValidated, IsCompleted, IsDeleted, IsPurgeed, TSIDate, TSITime
from DSS_Upload_RecordSelect 
where ExecutionID = @ExecutionID


-- After all is said and done, do some basic clean up.
delete from DSS_Upload_RecordSelect   where ExecutionID = @ExecutionID

declare @oldExecIDs table ( ExecutionID int )

insert @oldExecIDs ( ExecutionID ) 
select ExecutionID 
from DSS_Upload_ExecProperties
where datediff( day, ExecutionDate, getdate() ) > 1


delete DSS_Upload_RecordSelect
from DSS_Upload_RecordSelect r 
join @oldExecIDs x on r.ExecutionID = x.ExecutionID



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE  PROCEDURE [E_AB_Abstract] 
    @AbstractID int
AS 

--10489 Hong added temp
declare @LinkID    int
declare @CareType  int
declare @count     int

select 
    @LinkID   = LinkID, 
    @CareType = CareType
from AB_Abstract
WHERE AbstractID = @AbstractID

-- Sets the Deleted Flag to YES
UPDATE AB_Abstract 
SET IsDeleted = 1, LinkID = null,
    --NP - 00125
    IsCorrected = (case when IsSubmited = 1 then 2 else IsCorrected end),
    IsCorrectLevel1 = (case when IsSubmitLevel1 = 1 and caretype = 5 and admitdate > '2009/03/31' then 2 else IsCorrectLevel1 end)
WHERE AbstractID = @AbstractID
--NP - 00125 move this part together with deletion
-- Now set Correction to pending if it's been submitted.
--UPDATE AB_Abstract 
--SET IsCorrected = 2 
--WHERE AbstractID = @AbstractID
--AND IsSubmited = 1



--10489 Hong added temp
if @CareType = 5 and @LinkID > 0
begin
    if @LinkID = @AbstractID
    begin
        UPDATE AB_Abstract 
        SET IsDeleted = 1, LinkID = null, 
            IsCorrected = (case when IsSubmited = 1 and IsDeleted <> 1 then 2 else IsCorrected end)
        WHERE LinkID = @AbstractID 
    end
    else
    begin
    
        select @count = count(*)
        from AB_Abstract 
        where LinkID = @LinkID and IsDeleted <> 1

        if @count = 1 
            UPDATE AB_Abstract 
            SET LinkID = null, 
                IsCorrected = (case when IsSubmited = 1 then 2 else IsCorrected end)
            WHERE AbstractID = @LinkID
    end
end




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE PROCEDURE [E_AB_Main]
	@AbstractID int
AS 

-- Sets the Deleted Flag to YES
	UPDATE AB_Main SET IsDeleted = 1 WHERE UniversalID = @AbstractID

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE     PROCEDURE [E_CC_RecordInfo] 
	(@AbstractID    [int],
        -- @LinkID 	[int],
	 @AppID 	[int],    --675: Disease 676 : NDFP
	 @Coder 	[int])
AS 

declare @HID as int --NP-00025

  select @HID = HospitalID from U_Users where Code = @Coder --NP-00025

  update [CC_RecordInfo ] set [IsDeleted] = 1 where ([AbstractID] = @AbstractID)
  
  --Add to the Update History
  insert into CC_UpdateHistory (AbstractID, HospitalID, Coder, Updated, UpdateType)  --NP-00025
  select AbstractID, @HID, @Coder, GetDate(), 'Saved'  from [CC_RecordInfo] where ([AbstractID] = @AbstractID )
    
  -- Now set Correction to pending if it's been submitted.
  update [CC_RecordInfo] set [IsCorrected] = 2 where ([AbstractID] = @AbstractID and [IsSubmited] = 1)

  if @AppID = 675 -- Disease
  begin 
     --Update AB_Main
        update AB_Main set IsDeleted = 1 
	where abstractid in (select AbstractID from [CC_RecordInfo] where ([AbstractID] = @AbstractID) and AppType = 8)

         ------------   Update NDFP associated ----------
         Update  CC_RecordInfo   set [IsDeleted] = 1 where ([AbstractID] = 
	 (select CC_Demographic.AbstractID  from CC_Demographic where AppID = 676 and CC_Demographic.LinkID = @AbstractID ))

	 --Add to the Update History
  
	  insert INTO CC_UpdateHistory (AbstractID, HospitalID, Coder, Updated, UpdateType)  
	  select AbstractID, @HID, @Coder, GetDate(), 'Saved'  from CC_Demographic where (AppID = 676 and LinkID = @AbstractID ) 

	  -- Now set Correction to pending if it's been submitted.
	  update CC_RecordInfo set [IsCorrected] = 2 where ([IsSubmited] = 1 and [AbstractID] =
	 (select CC_Demographic.AbstractID  from CC_Demographic where AppID = 676 and CC_Demographic.LinkID = @AbstractID ))
    

  end



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
create PROCEDURE [E_CJRR_Abstract] 
    @RecordID int
AS 

-- Sets the Deleted Flag to YES
update CJRR_Abstract set 
	IsDeleted = 1 
	--IsCorrected = (case when IsSubmited = 1 then 2 else IsCorrected end)
where RecordID = @RecordID

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- Sets the Deleted Flag to YES
CREATE PROCEDURE [E_CM_CPI] (@PatientID [int])
AS 

UPDATE [CM_CPI] SET [IsDeleted] = 1 WHERE ([PatientID] = @PatientID)




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- Sets the Deleted Flag to YES
CREATE PROCEDURE [E_CR_Demographic] (@AbstractID [int])
AS 

UPDATE [CR_Demographic] 
SET [IsDeleted] = 1 
WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [E_CRS_Demographic] (@AbstractID [int])
AS 
--ED - 02717
UPDATE [CRS_Demographic] 
SET [IsDeleted] = 1, 
    IsCorrected = (case when isSubmited = 1 then 2 else 1 end),
    Y3 = 15771
WHERE ([AbstractID] = @AbstractID)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Sets the Deleted Flag to YES
CREATE    PROCEDURE [E_OMHRS_SecAA] 
	(@AbstractID 	[int],
	 @LinkID 	[int],
	 @Coder 	[int])
AS 

declare @LID as int 
declare @Z1 as int
declare @A1 as datetime

declare @HID as int --NP-00025
select @HID = HospitalID from U_Users where Code = @Coder

if @AbstractID <> 0 
begin
	--Add to the Update History
	insert into OMHRS_UpdateHistory (AbstractID, HospitalID, Coder, Updated, UpdateType) --PR-01953
	select AbstractID, @HID, @Coder, GetDate(), 'Deleted' from [OMHRS_SecAA] where [AbstractID] = @AbstractID	

	update  [OMHRS_SecAA] set  [X2] = 200303  where ([AbstractID] = @AbstractID)
	update  [OMHRS_RecInfo] set [IsDeleted] = 1  where ([AbstractID] = @AbstractID)
	--PR-00153	
	update [OMHRS_RecInfo] set  [IsCorrected] = 2  where [IsSubmited] = 1 and ([AbstractID] = @AbstractID)

    --12530
	select @Z1 = Z1, @A1 = A1, @LID = LinkID from OMHRS_SecAA AA inner join OMHRS_SecA A on AA.AbstractID = A.AbstractID
    where AA.AbstractID = @AbstractID
    
	if @Z1 = 200374 or @Z1 = 200376
	begin
		--Add to the Update History
		insert into OMHRS_UpdateHistory (AbstractID, HospitalID, Coder, Updated, UpdateType) --PR-01953
		select AbstractID, @HID, @Coder, GetDate(), 'Deleted' from [OMHRS_SecAA] where AbstractID in (select AA.AbstractID from OMHRS_SecAA AA inner join OMHRS_RecInfo R on AA.AbstractID =R.AbstractID inner join OMHRS_SecA A on AA.AbstractID = A.AbstractID  where [LinkID] = @LID and (isnull(A1, '') > isnull(@A1, '') or Z1 = 200375) and R.IsDeleted <> 1)

    	update [OMHRS_SecAA] set [X2] = 200303 where AbstractID in (select AA.AbstractID from OMHRS_SecAA AA inner join OMHRS_RecInfo R on AA.AbstractID =R.AbstractID inner join OMHRS_SecA A on AA.AbstractID = A.AbstractID  where [LinkID] = @LID and (isnull(A1, '') > isnull(@A1, '') or Z1 = 200375) and R.IsDeleted <> 1)        
		update [OMHRS_RecInfo] set  [IsDeleted] = 1  where AbstractID in (select AA.AbstractID from OMHRS_SecAA AA inner join OMHRS_RecInfo R on AA.AbstractID =R.AbstractID inner join OMHRS_SecA A on AA.AbstractID = A.AbstractID  where [LinkID] = @LID and (isnull(A1, '') > isnull(@A1, '') or Z1 = 200375) and R.IsDeleted <> 1)
	    --PR-00153
	    update [OMHRS_RecInfo] set  [IsCorrected] = 2  where [IsSubmited] = 1 and AbstractID in (select AA.AbstractID from OMHRS_SecAA AA inner join OMHRS_RecInfo R on AA.AbstractID =R.AbstractID inner join OMHRS_SecA A on AA.AbstractID = A.AbstractID  where [LinkID] = @LID and R.IsDeleted = 1 and (isnull(A1, '') > isnull(@A1, '') or Z1 = 200375))
	    
	end

    --PR - 04354
    update ab_main
    set IsDeleted = 1
    from ab_main 
        inner join (select AA.AbstractID from OMHRS_SecAA AA 
                        inner join OMHRS_RecInfo R on AA.AbstractID = R.AbstractID 
                        inner join OMHRS_SecA A on AA.AbstractID = A.AbstractID 
                    where (AA.AbstractID = @AbstractID) or ([LinkID] = @LID and R.IsDeleted in (1, 3) and (isnull(A1, '') > isnull(@A1, '') or Z1 = 200375))) Del on ab_main.abstractID = Del.AbstractID
    where ab_main.AppType = 7
end

else
begin
	--Add to the Update History
	insert into OMHRS_UpdateHistory (AbstractID, HospitalID, Coder, Updated, UpdateType) --PR-01953
	select AbstractID, @HID, @Coder, GetDate(), 'Deleted' from [OMHRS_SecAA] where [LinkID] = @LinkID	

	update  [OMHRS_SecAA] set  [X2] = 200303  where [LinkID] = @LinkID
	update  [OMHRS_RecInfo] set  [IsDeleted] = 1  where [AbstractID] in (select AbstractID from OMHRS_SecAA where  [LinkID] = @LinkID)
	--PR-00153
	update  [OMHRS_RecInfo] set  [IsCorrected] = 2  where [IsSubmited] = 1 and [AbstractID] in (select AbstractID from OMHRS_SecAA where  [LinkID] = @LinkID)	

    --PR - 04354
    update ab_main
    set IsDeleted = 1
    from ab_main 
        inner join (select AA.AbstractID from OMHRS_SecAA AA where [LinkID] = @LinkID) Del on ab_main.abstractID = Del.AbstractID
    where ab_main.AppType = 7

end



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Sets the Deleted Flag to YES
CREATE    PROCEDURE [E_RH_ClientInfo] 
	(@AbstractID    [int],
     @LinkID 	    [int],
	 @AssessType 	[int],
	 @Coder 	    [int])
AS 

declare @HID as int --NP-00025
select @HID = HospitalID from U_Users where Code = @Coder --NP-00025

if @AssessType = 134
begin
    update [RH_ClientInfo] set [IsDeleted] = 1 where ([LinkID] = @LinkID and AssessmentType >= @AssessType)
    
    --Update AB_Main
    update AB_Main set IsDeleted = 1
    where abstractid in (select AbstractID from [RH_ClientInfo] where ([LinkID] = @LinkID and AssessmentType >= @AssessType)) and AppType = 3
    
    --Add to the Update History
    insert into RH_UpdateHistory (AbstractID, HospitalID, Coder, Updated, UpdateType)  --NP-00025
    select AbstractID, @HID, @Coder, GetDate(), 'Saved'  from [RH_ClientInfo] where ([LinkID] = @LinkID and AssessmentType >= @AssessType)
    
    -- Now set Correction to pending if it's been submitted.
    update [RH_ClientInfo] set [IsCorrected] = 2 where ([LinkID] = @LinkID and AssessmentType >= @AssessType and [IsSubmited] = 1)
end

else if @AssessType = 135 or @AssessType = 136
begin
    update [RH_ClientInfo] set [IsDeleted] = 1 where AssessmentType <> 156 and ([LinkID] = @LinkID and AssessmentType >= @AssessType)
    
    --Update AB_Main
    update AB_Main set IsDeleted = 1
    where abstractid in (select AbstractID from [RH_ClientInfo] where AssessmentType <> 156 and ([LinkID] = @LinkID and AssessmentType >= @AssessType)) and AppType = 3
    
    --Add to the Update History
    insert into RH_UpdateHistory (AbstractID, HospitalID, Coder, Updated, UpdateType) --NP-00025
    select AbstractID, @HID, @Coder, GetDate(), 'Saved'  from [RH_ClientInfo] where AssessmentType <> 156 and ([LinkID] = @LinkID and AssessmentType >= @AssessType)
    
    -- Now set Correction to pending if it's been submitted.
    update [RH_ClientInfo] set [IsCorrected] = 2 where AssessmentType <> 156 and ([LinkID] = @LinkID and AssessmentType >= @AssessType and [IsSubmited] = 1)
end

else if @AssessType in (156, 157)   --PR - 05062 enable post discharge
begin
    update [RH_ClientInfo] set [IsDeleted] = 1 where [AbstractID] = @AbstractID    
    --Update AB_Main
    update AB_Main set IsDeleted = 1 where AbstractID = @AbstractID and AppType = 3
    
    --Add to the Update History
    insert into RH_UpdateHistory (AbstractID, HospitalID, Coder, Updated, UpdateType) values (@AbstractID, @HID, @Coder, GetDate(), 'Saved') --NP-00025
end
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- Sets the Deleted Flag to YES
CREATE PROCEDURE [E_ROI_Main] (@ROIID [int])
AS 
	UPDATE dbo.ROI_Main SET IsDeleted = 1 WHERE ([ROIID] = @ROIID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- Sets the Deleted Flag to YES
CREATE PROCEDURE [E_Transcription] (@TransID [int])
AS 
UPDATE [TR_Main] SET [IsDeleted] = 1 WHERE ([TranscriptionID] = @TransID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE  PROCEDURE [F_BarcodeChart]
	@BarC1 as varchar(20),
	@BarC2 as varchar(20),
	@BarC3 as varchar(20)
AS
	Set NoCount ON
	Declare @SQL as VarChar(1000)

	Create Table #BCTemp
	(AID int NULL, Orphan int NULL)

	set @SQL = ''

	if isnull(@BarC1, '') <> ''
		set @SQL = 'chartnumber = ''' + @BarC1 + ''' '
	if isnull(@BarC2, '') <> ''
		set @SQL = @SQL + 'and encounternumber = ''' + @BarC2 + ''' '
	if isnull(@BarC3, '') <> ''
		set @SQL = @SQL + 'and admitdate = ''' + @BarC3 + ''' '

	set @SQL = 'insert into #BCTemp Select abstractid, ''0'' as Orphan from ab_abstract where ' + @SQL
	exec(@SQL)

	if @@ROWCount = 0
		set @SQL = 'Select isnull(max(imagelink), ''0'') + 1, ''1'' as Orphan from DAS_Orphen'
	else
		set @SQL = 'Select * From #BCTemp'
	Set NoCount off
	exec(@SQL)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE Procedure [F_Fetch_HIM_Location]
    @Date   as datetime = null,
    @HospID as int = 0
as 
    select L.code, L.DisplayCode + ' -- ' + L.UserDescription
    from LoanLU_Location L
        inner join LU_YesNoSystem Y on L.InHospital = Y.Code
    where isnull(@Date, getdate()) between L.ValidFrom and L.ValidTo
        and Y.CIHIValue = '1'
        and (isnull(L.HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else ISNULL(L.HospitalID, 0) end)
    order by L.DisplayCode + ' -- ' + L.UserDescription


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create Procedure [F_GetDictationDeficiencyCode]
    @DischargeDate datetime
as
select D.Code, D.DisplayCode as [Deficiency Code], D.UserDescription as [Deficiency Description]
from DefLU_DeficiencyCode D
    inner join DefLU_DeficiencyType T on D.AssociationID = T.Code
where D.DisplayCode = 'D' 
    and @DischargeDate between D.ValidFrom and D.ValidTo



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- Called by the Quick Search Form
CREATE          PROCEDURE [F_QuickSearch]
	@CareType 	[varchar](1),
	@SearchDate 	[varchar](10) = '',	
    	@AppID          [int],
	@UserID	        [int],
    	@HospID		[varchar](100) = '0'
AS 

set nocount on

declare @SQL as nVarChar(4000)
declare @Select as nvarchar(2500)
declare @WDate as nvarchar(500)
declare @WCare as nVarChar(500)
declare @Order as nVarChar(500)

declare @SearchAudit as int

declare @ShowVip as NVarChar(1)
declare @SearchPrefix as nvarchar(500)

declare @TmpTable as nvarchar(100)

if @HospID = '0'
	select top 1 @SearchAudit = EnableSearchAudit from H_HospitalProfile 
else	
	select top 1 @SearchAudit = EnableSearchAudit from H_HospitalProfile where isnull(Code, 0) = @HospID

select @SearchPrefix = isnull(SearchChartPrefix, ''), @ShowVip = isnull(showvip, 0) from u_users where code = @UserID
if @SearchPrefix <> '' set @SearchPrefix = '  (ChartNumber like ''' + @SearchPrefix + '%'' or ChartNumber like ''Z' + @SearchPrefix + '%'') and '

set @TmpTable = '##QSearchTmp' + replace(convert(nvarchar(100), getdate(), 114), ':', '')

--Audit values searched on
insert into AU_Search Values (@AppID, @SearchDate, @UserID, GetDate(), 'Quick Search')

set @Select = 'SELECT AbstractID as [ ], ChartNumber as [C], 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Abstract.HospitalID, 0)) as [Hosp ID],
		convert(varchar(10), AdmitDate, 111) as [Admit Date], 
		convert(varchar(10), DischargeDate, 111) as [Discharge Date], 
		replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') as [Chart #], 
		EncounterNumber as [Encounter #], 
		IsNull(AB_Abstract.LastName, '''') + '', '' + IsNull(AB_Abstract.FirstName, '''') + '' '' + IsNull(AB_Abstract.MiddleName, '''') As [Full Name],		convert (varchar(5), AdmitTime, 14) as [Admit Time], 
		convert (varchar(5), DischargeTime, 14) as [Discharge Time], 
		IsNull(dbo.U_Users.DisplayCode, '''') AS Coder, dbo.LU_AbstractStatus.DisplayCode AS Status
        into ' + @TmpTable + '
		from dbo.AB_Abstract left outer join
		dbo.U_Users on dbo.AB_Abstract.CoderNumber = dbo.U_Users.Code left outer join
		dbo.LU_AbstractStatus on dbo.AB_Abstract.IsCompleted = dbo.LU_AbstractStatus.Code where ' + @SearchPrefix 

if @CareType = '0' -- CCR
begin
    set @WDate = 'AdmitDate = Convert(DateTime, ''' + @SearchDate + ''') and dischargedate is null '
    set @WCare = ' and CareType = 1 ' 
    set @Order = ' order by AdmitDate, AdmitTime '

	if right(@SearchDate, 2) = '00' set @WDate = '(AdmitDate >= Convert(DateTime, ''' + left(@SearchDate, 8) + '01'') and AdmitDate < dateadd(M, 1, Convert(DateTime, ''' + left(@SearchDate, 8) + '01''))) and dischargedate is null '
end 

else if @CareType in ('1','2') -- Inpatient, SDS
begin
    set @WDate = 'DischargeDate = Convert(DateTime, ''' + @SearchDate + ''') '
    set @WCare = ' and caretype = '+ @CareType 
    set @Order = ' order by DischargeDate, DischargeTime '

	if right(@SearchDate, 2) = '00' set @WDate = '(DischargeDate >= Convert(DateTime, ''' + left(@SearchDate, 8) + '01'') and DischargeDate < dateadd(M, 1, Convert(DateTime, ''' + left(@SearchDate, 8) + '01''))) '
end 

else if @CareType = '5' -- Amcare
begin
    set @WDate = 'AdmitDate = Convert(DateTime, ''' + @SearchDate + ''') '
    set @WCare = ' and caretype = 5 '
    set @Order = ' order by AdmitDate, AdmitTime '
	
    if right(@SearchDate, 2) = '00' set @WDate = '(AdmitDate >= Convert(DateTime, ''' + left(@SearchDate, 8) + '01'') and AdmitDate < dateadd(M, 1, Convert(DateTime, ''' + left(@SearchDate, 8) + '01''))) '
end 

----------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------

set @SQL = @Select + @WDate + @WCare + ' and (isnull(AB_Abstract.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(AB_Abstract.HospitalID, 0) end) ' + @Order
--print @SQL
exec sp_executesql @SQL

if @ShowVip = '2'
begin
	set @SQL = 'delete ' + @TmpTable + ' where [C] in (select ChartNumber from CM_CPI where isnull(secret, 0) = 1 and ChartNumber in (select [C] from ' + @TmpTable + '))'
	exec(@SQL)
end

if @SearchAudit = 1
begin
	declare @CurDTime as Datetime
	set @CurDTime = getdate()
	set @SQL = 'insert into AU_SearchDetail select ' + cast(@Appid as varchar(10)) + ', [ ], ''' + Cast(@UserID as varchar(10)) + ''', ''' + convert(varchar(30), @CurDTime, 120) + ''' as Field2 from ' + @TmpTable
	exec(@SQL)
end

set nocount off

set @SQL = 'select * From ' + @TmpTable
exec(@SQL)
set @SQL = 'drop table ' + @TmpTable
exec(@SQL)


return 0




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec F_SearchAbstract '5', 'T', '', 401, 614, 'x', 'x000000000', 100000, 1, 100000, 0, ''

--exec F_SearchAbstract '1', 'T', '', 201, 614, '333', ' 000000333', 4, 0, 4, '0', ''
-- Called by the Abstract Search Form
CREATE   PROCEDURE [F_SearchAbstract]
	@CareType 	[VarChar](3),
	@ICDType1 	[VarChar](1),
	@ICDType2 	[VarChar](1) = '',
	@AppID 	    [int], 
	@FKey 		[int],
	@SearchString 	[VarChar](50) = '',
	@SearchString2 [VarChar](50) = '',
	@UserID 	[int] = 1,  -- This is actually the RoleID
	@Exact 	[int] = 0,
	@LogID	[int] = 0,	--This is the UserID that Logged In
	@HospID	[varchar](100) = '0', 
	@ExtraSearch 	[varchar](1000) = ''
AS 
-- NP-00025 - 		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Abstract.HospitalID, 0)) as [Hosp ID],

Set nocount on
	DECLARE @SQL    NVarChar(4000)
   	DECLARE @select NVarChar(2500)
    DECLARE @from   NVarChar(500)
   	DECLARE @where  NVarChar(500)
    DECLARE @order  NVarChar(500)

	DECLARE @DataType    int
	DECLARE @LookupTable NVarChar(50)
	DECLARE @FieldName   NVarChar(50)
	DECLARE @NameSplit   int
	DECLARE @FieldDesc   NVarChar(150)
	DECLARE @Temp        datetime
	DECLARE @DBTableName NVarChar(50)
	Declare @FieldDT     NVarChar(20)
	DECLARE @CCRSearch   NVarChar(50)

	SELECT @DataType    = DataType FROM U_UsersFields  WHERE AppID = @AppID AND FieldID = @FKey AND UserID = @UserID
	SELECT @LookupTable = LookUpTable FROM U_UsersFields  WHERE AppID = @AppID AND FieldID = @FKey AND UserID = @UserID
	SELECT @FieldName   = SystemName FROM U_Fields  WHERE FieldID = @FKey
	SELECT @FieldDesc   =  Header_User FROM U_UsersFields  WHERE AppID = @AppID AND FieldID = @FKey AND UserID = @UserID
	SET @FieldDesc = replace(@FieldDesc, '[', '')
	SET @FieldDesc = replace(@FieldDesc, ']', '')

	--CHANGING THIS TO USE User Header, the In House Desc is unreliable and can cause this whole procedure to fail
	--SELECT @FieldDesc   = InHouseDesc FROM U_Fields  WHERE FieldID = @FKey
	SELECT top 1 @DBTableName = Table_Name from information_schema.columns Where Column_Name = @FieldName and Table_Name like 'AB_%' order by Table_Name
	--Audit values searched on
	insert into AU_Search Values (@AppID, @SearchString, @LogID, GetDate(), @FieldDesc)

--Chart Audits, Prefixs, VIP and Top X parameters
	Declare @SearchPrefix as NVarChar(1000)
	Declare @SearchPrefix_Org as NVarChar(100) --PR - 05450
	Declare @ShowVip as NVarChar(1)
	Declare @TopX as NVarChar(3)
	Declare @SearchAudit as int
	Declare @SQLTopX as NVarChar(20)
	Declare @HospSearch as NVarChar(200)
	Select @SearchPrefix = isnull(searchchartprefix, ''), @ShowVip = isnull(showvip, 0) from u_users where code = @UserID
	set @SearchPrefix_Org = @SearchPrefix   --PR - 05450
	If @SearchPrefix <> ''
	    --2.x-0010 Allow still birth prefix, X, Y, Z
		--Set @SearchPrefix = ' and (Chartnumber like ''' + @SearchPrefix + '%'' or Chartnumber like ''Z' + @SearchPrefix + '%'') '
		Set @SearchPrefix = ' and (Chartnumber like ''' + @SearchPrefix + '%'' or Chartnumber like ''Z' + @SearchPrefix + '%'' or Chartnumber like ''Y' + @SearchPrefix + '%'' or Chartnumber like ''X' + @SearchPrefix + '%'') '
	If @HospID = '0'
		Select top 1 @TopX = isnull(TopSearch, '999'), @SearchAudit = EnableSearchAudit  FROM H_HospitalProfile 
	else	
		Select top 1 @TopX = isnull(TopSearch, '999'), @SearchAudit = EnableSearchAudit  FROM H_HospitalProfile where isnull(Code, 0) = @HospID

    --12294
-- 	If isnull(@HospID, '') = '0'
-- 		Set @HospSearch = ' and ISNULL(HospitalID, 0) = 0 '
-- 	else	
-- 		Set @HospSearch = ' and ISNULL(HospitalID, 0) = ' + @HospID + ' '     
    set @HospSearch = ' and (isnull(AB_Abstract.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(AB_Abstract.HospitalID, 0) end) '

	Set @SQLTopX = 'Select top ' + @TopX + ' ' 
	SET @NameSplit = CHARINDEX(',', @SearchString) 
	Declare @TempTable as NVarChar(100)
	set @TempTable = '##SearchTmp' + replace(convert(nvarchar(100), getdate(), 114), ':', '')
    -- determine the Where Clause base on datatype
if (@DataType in (11, 12, 13))     -- if it is a date PR-01739
begin 
	--EN-00081
	if right(@SearchString, 5) = '00/00' 
		set @where = '(' + @FieldName + ' >= Convert(DateTime, ''' + left(@SearchString, 5) + '01/01'') and ' + @FieldName + ' <= convert(DateTime, ''' + left(@SearchString, 5) + '12/31'')) '

	else if right(@SearchString, 2) = '00' 
        	set @where = '(' + @FieldName + ' >= Convert(DateTime, ''' + left(@SearchString, 8) + '01'') and ' + @FieldName + ' < dateadd(M, 1, Convert(DateTime, ''' + left(@SearchString, 8) + '01''))) '

        Else if (isdate(@SearchString) = 0) 
		set @SearchString = '1950/01/01'

	If isnull(@where, '') = ''            set @where =  ' convert(nvarchar(10), ' + @FieldName + ', 111) = ''' + @SearchString + ''''
            --12626
	        --set @where = @FieldName + ' = Convert(DateTime, ''' + @SearchString + ''') '
end 

IF @AppID = 100 or @AppID = 200
	SET @CCRSearch = 'isnull(DischargeDate, '''') = '''' AND'
ELSE IF @AppID = 301 OR @AppID = 401
	SET @CCRSearch = ''
ELSE
	SET @CCRSearch = 'isnull(DischargeDate, '''') <> '''' AND'

--13507: Moved to top	
Set @SearchString = replace(@SearchString, '''', '''''')
Set @SearchString2 = replace(@SearchString2, '''', '''''')

--if @FieldName in ('EncounterNumber', 'ChartNumber', 'AdmitDate', 'DischargeDate', 'LastName')
--begin 

   if @FKey = 45006 -- TERMINAL DIGIT SORT
    begin
-- 	declare @TDigit as varchar(10)
-- 	declare @TDigitR as varchar(10)
-- 	declare @TDigitH as varchar(10)
-- 
-- 	select @TDigitR = TerminalDigit from H_RegionProfile
-- 	if @HospID = '0' 
-- 		select top 1 @TDigitH = TerminalDigit from H_HospitalProfile 
-- 	else
-- 		select top 1 @TDigitH = TerminalDigit from H_HospitalProfile where HospitalID = @HospID
-- 	
-- 	set @TDigit = @TDigitR
-- 	if len(@TDigitH) <> 0 and isnull(@TDigitH, '0') <> '0' set @TDigit = @TDigitH
-- 	--set @TDigit = '926315'
-- 	
-- 	declare @Pos1 as varchar(1)
-- 	declare @Len1 as varchar(1)
-- 	declare @Pos2 as varchar(1)
-- 	declare @Len2 as varchar(1)
-- 	declare @Pos3 as varchar(1)
-- 	declare @Len3 as varchar(1)
-- 	declare @Pos4 as varchar(1)
-- 	declare @Len4 as varchar(1)
-- 	declare @Pos5 as varchar(1)
-- 	declare @Len5 as varchar(1)
-- 
-- 	declare @OrdT as varchar(400)
-- 
-- 	if isnumeric(substring(@TDigit, 1, 1)) = 1 
-- 		set @Pos1 = substring(@TDigit, 1, 1)
-- 	if isnumeric(substring(@TDigit, 2, 1)) = 1 
-- 		set @Len1 = substring(@TDigit, 2, 1)
-- 	if isnumeric(substring(@TDigit, 3, 1)) = 1 
-- 		set @Pos2 = substring(@TDigit, 3, 1)
-- 	if isnumeric(substring(@TDigit, 4, 1)) = 1 
-- 		set @Len2 = substring(@TDigit, 4, 1)
-- 	if isnumeric(substring(@TDigit, 5, 1)) = 1 
-- 		set @Pos3 = substring(@TDigit, 5, 1)
-- 	if isnumeric(substring(@TDigit, 6, 1)) = 1 
-- 		set @Len3 = substring(@TDigit, 6, 1)
-- 	if isnumeric(substring(@TDigit, 7, 1)) = 1 
-- 		set @Pos4 = substring(@TDigit, 7, 1)
-- 	if isnumeric(substring(@TDigit, 8, 1)) = 1 
-- 		set @Len4 = substring(@TDigit, 8, 1)
-- 	if isnumeric(substring(@TDigit, 9, 1)) = 1 
-- 		set @Pos5 = substring(@TDigit, 9, 1)
-- 	if isnumeric(substring(@TDigit, 10, 1)) = 1 
-- 		set @Len5 = substring(@TDigit, 10, 1)
-- 
-- 	if len(@Pos1) <> 0 and len(@Len1) <> 0
-- 		set @OrdT = ' substring(replace(space(10-len([Chart #])) + [Chart #], '' '', ''0''), ' + @Pos1 + ', ' + @Len1 + '), '
-- 		
-- 	if len(@Pos2) <> 0 and len(@Len2) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len([Chart #])) + [Chart #], '' '', ''0''), ' + @Pos2 + ', ' + @Len2 + '), '
-- 
-- 	if len(@Pos3) <> 0 and len(@Len3) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len([Chart #])) + [Chart #], '' '', ''0''), ' + @Pos3 + ', ' + @Len3 + '), '
-- 
-- 	if len(@Pos4) <> 0 and len(@Len4) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len([Chart #])) + [Chart #], '' '', ''0''), ' + @Pos4 + ', ' + @Len4 + '), '
-- 
-- 	if len(@Pos5) <> 0 and len(@Len5) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len([Chart #])) + [Chart #], '' '', ''0''), ' + @Pos5 + ', ' + @Len5 + '), '
-- 
-- -- ORDER BY IS DEFINED NEAR THE BOTTOM OF THE SP
-- -- 	if len(@Pos1) <> 0 and len(@Len1) <> 0
-- -- 		set @OrdT = ' substring(replace(space(10-len([ChartNumber])) + [ChartNumber], '' '', ''0''), ' + @Pos1 + ', ' + @Len1 + '), '
-- -- 		
-- -- 	if len(@Pos2) <> 0 and len(@Len2) <> 0
-- -- 		set @OrdT = @OrdT + ' substring(replace(space(10-len([ChartNumber])) + [ChartNumber], '' '', ''0''), ' + @Pos2 + ', ' + @Len2 + '), '
-- -- 
-- -- 	if len(@Pos3) <> 0 and len(@Len3) <> 0
-- -- 		set @OrdT = @OrdT + ' substring(replace(space(10-len([ChartNumber])) + [ChartNumber], '' '', ''0''), ' + @Pos3 + ', ' + @Len3 + '), '
-- -- 
-- -- 	if len(@Pos4) <> 0 and len(@Len4) <> 0
-- -- 		set @OrdT = @OrdT + ' substring(replace(space(10-len([ChartNumber])) + [ChartNumber], '' '', ''0''), ' + @Pos4 + ', ' + @Len4 + '), '
-- -- 
-- -- 	if len(@Pos5) <> 0 and len(@Len5) <> 0
-- -- 		set @OrdT = @OrdT + ' substring(replace(space(10-len([ChartNumber])) + [ChartNumber], '' '', ''0''), ' + @Pos5 + ', ' + @Len5 + '), '
-- 
-- 	if len(@OrdT) <> 0 
-- 		set @OrdT = left(@OrdT, len(@OrdT) - 1)
-- 
-- --		replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') as [Chart #], 
-- --		replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') as [ChartNumber], 
-- 	set @SQL = @SQLTopX + 'AbstractID as [ ], 
-- 		(select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = AB_Abstract.ChartNumber) as [Deceased],
-- 		replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') as [Chart #], 
--     		EncounterNumber as [Encounter #], 
--     		replace(space(3-len(EncounterSequence)) + convert(nvarchar(3), EncounterSequence), '' '', ''0'')  as [Seq], 	
-- 		IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''') + '' '' + IsNull(MiddleName, '''') As [Full Name],
-- 		Convert(NVarChar(10), AdmitDate, 111) as [Admit Date], 
-- 		CONVERT (NVarChar(5), AdmitTime, 14) as [Admit Time] ,
-- 		Convert(NVarChar(10), DischargeDate, 111) as [Discharge Date] 							
-- 		into ' + @TempTable + ' FROM AB_Abstract WHERE ' + @CCRSearch + ' (ChartNumber Like ''' + @SearchString + '%'' OR ChartNumber LIKE ''' + @SearchString2 +'%'')
-- 		AND CareType = ' + @CareType + '-- 
-- 		AND (ICDType = ''' + @ICDType1 + '''
-- 			OR ICDType = ''' + @ICDType2 + ''')
-- 		AND IsDeleted = 2' + @SearchPrefix + @HospSearch + @ExtraSearch 
-- 
-- 	set @order = ''
-- 	if len(@OrdT) <> 0 
-- 	        set @order = ' order by ' + @OrdT
-- 
-- 	-- ORDER BY IS DEFINED NEAR THE BOTTOM OF THE SP
-- 	--set @sql = @sql + @order
-- 	--print @sql 
    --PR - 04434 set the search item to be the first visible item. Move Terminal chart from 3 to 1
--		(select TerminalChart from CM_Terminal where PatientID = (select PatientID from CM_CPI where ChartNumber = AB_Abstract.ChartNumber)) as [Terminal #], 
	set @SQL = @SQLTopX + 'AbstractID , 
		(select TerminalChart from CM_Terminal where PatientID = (select PatientID from CM_CPI where ChartNumber = AB_Abstract.ChartNumber)) as [SearchItem#], 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Abstract.HospitalID, 0)) as [Hosp ID],
		(select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = AB_Abstract.ChartNumber) as [Deceased],
		replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') as [Chart #], 
   		EncounterNumber as [Encounter #], 
   		(case when EncounterSequence > 999 then cast(EncounterSequence as varchar(50)) else replace(space(3-len(EncounterSequence)) + convert(nvarchar(3), EncounterSequence), '' '', ''0'') end)  as [Seq], 	
		IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''') + '' '' + IsNull(MiddleName, '''') As [Full Name],
		Convert(NVarChar(10), AdmitDate, 111) as [Admit Date], 
		CONVERT (NVarChar(5), AdmitTime, 14) as [Admit Time] ,
		Convert(NVarChar(10), DischargeDate, 111) as [Discharge Date], 		
		(select top 1 DisplayCode from dbo.LU_AbstractStatus where Code = (case when isnull(AB_Abstract.IsCompleted, 0) = 0 then 1 else AB_Abstract.IsCompleted end) ) as [Status],  --ED - 01604
		(select top 1 DisplayCode from dbo.LU_AbstractStatus where Code = (case when isnull(AB_Abstract.IsCompleteLevel1, 0) = 0 then 1 else AB_Abstract.IsCompleteLevel1 end) ) as [Status (L1/2)]  --ED-02065
		into ' + @TempTable + ' FROM AB_Abstract WHERE ' + @CCRSearch 
		+ ' (ChartNumber in (select CM_CPI.ChartNumber from CM_CPI where PatientID in (select PatientID from CM_Terminal where TerminalChart Like ''' + @SearchString + '%'' or MaskTerminal Like ''' + @SearchString + '%'')))
		AND CareType = ' + @CareType + '
		AND (ICDType = ''' + @ICDType1 + '''
			OR ICDType = ''' + @ICDType2 + ''')
		AND IsDeleted = 2' + @SearchPrefix + @HospSearch + @ExtraSearch 

	set @order = ' order by [Hosp ID], [Terminal #]'
    set @fielddesc = 'Terminal #'
    --print @sql
        exec sp_executesql @sql 
    end
   	
   else IF @FieldName = 'EncounterNumber'     	
    begin
        set @SQL = @SQLTopX + 'AbstractID , 
   		EncounterNumber as [SearchItem#], 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Abstract.HospitalID, 0)) as [Hosp ID],
		(select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = AB_Abstract.ChartNumber) as [Deceased],
    		EncounterNumber as [Encounter #], 
    		(case when EncounterSequence > 999 then cast(EncounterSequence as varchar(50)) else replace(space(3-len(EncounterSequence)) + convert(nvarchar(3), EncounterSequence), '' '', ''0'') end) as [Seq], 
    		replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')  as [Chart #], 
    		IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''') + '' '' + IsNull(MiddleName, '''') As [Full Name], 
    		Convert(NVarChar(10), AdmitDate, 111) as [Admit Date], 
    		CONVERT (NVarChar(5), AdmitTime, 14) as [Admit Time] ,
    		Convert(NVarChar(10), DischargeDate, 111) as [Discharge Date] , 		
		(select top 1 DisplayCode from dbo.LU_AbstractStatus where Code = (case when isnull(AB_Abstract.IsCompleted, 0) = 0 then 1 else AB_Abstract.IsCompleted end) ) as [Status],  --ED - 01604
		(select top 1 DisplayCode from dbo.LU_AbstractStatus where Code = (case when isnull(AB_Abstract.IsCompleteLevel1, 0) = 0 then 1 else AB_Abstract.IsCompleteLevel1 end) ) as [Status (L1/2)]  --ED-02065
    		into ' + @TempTable + ' FROM dbo.AB_Abstract WHERE ' + @CCRSearch + ' EncounterNumber Like ''' + @SearchString + '%''
    		AND CareType = ' + @CareType + '
    		AND (ICDType = ''' + @ICDType1 + '''
    			OR ICDType = ''' + @ICDType2 + ''')
    		AND IsDeleted = 2' + @SearchPrefix + '
		AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end) ' 
		+ @ExtraSearch + ' ORDER BY [Hosp ID], [Encounter #] DESC'

        set @order = ' ORDER BY [Hosp ID], [Encounter #] DESC'
        exec sp_executesql @sql 
    end

    else if @FieldName = 'EncounterSequence'     	
    begin
        if len(ltrim(rtrim(@SearchString))) = 0 set @SearchString = '0'
        set @SQL = @SQLTopX + 'AbstractID , 
       		(case when EncounterSequence > 999 then cast(EncounterSequence as varchar(50)) else replace(space(3-len(EncounterSequence)) + convert(nvarchar(3), EncounterSequence), '' '', ''0'') end) as [SearchItem#], 
	    	(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Abstract.HospitalID, 0)) as [Hosp ID],
		    (select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = AB_Abstract.ChartNumber) as [Deceased],
    		replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')  as [Chart #], 
    		EncounterNumber as [Encounter #], 
    		(case when EncounterSequence > 999 then cast(EncounterSequence as varchar(50)) else replace(space(3-len(EncounterSequence)) + convert(nvarchar(3), EncounterSequence), '' '', ''0'') end) as [Seq], 
    		IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''') + '' '' + IsNull(MiddleName, '''') As [Full Name], 
    		Convert(NVarChar(10), AdmitDate, 111) as [Admit Date], 
    		CONVERT (NVarChar(5), AdmitTime, 14) as [Admit Time] ,
    		Convert(NVarChar(10), DischargeDate, 111) as [Discharge Date], 		
		(select top 1 DisplayCode from dbo.LU_AbstractStatus where Code = (case when isnull(AB_Abstract.IsCompleted, 0) = 0 then 1 else AB_Abstract.IsCompleted end) ) as [Status],  --ED - 01604
		(select top 1 DisplayCode from dbo.LU_AbstractStatus where Code = (case when isnull(AB_Abstract.IsCompleteLevel1, 0) = 0 then 1 else AB_Abstract.IsCompleteLevel1 end) ) as [Status (L1/2)]  --ED-02065
    		into ' + @TempTable + ' FROM dbo.AB_Abstract WHERE ' + @CCRSearch + ' isnull(EncounterSequence, 0) = ' + @SearchString + '
    		AND CareType = ' + @CareType + '
    		AND (ICDType = ''' + @ICDType1 + '''
    			OR ICDType = ''' + @ICDType2 + ''')
    		AND IsDeleted = 2' + @SearchPrefix + '
		AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end) ' 
		+ @ExtraSearch + ' ORDER BY [Hosp ID], [Seq] DESC'

        set @order = ' ORDER BY [Hosp ID], [Seq] DESC'
        exec sp_executesql @sql
    end

    ELSE IF @FieldName = 'ChartNumber' 
    begin
        --PR - 05450
        if len(@SearchPrefix_Org) > 0 and len(isnull(@SearchString, '')) > 0
        begin
            --2.x-0010 Allow client search chart with X, Y, Z 
            if left(@SearchString, 1) in ('X', 'Y', 'Z')
            begin
                set @SearchString = substring(@SearchString, 2, 10)
            end

            if charindex(@SearchPrefix_Org, @SearchString) <> 1 
                set @SearchString = @SearchPrefix_Org + @SearchString
        end
	IF @Exact = 0 
		set @SQL = @SQLTopX + 'AbstractID , 
            ChartNumber as [SearchItem#], 
			(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Abstract.HospitalID, 0)) as [Hosp ID],
			(select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = AB_Abstract.ChartNumber) as [Deceased],
			replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') as [Chart #], 
	    		EncounterNumber as [Encounter #], 
	    	(case when EncounterSequence > 999 then cast(EncounterSequence as varchar(50)) else replace(space(3-len(EncounterSequence)) + convert(nvarchar(3), EncounterSequence), '' '', ''0'') end) as [Seq], 	
			IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''') + '' '' + IsNull(MiddleName, '''') As [Full Name],
			Convert(NVarChar(10), AdmitDate, 111) as [Admit Date], 
			CONVERT (NVarChar(5), AdmitTime, 14) as [Admit Time] ,
			Convert(NVarChar(10), DischargeDate, 111) as [Discharge Date], 		
			(select top 1 DisplayCode from dbo.LU_AbstractStatus where Code = (case when isnull(AB_Abstract.IsCompleted, 0) = 0 then 1 else AB_Abstract.IsCompleted end) ) as [Status],  --ED - 01604
			(select top 1 DisplayCode from dbo.LU_AbstractStatus where Code = (case when isnull(AB_Abstract.IsCompleteLevel1, 0) = 0 then 1 else AB_Abstract.IsCompleteLevel1 end) ) as [Status (L1/2)]  --ED-02065
			into ' + @TempTable + ' FROM dbo.AB_Abstract WHERE ' + @CCRSearch + 
			' (ChartNumber Like ''' + @SearchString + '%'' OR ChartNumber Like ''X' + @SearchString + '%'' or ChartNumber Like ''Y' + @SearchString + '%'' OR ChartNumber Like ''Z' + @SearchString + '%'' OR ChartNumber LIKE ''' + @SearchString2 +'%'')
			AND CareType = ' + @CareType + '
			AND (ICDType = ''' + @ICDType1 + '''
				OR ICDType = ''' + @ICDType2 + ''')
			AND IsDeleted = 2' + @SearchPrefix + @HospSearch +
			+ @ExtraSearch + ' ORDER BY [Hosp ID], [Chart #] Desc, [Admit Date] DESC'
	ELSE
		set @SQL = @SQLTopX + 'AbstractID , 
            ChartNumber as [SearchItem#], 
			(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Abstract.HospitalID, 0)) as [Hosp ID],
			(select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = AB_Abstract.ChartNumber) as [Deceased],
			replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') as [Chart #], 
    		EncounterNumber as [Encounter #], 
    		(case when EncounterSequence > 999 then cast(EncounterSequence as varchar(50)) else replace(space(3-len(EncounterSequence)) + convert(nvarchar(3), EncounterSequence), '' '', ''0'') end)  as [Seq], 
			IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''') + '' '' + IsNull(MiddleName, '''') As [Full Name],
			Convert(NVarChar(10), AdmitDate, 111) as [Admit Date], 
			CONVERT (NVarChar(5), AdmitTime, 14) as [Admit Time] ,
			Convert(NVarChar(10), DischargeDate, 111) as [Discharge Date], 		
			(select top 1 DisplayCode from dbo.LU_AbstractStatus where Code = (case when isnull(AB_Abstract.IsCompleted, 0) = 0 then 1 else AB_Abstract.IsCompleted end) ) as [Status],  --ED - 01604
			(select top 1 DisplayCode from dbo.LU_AbstractStatus where Code = (case when isnull(AB_Abstract.IsCompleteLevel1, 0) = 0 then 1 else AB_Abstract.IsCompleteLevel1 end) ) as [Status (L1/2)]  --ED-02065
			into ' + @TempTable + ' FROM dbo.AB_Abstract WHERE ' + @CCRSearch + ' (ChartNumber in (''' + @SearchString + ''', ''X' + @SearchString + ''', ''Y' + @SearchString + ''', ''Z' + @SearchString + ''') OR ChartNumber = ''' + @SearchString2 +''')
			AND CareType = ' + @CareType + '
			AND (ICDType = ''' + @ICDType1 + '''
				OR ICDType = ''' + @ICDType2 + ''')
			AND IsDeleted = 2' + @SearchPrefix + @HospSearch +
			+ @ExtraSearch + ' ORDER BY [Hosp ID], [Chart #] Desc, [Admit Date] DESC'

        set @order = ' ORDER BY [Hosp ID], [Chart #] Desc, [Admit Date] DESC'	
	    --print @sql
        exec sp_executesql @sql
    end
    ELSE IF @FieldName = 'AdmitDate' 
    begin
		set @SQL = @SQLTopX + 'AbstractID, 
			Convert(NVarChar(10), AdmitDate, 111) as [SearchItem#], 
			(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Abstract.HospitalID, 0)) as [Hosp ID],
			(select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = AB_Abstract.ChartNumber) as [Deceased],
			replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') as [Chart #], 
    		EncounterNumber as [Encounter #], 
    		(case when EncounterSequence > 999 then cast(EncounterSequence as varchar(50)) else replace(space(3-len(EncounterSequence)) + convert(nvarchar(3), EncounterSequence), '' '', ''0'') end)  as [Seq], 
			IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''') + '' '' + IsNull(MiddleName, '''') As [Full Name],	
			Convert(NVarChar(10), AdmitDate, 111) as [Admit Date], 
			CONVERT (NVarChar(5), AdmitTime, 14) as [Admit Time] ,
			Convert(NVarChar(10), DischargeDate, 111) as [Discharge Date], 		
			(select top 1 DisplayCode from dbo.LU_AbstractStatus where Code = (case when isnull(AB_Abstract.IsCompleted, 0) = 0 then 1 else AB_Abstract.IsCompleted end) ) as [Status],  --ED - 01604
			(select top 1 DisplayCode from dbo.LU_AbstractStatus where Code = (case when isnull(AB_Abstract.IsCompleteLevel1, 0) = 0 then 1 else AB_Abstract.IsCompleteLevel1 end) ) as [Status (L1/2)]  --ED-02065
			into ' + @TempTable + ' FROM dbo.AB_Abstract WHERE ' + @CCRSearch + ' ' + @Where + ' 
			AND CareType = ' + @CareType + '
			AND (ICDType = ''' + @ICDType1 + '''
				OR ICDType = ''' + @ICDType2 + ''')
			AND IsDeleted = 2' + @SearchPrefix + @HospSearch +
			+ @ExtraSearch + ' ORDER BY [Hosp ID], [Admit Date]'

        set @order = ' ORDER BY [Hosp ID], [Admit Date]'
        --print @sql
        exec sp_executesql @sql
    end
    ELSE IF @FieldName = 'DischargeDate'  --AND (@AppID NOT IN (100, 200))
    BEGIN    		set @SQL = @SQLTopX + 'AbstractID, 
    		Convert(NVarChar(10), DischargeDate, 111) as [SearchItem#], 
			(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Abstract.HospitalID, 0)) as [Hosp ID],
			(select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = AB_Abstract.ChartNumber) as [Deceased],
    		replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') as [Chart #], 
	    	EncounterNumber as [Encounter #], 
	    	(case when EncounterSequence > 999 then cast(EncounterSequence as varchar(50)) else replace(space(3-len(EncounterSequence)) + convert(nvarchar(3), EncounterSequence), '' '', ''0'') end) as [Seq], 
    		IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''') + '' '' + IsNull(MiddleName, '''') As [Full Name],
    		Convert(NVarChar(10), AdmitDate, 111) as [Admit Date], 
    		CONVERT (NVarChar(5), AdmitTime, 14) as [Admit Time], 		
    		Convert(NVarChar(10), DischargeDate, 111) as [Discharge Date], 
		(select top 1 DisplayCode from dbo.LU_AbstractStatus where Code = (case when isnull(AB_Abstract.IsCompleted, 0) = 0 then 1 else AB_Abstract.IsCompleted end) ) as [Status],  --ED - 01604
		(select top 1 DisplayCode from dbo.LU_AbstractStatus where Code = (case when isnull(AB_Abstract.IsCompleteLevel1, 0) = 0 then 1 else AB_Abstract.IsCompleteLevel1 end) ) as [Status (L1/2)]  --ED-02065
    		into ' + @TempTable + ' FROM dbo.AB_Abstract WHERE ' + @CCRSearch + ' ' + @Where + '
    			AND CareType = ' + @CareType + '
    			AND (ICDType = ''' + @ICDType1 + '''
    				OR ICDType = ''' + @ICDType2 + ''')
    			AND IsDeleted = 2' + @SearchPrefix + @HospSearch +
			+ @ExtraSearch + ' ORDER BY [Hosp ID], [Discharge Date]'
        
        set @order = ' ORDER BY [Hosp ID], [Discharge Date]'
	    --print @sql
        exec sp_executesql @sql
    END
    ELSE IF @FieldName = 'LastName' AND @NameSplit = 0
	BEGIN
		--13507: Moved to top
		--Set @SearchString = replace(@SearchString, '''', '''''')
		set @SQL = @SQLTopX + 'AbstractID,
            LastName as [SearchItem#], 
			(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Abstract.HospitalID, 0)) as [Hosp ID],
			(select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = AB_Abstract.ChartNumber) as [Deceased],
			replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') as [Chart #], 
	    	EncounterNumber as [Encounter #], 
	    	(case when EncounterSequence > 999 then cast(EncounterSequence as varchar(50)) else replace(space(3-len(EncounterSequence)) + convert(nvarchar(3), EncounterSequence), '' '', ''0'') end) as [Seq], 
			IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''') + '' '' + IsNull(MiddleName, '''') As [Full Name],	    		
			Convert(NVarChar(10), AdmitDate, 111) as [Admit Date],
			CONVERT (NVarChar(5), AdmitTime, 14) as [Admit Time] ,
			Convert(NVarChar(10), DischargeDate, 111) as [Discharge Date], 		
			(select top 1 DisplayCode from dbo.LU_AbstractStatus where Code = (case when isnull(AB_Abstract.IsCompleted, 0) = 0 then 1 else AB_Abstract.IsCompleted end) ) as [Status],  --ED - 01604
			(select top 1 DisplayCode from dbo.LU_AbstractStatus where Code = (case when isnull(AB_Abstract.IsCompleteLevel1, 0) = 0 then 1 else AB_Abstract.IsCompleteLevel1 end) ) as [Status (L1/2)]  --ED-02065
			into ' + @TempTable + ' FROM dbo.AB_Abstract WHERE ' + @CCRSearch + ' LastName Like ''' + @SearchString + '%'' 
			AND CareType = ' + @CareType + ' 
			AND (ICDType = ''' + @ICDType1 + '''
				OR ICDType = ''' + @ICDType2 + ''')
			AND IsDeleted = 2' + @SearchPrefix + @HospSearch +
			+ @ExtraSearch + ' ORDER BY [Hosp ID], [Full Name], [Admit Date] DESC'

        set @order = ' ORDER BY [Hosp ID], [Full Name], [Admit Date] DESC'
        --print @sql
        exec sp_executesql @sql
	END
    ELSE IF @FieldName = 'LastName' AND @NameSplit > 0
	BEGIN
		--13507: Moved to top
		--Set @SearchString = replace(@SearchString, '''', '''''')
		set @SQL = @SQLTopX + 'AbstractID, 
			IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''') + '' '' + IsNull(MiddleName, '''') As [SearchItem#],
			(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Abstract.HospitalID, 0)) as [Hosp ID],
			(select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = AB_Abstract.ChartNumber) as [Deceased],
			replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') as [Chart #], 
    		EncounterNumber as [Encounter #], 
    		(case when EncounterSequence > 999 then cast(EncounterSequence as varchar(50)) else replace(space(3-len(EncounterSequence)) + convert(nvarchar(3), EncounterSequence), '' '', ''0'') end) as [Seq], 
			IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''') + '' '' + IsNull(MiddleName, '''') As [Full Name],
			Convert(NVarChar(10), AdmitDate, 111) as [Admit Date], 
			CONVERT (NVarChar(5), AdmitTime, 14) as [Admit Time] ,
			Convert(NVarChar(10), DischargeDate, 111) as [Discharge Date], 		
			(select top 1 DisplayCode from dbo.LU_AbstractStatus where Code = (case when isnull(AB_Abstract.IsCompleted, 0) = 0 then 1 else AB_Abstract.IsCompleted end) ) as [Status],  --ED - 01604
			(select top 1 DisplayCode from dbo.LU_AbstractStatus where Code = (case when isnull(AB_Abstract.IsCompleteLevel1, 0) = 0 then 1 else AB_Abstract.IsCompleteLevel1 end) ) as [Status (L1/2)]  --ED-02065
			into ' + @TempTable + ' FROM dbo.AB_Abstract WHERE ' + @CCRSearch + ' LastName Like ''' + rtrim(ltrim(Left(@SearchString, @NameSplit-1))) + '%'' 
			AND FirstName Like ''' + rtrim(ltrim(Stuff(@SearchString, 1, @NameSplit, ''))) + '%'' 
			AND CareType = ' + @CareType + ' 
			AND (ICDType = ''' + @ICDType1 + '''
				OR ICDType = ''' + @ICDType2 + ''')
			AND IsDeleted = 2' + @SearchPrefix + @HospSearch +
			+ @ExtraSearch + ' ORDER BY [Hosp ID], [Full Name], [Admit Date] DESC'

        set @order = ' ORDER BY [Hosp ID], [Full Name], [Admit Date] DESC'
        --print @sql
        exec sp_executesql @sql
	END
--END

ELSE 
BEGIN

    Declare @TempFieldDesc as Varchar(100)
    set @TempFieldDesc = 'SearchItem#' --'[' + @FieldDesc + ']'
    set @TempFieldDesc = '[' + @TempFieldDesc + '] = ' + (case @DataType
        when 11 then 'Convert(NVarChar(10), ' + @FieldName + ', 111), '
        when 12 then 'Convert(NVarChar(10), ' + @FieldName + ', 111), ' --PR-01739
        when 13 then 'Convert(NVarChar(10), ' + @FieldName + ', 111), ' --PR-01739
        when 15 then 'Convert(NVarChar(5), ' + @FieldName + ', 14), ' 
        else         '' + @FieldName + ', '
        end)
    --print @TempFieldDesc
    set @select =@SQLTopX + 
            'AB_Abstract.AbstractID, 
    	 ' + @TempFieldDesc + ' 
	        [Hosp ID] = (select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Abstract.HospitalID, 0)),
         	[Deceased] = (select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = AB_Abstract.ChartNumber),
            [Chart #] = replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0''), ' +
            '[Encounter #] = EncounterNumber, ' +
            '[Seq] = (case when EncounterSequence > 999 then cast(EncounterSequence as varchar(50)) else replace(space(3-len(EncounterSequence)) + convert(nvarchar(3), EncounterSequence), '' '', ''0'')  end), ' + 
            '[Full Name] = IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''') + '' '' + IsNull(MiddleName, ''''), ' +
            '[Admit Date] = Convert(NVarChar(10), AdmitDate, 111), ' +
            '[Admit Time] = CONVERT (NVarChar(5), AdmitTime, 14), ' +
            '[Discharge Date] = Convert(NVarChar(10), DischargeDate, 111), ' + 		
	    '(select top 1 DisplayCode from dbo.LU_AbstractStatus where Code = (case when isnull(AB_Abstract.IsCompleted, 0) = 0 then 1 else AB_Abstract.IsCompleted end) ) as [Status], ' + --ED - 01604
	    '(select top 1 DisplayCode from dbo.LU_AbstractStatus where Code = (case when isnull(AB_Abstract.IsCompleteLevel1, 0) = 0 then 1 else AB_Abstract.IsCompleteLevel1 end) ) as [Status (L1/2)] ' --ED-02065


    set @from = 'into ' + @TempTable + ' FROM dbo.AB_Abstract ' + (case @DBTableName
        when 'AB_Abstract' then ''
        else 'join dbo.' + @DBTableName + ' ab2 on AB_Abstract.AbstractID = ab2.AbstractID '
    end)

    if (@DataType = 15) -- if it is a time
    begin 

        set @SearchString = (case charindex(':', @SearchString)
            when 1 then '00' + @SearchString
            when 2 then '0' + @SearchString
            else @SearchString
        end)

        set @SearchString = replace(@SearchString, ':', '')

        set @SearchString = (case len(@SearchString) 
            when 0 then '00:00'
            when 1 then '00:0' + @SearchString 
            when 2 then '00:' + @SearchString
            when 3 then '0' + left(@SearchString, 1) + ':' + right(@SearchString, 2) 
            when 4 then left(@SearchString, 2) + ':' + right(@SearchString, 2)
            else left(@SearchString, 2) + ':' + substring(@SearchString, 2, 2)
        end)

        --if (isdate(@SearchString) = 0) Set @SearchString = '23:59:59' --PR-03191
        --set @where = @FieldName + ' >= ''1899-12-30 ' + @SearchString + ''' ' --PR-03191
	if (isdate(@SearchString) = 0) Set @SearchString = '23:59' --PR-03191
	set @where = 'convert(NVarChar(5), ' + @FieldName + ', 14) >= ''' + @SearchString + ''' ' --PR-03191
    end

    else if isnull(@where, '') = ''-- all other cases
    begin
		select @FieldDT = Data_Type from information_schema.columns Where Column_Name = @FieldName and Table_Name like 'AB_%'
		If (@FieldDT = 'int') 
        begin
            --if (@SearchString = '') Set @SearchString = '0'
            if (isnumeric(@SearchString) <> 1) Set @SearchString = '0'
            set @where = @FieldName + ' >= ' + @SearchString + ' '
        end
        else set @where = @FieldName + ' Like ''%' + @SearchString + '%'' '
    end 

    set @where = 
        'WHERE ' + @CCRSearch + ' CareType = ' + @CareType + ' ' +
		'AND ICDType IN (''' + @ICDType1 + ''', ''' + @ICDType2 + ''') ' +
		'AND IsDeleted = 2 ' + @SearchPrefix + @HospSearch +
        'AND ' + @where + @ExtraSearch

    --set @order = ' ORDER BY [Hosp ID], [SearchItem#], [Admit Date] DESC'
    
    select @sql = @select + @from + @where -- + @order
    --print @sql
    exec sp_executesql @sql
END
--PRINT @SQL

If @ShowVip = '2'
Begin
	set @SQL = 'delete ' + @TempTable + ' where [Chart #] in (select replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') 
		from CM_CPI where isnull(secret, 0) = 1 and replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')
		in (select [Chart #] from ' + @TempTable + '))'
	Exec(@SQL)
End
If @SearchAudit = 1
Begin
	Declare @CurDTime as Datetime
	Set @CurDTime = getdate()
	set @SQL = 'insert into AU_SearchDetail select ' + cast(@Appid as varchar(10)) + ', AbstractID, ''' + Cast(@LogID as varchar(10)) + ''', ''' + convert(varchar(30), @CurDTime, 120) + ''' as Field2 from ' + @TempTable
	exec(@SQL)
end

Set nocount off
	set @SQL = 'select AbstractID as [ ], [SearchItem#] as [' + @fielddesc + '], 
    [Hosp ID], [Deceased], [Chart #], [Encounter #], [Seq], [Full Name], [Admit Date], [Admit Time],
    [Discharge Date], [Status], [Status (L1/2)] From ' + @TempTable + ' order by [Hosp ID], [SearchItem#] ' --@order
	--print @sql 
	exec(@SQL)
	set @SQL = 'drop table ' + @TempTable
	exec(@SQL)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--F_SearchAbstract_Chart '23217', ' 000023217', 4,  0,  '0' 



-- Called by the New Abstract Record Form (Locates Chart to user in new record).
CREATE PROCEDURE [F_SearchAbstract_Chart]
   @SearchString as VarChar(50), 
   @SearchString2 as VarChar(50),
   @UserID as int = 1,
   @Exact as int = 0,
   @HospID as varchar(100) = '0'
AS 
Set Nocount on
   Declare @SQL as NVarChar(1500)

--Chart Audits, Prefixs, VIP and Top X parameters
   Declare @SearchPrefix as NVarChar(50)
   Declare @ShowVip as NVarChar(1)
   Declare @TopX as NVarChar(3)
   Declare @SearchAudit as int
   Declare @SQLTopX as NVarChar(20)
   Select @SearchPrefix = isnull(searchchartprefix, ''), @ShowVip = isnull(showvip, 0) from u_users where code = @UserID
   --2.x-0010 Allow X, Y, Z for stillbirth
   --If @SearchPrefix <> '' 
   If @SearchPrefix <> '' and left(@SearchString, 1) not in ('X', 'Y', 'Z')
   begin
       --2.x-0010 I think the prefix length can be 1 or 2.
       --if left(@SearchString, 2) <> @SearchPrefix set @SearchString = @SearchPrefix + @SearchString
       --if left(@SearchString2, 2) <> @SearchPrefix set @SearchString2 = @SearchPrefix + @SearchString2
       if left(@SearchString, len(rtrim(@SearchPrefix))) <> @SearchPrefix set @SearchString = @SearchPrefix + @SearchString
       if left(@SearchString2, len(rtrim(@SearchPrefix))) <> @SearchPrefix set @SearchString2 = @SearchPrefix + @SearchString2
   end                     

   Select @TopX = isnull(TopSearch, '999'), @SearchAudit = EnableSearchAudit FROM H_HospitalProfile
   Set @SQLTopX = 'Select top ' + @TopX + ' ' 
   Declare @TempTable as NVarChar(100)
   set @TempTable = '##SearchTmp' + replace(convert(nvarchar(100), getdate(), 114), ':', '')

	insert into AU_Search Values (0, @SearchString, @UserID, GetDate(), 'Chart Number') --PR - 06295

--13507: Stops ' from screwing it up
Set @SearchString = replace(@SearchString, '''', '''''')
Set @SearchString2 = replace(@SearchString2, '''', '''''')

   IF @Exact = 0 
           Set @SQL = @SQLTopX + ' PatientID as [ ], 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CM_CPI.HospitalID, 0)) as [Hosp ID],
		case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
                           replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')  as [ChartNumber],
                           IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''')  + '' '' + IsNull(MiddleName, '''') As [Full Name],
                           Convert(VarChar(10), BirthDate, 111) as [Birth Date]
           into ' + @TempTable + '  FROM dbo.CM_CPI 
           WHERE (ChartNumber LIKE ''' + @SearchString + '%'' OR ChartNumber LIKE ''' + @SearchString2 + '%'')
	   AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end) 
           AND IsDeleted = 2 ORDER BY [Hosp ID], ChartNumber'
   Else
           Set @SQL = @SQLTopX + ' PatientID as [ ], 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CM_CPI.HospitalID, 0)) as [Hosp ID],
		case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
                           replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')  as [ChartNumber],
                           IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''')  + '' '' + IsNull(MiddleName, '''') As [Full Name],
                           Convert(VarChar(10), BirthDate, 111) as [Birth Date]
           into ' + @TempTable + '  FROM dbo.CM_CPI 
           WHERE (ChartNumber = ''' + @SearchString + ''' OR ChartNumber = ''' + @SearchString2 + ''')
	   AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end) 
           AND IsDeleted = 2 ORDER BY [Hosp ID], ChartNumber'

--print @sql
   exec sp_executesql @sql

   If @ShowVip  <> '1'  -- = '2'
   Begin
           set @SQL = 'delete ' + @TempTable + ' where [ChartNumber] in (select replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') 
                   from CM_CPI where isnull(secret, 0) = 1 and replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')
                   in (select [ChartNumber] from ' + @TempTable + '))'
           Exec(@SQL)
   End
   Set nocount off
           set @SQL = 'select * From ' + @TempTable
           exec(@SQL)
           set @SQL = 'drop table ' + @TempTable
           exec(@SQL)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Called by the Abstract Search Form
CREATE       PROCEDURE [F_SearchAbstract2]
	@CareType 	[varchar](3),
	@ICDType1 	[varchar](1),
	@ICDType2 	[varchar](1) = '',
	@AppID 	    [int], 
	@FKey 		[int],
	@SearchString 	[varchar](50) = '',
	@SearchString2 [varchar](50) = '',
	@UserID 	[int] = 1
AS 

	DECLARE @SQL    varchar(1500)
   	DECLARE @select varchar(750)
    	DECLARE @from   varchar(150)
   	DECLARE @where  varchar(500)
    	DECLARE @order  varchar(100)

	DECLARE @DataType    int
	DECLARE @LookupTable varchar(50)
	DECLARE @FieldName   varchar(50)
	DECLARE @NameSplit   int
	DECLARE @FieldDesc   varchar(150)
	DECLARE @Temp        datetime
	DECLARE @DBTableName varchar(50)
	Declare @FieldDT     varchar(20)
	DECLARE @CCRSearch   varchar(50)

	SELECT @DataType = DataType, @LookupTable = LookUpTable FROM U_UsersFields  WHERE AppID = @AppID AND FieldID = @FKey AND UserID = @UserID
	SELECT @FieldName = SystemName, @FieldDesc = InHouseDesc FROM U_Fields  WHERE FieldID = @FKey
	SELECT @DBTableName = Table_Name from information_schema.columns Where Column_Name = @FieldName and Table_Name like 'AB_%'

	SET @NameSplit = CHARINDEX(',', @SearchString) 

IF @AppID = 100 or @AppID = 200
	SET @CCRSearch = 'isnull(DischargeDate, '''') = '''' AND'
ELSE IF @AppID = 301 OR @AppID = 401
	SET @CCRSearch = ''
ELSE
	SET @CCRSearch = 'isnull(DischargeDate, '''') <> '''' AND'

if @FieldName in ('EncounterNumber', 'ChartNumber', 'AdmitDate', 'DischargeDate', 'LastName')
begin 

    IF @FieldName = 'EncounterNumber'     	
    begin
        set @SQL = 'SELECT TOP 100 PERCENT AbstractID as [ ], 
    		EncounterNumber as [Encounter #], 
    		replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')  as [Chart #], 
    		IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''') + '' '' + IsNull(MiddleName, '''') As [Full Name], 
    		Convert(varchar(10), AdmitDate, 111) as [Admit Date], 
    		CONVERT (varchar(5), AdmitTime, 14) as [Admit Time] ,
    		Convert(varchar(10), DischargeDate, 111) as [Discharge Date] 
    		FROM dbo.AB_Abstract WHERE ' + @CCRSearch + ' EncounterNumber Like ''' + @SearchString + '%''
    		AND CareType = ' + @CareType + '
    		AND (ICDType = ''' + @ICDType1 + '''
    			OR ICDType = ''' + @ICDType2 + ''')
    		AND IsDeleted = 2
    		ORDER BY EncounterNumber DESC, AdmitDate DESC'
        EXECUTE(@SQL)
        RETURN 0
    end

    ELSE IF @FieldName = 'ChartNumber' 
    begin
		set @SQL = 'SELECT TOP 100 PERCENT AbstractID as [ ], 
			replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') as [Chart #], 
	    		EncounterNumber as [Encounter #], 
			IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''') + '' '' + IsNull(MiddleName, '''') As [Full Name],
			Convert(varchar(10), AdmitDate, 111) as [Admit Date], 
			CONVERT (varchar(5), AdmitTime, 14) as [Admit Time] ,
			Convert(varchar(10), DischargeDate, 111) as [Discharge Date] 
			FROM dbo.AB_Abstract WHERE ' + @CCRSearch + ' (ChartNumber Like ''' + @SearchString + '%'' OR ChartNumber LIKE ''' + @SearchString2 +'%'')
			AND CareType = ' + @CareType + '
			AND (ICDType = ''' + @ICDType1 + '''
				OR ICDType = ''' + @ICDType2 + ''')
			AND IsDeleted = 2
			ORDER BY [Chart #] Desc, AdmitDate DESC'
        EXECUTE(@SQL)
        RETURN 0
    end

    ELSE IF @FieldName = 'AdmitDate' 
    begin
		set @SQL = 'SELECT TOP 100 PERCENT AbstractID as [ ], 
			Convert(varchar(10), AdmitDate, 111) as [Admit Date], 
			replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') as [Chart #], 
	    		EncounterNumber as [Encounter #], 
			IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''') + '' '' + IsNull(MiddleName, '''') As [Full Name],
			CONVERT (varchar(5), AdmitTime, 14) as [Admit Time] ,
			Convert(varchar(10), DischargeDate, 111) as [Discharge Date] 
			FROM dbo.AB_Abstract WHERE ' + @CCRSearch + ' AdmitDate >= Convert(Datetime, ''' + @SearchString + ''') 
			AND CareType = ' + @CareType + '
			AND (ICDType = ''' + @ICDType1 + '''
				OR ICDType = ''' + @ICDType2 + ''')
			AND IsDeleted = 2
			ORDER BY AdmitDate'
        EXECUTE(@SQL)
        RETURN 0
    end

    ELSE IF @FieldName = 'DischargeDate' 
    BEGIN        IF (@AppID NOT IN (100, 200))
        BEGIN
    		set @SQL = 'SELECT TOP 100 PERCENT AbstractID as [ ], 
    			Convert(varchar(10), DischargeDate, 111) as [Discharge Date], 
    			replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') as [Chart #], 
	    		EncounterNumber as [Encounter #], 
    			IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''') + '' '' + IsNull(MiddleName, '''') As [Full Name],
    			Convert(varchar(10), AdmitDate, 111) as [Admit Date], 
    			CONVERT (varchar(5), AdmitTime, 14) as [Admit Time] 
    			FROM dbo.AB_Abstract WHERE DischargeDate >= Convert(Datetime, ''' + @SearchString + ''')
    			AND CareType = ' + @CareType + '
    			AND (ICDType = ''' + @ICDType1 + '''
    				OR ICDType = ''' + @ICDType2 + ''')
    			AND IsDeleted = 2
    			ORDER BY DischargeDate'
            EXECUTE(@SQL)
            RETURN 0
        END
    END

    ELSE IF @FieldName = 'LastName' AND @NameSplit = 0
	BEGIN
		Set @SearchString = replace(@SearchString, '''', '''''')
		set @SQL = 'SELECT TOP 100 PERCENT AbstractID as [ ], 
			IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''') + '' '' + IsNull(MiddleName, '''') As [Full Name],
	    		EncounterNumber as [Encounter #], 
			replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') as [Chart #], 
			Convert(varchar(10), AdmitDate, 111) as [Admit Date],
			CONVERT (varchar(5), AdmitTime, 14) as [Admit Time] ,
			Convert(varchar(10), DischargeDate, 111) as [Discharge Date] 
			FROM dbo.AB_Abstract WHERE ' + @CCRSearch + ' LastName Like ''' + @SearchString + '%'' 
			AND CareType = ' + @CareType + ' 
			AND (ICDType = ''' + @ICDType1 + '''
				OR ICDType = ''' + @ICDType2 + ''')
			AND IsDeleted = 2
			ORDER BY LastName DESC, FirstName, AdmitDate DESC'
        EXECUTE(@SQL)
        RETURN 0
	END

    ELSE IF @FieldName = 'LastName' AND @NameSplit > 0
	BEGIN
		Set @SearchString = replace(@SearchString, '''', '''''')
		set @SQL = 'SELECT TOP 100 PERCENT AbstractID as [ ], 
			IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''') + '' '' + IsNull(MiddleName, '''') As [Full Name],
	    		EncounterNumber as [Encounter #], 
			replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') as [Chart #], 
			Convert(varchar(10), AdmitDate, 111) as [Admit Date], 
			CONVERT (varchar(5), AdmitTime, 14) as [Admit Time] ,
			Convert(varchar(10), DischargeDate, 111) as [Discharge Date] 
			FROM dbo.AB_Abstract WHERE ' + @CCRSearch + ' LastName Like ''' + rtrim(ltrim(Left(@SearchString, @NameSplit-1))) + '%'' 
			AND FirstName Like ''' + rtrim(ltrim(Stuff(@SearchString, 1, @NameSplit, ''))) + '%'' 
			AND CareType = ' + @CareType + ' 
			AND (ICDType = ''' + @ICDType1 + '''
				OR ICDType = ''' + @ICDType2 + ''')
			AND IsDeleted = 2
			ORDER BY LastName DESC, FirstName, AdmitDate DESC'
        EXECUTE(@SQL)
        RETURN 0
	END
END

ELSE 
BEGIN


    set @FieldDesc = '[' + @FieldDesc + '] = ' + (case @DataType
        when 11 then 'Convert(varchar(10), ' + @FieldName + ', 111), '
        when 12 then 'Convert(varchar(10), ' + @FieldName + ', 111), ' --PR-01739
        when 13 then 'Convert(varchar(10), ' + @FieldName + ', 111), ' --PR-01739
        when 15 then 'Convert(varchar(5), ' + @FieldName + ', 14), ' 
        else         '' + @FieldName + ', '
        end)

    set @select = 
        'SELECT TOP 100 PERCENT ' +
            '[ ]              = ab.AbstractID, ' + @FieldDesc +
            '[Chart #]        = replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0''), ' +
            '[Encounter #]    = EncounterNumber, ' +
            '[Full Name]      = IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''') + '' '' + IsNull(MiddleName, ''''), ' +
            '[Admit Date]     = Convert(varchar(10), AdmitDate, 111), ' +
            '[Admit Time]     = CONVERT (varchar(5), AdmitTime, 14), ' +
            '[Discharge Date] = Convert(varchar(10), DischargeDate, 111) ' 

    set @from = 'FROM dbo.AB_Abstract ab ' + (case @DBTableName
        when 'AB_Abstract' then ''
        else 'join dbo.' + @DBTableName + ' ab2 on ab.AbstractID = ab2.AbstractID '
    end)

    -- determine the Where Clause base on datatype
    if (@DataType in (11, 12, 13))     -- if it is a date --PR-01739
    begin 
        if (isdate(@SearchString) = 0) set @SearchString = '1950/01/01'
        set @where = @FieldName + ' >= Convert(DateTime, ''' + @SearchString + ''') '
    end 

    else if (@DataType = 15) -- if it is a time
    begin 

        set @SearchString = (case charindex(':', @SearchString)
            when 1 then '00' + @SearchString
            when 2 then '0' + @SearchString
            else @SearchString
        end)

        set @SearchString = replace(@SearchString, ':', '')

        set @SearchString = (case len(@SearchString) 
            when 0 then '00:00'
            when 1 then '00:0' + @SearchString 
            when 2 then '00:' + @SearchString
            when 3 then '0' + left(@SearchString, 1) + ':' + right(@SearchString, 2) 
            when 4 then left(@SearchString, 2) + ':' + right(@SearchString, 2)
            else left(@SearchString, 2) + ':' + substring(@SearchString, 2, 2)
        end)

        --if (isdate(@SearchString) = 0) Set @SearchString = '23:59:59' --PR-03191
        --set @where = @FieldName + ' >= ''1899-12-30 ' + @SearchString + ''' ' --PR-03191
	if (isdate(@SearchString) = 0) Set @SearchString = '23:59' --PR-03191
	set @where = 'convert(NVarChar(5), ' + @FieldName + ', 14) >= ''' + @SearchString + ''' ' --PR-03191
    end

    else -- all other cases
    begin
		select @FieldDT = Data_Type from information_schema.columns Where Column_Name = @FieldName and Table_Name like 'AB_%'
		If (@FieldDT = 'int') 
        begin
            if (@SearchString = '') Set @SearchString = '0'
            set @where = @FieldName + ' >= ' + @SearchString + ' '
        end
        else set @where = @FieldName + ' Like ''%' + @SearchString + '%'' '
    end 


    set @where = 
        'WHERE ' + @CCRSearch + ' CareType = ' + @CareType + ' ' +
		'AND ICDType IN (''' + @ICDType1 + ''', ''' + @ICDType2 + ''') ' +
		'AND IsDeleted = 2 ' +
        'AND ' + @where

    set @order = 'ORDER BY ' + @FieldName + ', AdmitDate DESC'

    select @sql = @select + @from + @where + @order

    EXECUTE(@SQL)
    RETURN 0
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE     PROCEDURE [F_SearchCareMap]
	@FKey as int,
	@SearchString as varchar(50),
	@SearchString2 as varchar(50),
	@UserID as int = 1,
	@Exact as int = 0,
	@HospID as varchar(10) = '0'
AS 

DECLARE @SQL nvarchar(3000)
DECLARE @DataType int
DECLARE @FieldName as varchar(50)
DECLARE @FieldDescription as varchar(50)
DECLARE @NameSplit as int

select @DataType = (select DataType from U_UsersFields  WHERE AppID = 15 AND FieldID = @FKey and UserID = @UserID)
select @FieldName = (select SystemName from U_Fields  WHERE FieldID = @FKey)
select @FieldDescription = (select isnull(Header_User, @FieldName) from U_UsersFields  WHERE AppID = 15 AND FieldID = @FKey and UserID = @UserID)
select @NameSplit = CHARINDEX(',', @SearchString) 

--13507: Moved to top	
Set @SearchString = replace(@SearchString, '''', '''''')
Set @SearchString2 = replace(@SearchString2, '''', '''''')

	insert into AU_Search Values (550, @SearchString, @UserID, GetDate(), @FieldDescription) --PR - 06295


-- if @FKey = 45006 -- TERMINAL DIGIT SORT
--     begin
-- 	declare @TDigit as varchar(10)
-- 	declare @TDigitR as varchar(10)
-- 	declare @TDigitH as varchar(10)
-- 
-- 	select @TDigitR = TerminalDigit from H_RegionProfile
-- 	if @HospID = '0' 
-- 		select top 1 @TDigitH = TerminalDigit from H_HospitalProfile 
-- 	else
-- 		select top 1 @TDigitH = TerminalDigit from H_HospitalProfile where HospitalID = @HospID
-- 	
-- 	set @TDigit = @TDigitR
-- 	if len(@TDigitH) <> 0 and isnull(@TDigitH, '0') <> '0' set @TDigit = @TDigitH
-- 	--set @TDigit = '926315'
-- 	
-- 	declare @Pos1 as varchar(1)
-- 	declare @len1 as varchar(1)
-- 	declare @Pos2 as varchar(1)
-- 	declare @len2 as varchar(1)
-- 	declare @Pos3 as varchar(1)
-- 	declare @len3 as varchar(1)
-- 	declare @Pos4 as varchar(1)
-- 	declare @len4 as varchar(1)
-- 	declare @Pos5 as varchar(1)
-- 	declare @len5 as varchar(1)
-- 
-- 	declare @order as varchar(400)
-- 	declare @OrdT as varchar(400)
-- 
-- 	if isnumeric(substring(@TDigit, 1, 1)) = 1 
-- 		set @Pos1 = substring(@TDigit, 1, 1)
-- 	if isnumeric(substring(@TDigit, 2, 1)) = 1 
-- 		set @len1 = substring(@TDigit, 2, 1)
-- 	if isnumeric(substring(@TDigit, 3, 1)) = 1 
-- 		set @Pos2 = substring(@TDigit, 3, 1)
-- 	if isnumeric(substring(@TDigit, 4, 1)) = 1 
-- 		set @len2 = substring(@TDigit, 4, 1)
-- 	if isnumeric(substring(@TDigit, 5, 1)) = 1 
-- 		set @Pos3 = substring(@TDigit, 5, 1)
-- 	if isnumeric(substring(@TDigit, 6, 1)) = 1 
-- 		set @len3 = substring(@TDigit, 6, 1)
-- 	if isnumeric(substring(@TDigit, 7, 1)) = 1 
-- 		set @Pos4 = substring(@TDigit, 7, 1)
-- 	if isnumeric(substring(@TDigit, 8, 1)) = 1 
-- 		set @len4 = substring(@TDigit, 8, 1)
-- 	if isnumeric(substring(@TDigit, 9, 1)) = 1 
-- 		set @Pos5 = substring(@TDigit, 9, 1)
-- 	if isnumeric(substring(@TDigit, 10, 1)) = 1 
-- 		set @len5 = substring(@TDigit, 10, 1)
-- 
-- 	if len(@Pos1) <> 0 and len(@len1) <> 0
-- 		set @OrdT = ' substring(replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0''), ' + @Pos1 + ', ' + @len1 + '), '
-- 		
-- 	if len(@Pos2) <> 0 and len(@len2) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0''), ' + @Pos2 + ', ' + @len2 + '), '
-- 
-- 	if len(@Pos3) <> 0 and len(@len3) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0''), ' + @Pos3 + ', ' + @len3 + '), '
-- 
-- 	if len(@Pos4) <> 0 and len(@len4) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0''), ' + @Pos4 + ', ' + @len4 + '), '
-- 
-- 	if len(@Pos5) <> 0 and len(@len5) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0''), ' + @Pos5 + ', ' + @len5 + '), '
-- 
-- 	if len(@OrdT) <> 0 
-- 		set @OrdT = left(@OrdT, len(@OrdT) - 1)
-- 
-- 	set @SQL = 'select top 999 dbo.Def_SlipMain.DefeciencyID AS [ ], 
-- 			replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
-- 			dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number], 
-- 			(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
-- 			(select convert(varchar(10), isnull(DischargeDate, AdmitDate), 111) from AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
-- 			isnull(dbo.CM_CPI.LastName, '''') + '', '' + isnull(dbo.CM_CPI.FirstName, '''') + '' '' + isnull(dbo.CM_CPI.Middlename, '''') AS [Patient Name], 
-- 			dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],
-- 			(select DisplayCode from LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
-- 			(select DisplayCode from DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status]
-- 		from dbo.Def_SlipMain
-- 		left join dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
-- 		left join dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID
-- 		WHERE (isnull(dbo.Def_SlipMain.DefMainStatus, 0) <> 8) 
-- 		AND (isnull(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else isnull(Def_SlipMain.HospitalID, 0) end) 	
-- 		AND (dbo.CM_CPI.ChartNumber LIKE ''' + @SearchString + '%'' OR ChartNumber LIKE ''' + @SearchString2 + '%'') 
--         and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end) '  
-- 	+ @ExtraSearch 
-- 
-- 	set @order = ''
-- 	if len(@OrdT) <> 0 
-- 	        set @order = ' order by ' + @OrdT
-- 
-- 	set @sql = @sql + @order 
-- 	--print @sql
--         exec sp_executesql @sql 
--     end

--else 
if @FieldName = 'ClinicPatientID' 
begin
--	if @Exact = 0 
		set @SQL = 'select top 999 V.RecordID AS [ ], 
			(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(V.HospitalID, 0)) as [Hosp ID],
			replace(space(10-len(C.ChartNumber)) + C.ChartNumber, '' '', ''0'') AS [Chart #], 
		    	isnull(ClinicPatLName, '''') + '', '' + isnull(ClinicPatFName, '''') as [Patient Name],
			(select DisplayCode from LU_ClinicalPathway where Code = V.ClinicPath) as [Path], 
			convert(varchar(10), V.StartDate, 111) as [Start Date],
			convert(varchar(10), V.EndDate, 111) as [End Date]
		from CMV_ClinicalPathway V left join CM_CPI C ON V.ClinicPatientID = C.PatientID
		WHERE (C.ChartNumber like ''' + @SearchString + '%'' or C.ChartNumber like ''' + @SearchString2 + '%'') 
	        and (isnull(V.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(V.HospitalID, 0) end)   
		order by [Hosp ID], [Chart #] '
		
-- 	ELSE
-- 		set @SQL = 'select top 999 dbo.Def_SlipMain.DefeciencyID AS [ ], 
-- 			replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
-- 			dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number], 
-- 			(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
-- 			(select convert(varchar(10), isnull(DischargeDate, AdmitDate), 111) from AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
--     		isnull(dbo.CM_CPI.LastName, '''') + '', '' + isnull(dbo.CM_CPI.FirstName, '''') + '' '' + isnull(dbo.CM_CPI.Middlename, '''') AS [Patient Name], 
-- 			dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],
-- 			(select DisplayCode from LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
-- 			(select DisplayCode from DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status]
-- 		from dbo.Def_SlipMain
-- 		left join dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
-- 		left join dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID
-- 		WHERE (isnull(dbo.Def_SlipMain.DefMainStatus, 0) <> 8) 
-- 		AND (isnull(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else isnull(Def_SlipMain.HospitalID, 0) end) 	
-- 		AND (dbo.CM_CPI.ChartNumber = ''' + @SearchString + ''' OR ChartNumber = ''' + @SearchString2 + ''') 
--         and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end) '  +
-- 		@ExtraSearch + 
-- 		' order by [Chart Number]'
	--print @sql
	execute (@SQL)
end

-- ELSE IF @FieldName = 'DefVolumeID'
-- BEGIN
-- 	set @SQL = 'select top 999 dbo.Def_SlipMain.DefeciencyID AS [ ], 
-- 		dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number],
-- 		(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
-- 		replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
-- 		(select convert(varchar(10), isnull(DischargeDate, AdmitDate), 111) from AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
--    		isnull(dbo.CM_CPI.LastName, '''') + '', '' + isnull(dbo.CM_CPI.FirstName, '''') + '' '' + isnull(dbo.CM_CPI.Middlename, '''') AS [Patient Name], 
-- 		dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],
-- 		(select DisplayCode from LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
-- 		(select DisplayCode from DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status]
-- 	from dbo.Def_SlipMain
-- 	left join dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
-- 	left join dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID
-- 	WHERE (isnull(dbo.Def_SlipMain.DefMainStatus, 0) <> 8) 
-- 		AND (isnull(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else isnull(Def_SlipMain.HospitalID, 0) end) 	
--    	AND(dbo.Def_SlipMain.DefVolumeID IN (select VolumeID from CM_CPI_Volume WHERE VolumeNumber LIKE ''' + @SearchString + '%'')) 
--     and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end) '  +
--     	@ExtraSearch + 	   
-- 	' order by [Volume Number]'
-- 
--     execute (@SQL)
-- end
-- 
-- ELSE IF @FieldName = 'DefeciencyID'
-- BEGIN
-- 	set @SQL = 'select top 999 dbo.Def_SlipMain.DefeciencyID AS [ ], 
-- 		dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],
-- 		replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
-- 		dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number],
-- 		(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
-- 		(select convert(varchar(10), isnull(DischargeDate, AdmitDate), 111) from AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
-- 	    isnull(dbo.CM_CPI.LastName, '''') + '', '' + isnull(dbo.CM_CPI.FirstName, '''') + '' '' + isnull(dbo.CM_CPI.Middlename, '''') AS [Patient Name], 
-- 		(select DisplayCode from LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
-- 		(select DisplayCode from DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status]
-- 	from dbo.Def_SlipMain
-- 	left join dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
-- 	left join dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID
-- 	WHERE (isnull(dbo.Def_SlipMain.DefMainStatus, 0) <> 8) 
-- 		AND (isnull(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else isnull(Def_SlipMain.HospitalID, 0) end) 	
--     	AND (dbo.Def_SlipMain.DefeciencyID LIKE ''' + @SearchString + '%'') 
--         and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end) ' +
--     	@ExtraSearch + 	
-- 	' order by [Header Ref. ID]'
-- 
--     execute (@SQL)
-- end
-- 
-- ELSE IF @FieldName = 'DefDrNumber'
-- BEGIN
-- 		--(select UserDescription from LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider Name],
-- 	set @SQL = 'select top 999 dbo.Def_SlipMain.DefeciencyID AS [ ], 
-- 		(select DisplayCode from LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
-- 		replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
-- 		dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number], 
-- 		(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
-- 		(select convert(varchar(10), isnull(DischargeDate, AdmitDate), 111) from AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
-- 	    isnull(dbo.CM_CPI.LastName, '''') + '', '' + isnull(dbo.CM_CPI.FirstName, '''') + '' '' + isnull(dbo.CM_CPI.Middlename, '''') AS [Patient Name], 
-- 		dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],				
-- 		(select DisplayCode from DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status]
-- 	from dbo.Def_SlipMain
-- 	left join dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
-- 	left join dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID			
-- 	WHERE (isnull(dbo.Def_SlipMain.DefMainStatus, 0) <> 8) 
-- 		AND (isnull(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else isnull(Def_SlipMain.HospitalID, 0) end) 	
--     	AND (dbo.Def_SlipMain.DefDrNumber IN (select Code from LU_Provider WHERE DisplayCode LIKE ''' + @SearchString + '%'')) 
--         and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end) ' +
--     	@ExtraSearch + 
-- 	' order by [Provider #]'
-- 
--     execute (@SQL)
-- end
-- 
-- ELSE IF @FieldName = 'DefPatLastName' AND @NameSplit = 0
-- BEGIN
-- 	--13507: Moved to top	
-- 	--Set @SearchString = replace(@SearchString, '''', '''''')
-- 	set @SQL = 'select top 999 dbo.Def_SlipMain.DefeciencyID AS [ ], 
-- 	    isnull(dbo.CM_CPI.LastName, '''') + '', '' + isnull(dbo.CM_CPI.FirstName, '''') + '' '' + isnull(dbo.CM_CPI.Middlename, '''') AS [Patient Name], 
-- 		(select DisplayCode from LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
-- 		replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
-- 		dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number], 
-- 		(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
-- 		(select convert(varchar(10), isnull(DischargeDate, AdmitDate), 111) from AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
-- 		dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],				
-- 		(select DisplayCode from DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status]
-- 	from dbo.Def_SlipMain
-- 	left join dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
-- 	left join dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID			
-- 	WHERE (isnull(dbo.Def_SlipMain.DefMainStatus, 0) <> 8) 
-- 		AND (isnull(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else isnull(Def_SlipMain.HospitalID, 0) end) 	
--     	AND (dbo.CM_CPI.LastName Like ''' + @SearchString + '%'' AND dbo.CM_CPI.IsDeleted = 2) 
--         and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end) ' +
--     	@ExtraSearch + 
-- 	' order by dbo.CM_CPI.LastName DESC, dbo.CM_CPI.FirstName'
--     
--     execute (@SQL)
-- end
-- 
-- ELSE IF @FieldName = 'DefPatLastName' AND @NameSplit > 0
-- BEGIN
-- 	--13507: Moved to top	
-- 	--Set @SearchString = replace(@SearchString, '''', '''''')
-- 	Set @NameSplit = CHARINDEX(',', @SearchString) 
-- 	--Set @SearchString = replace(@SearchString, '''', '''''')
-- 	set @SQL = 'select top 999 dbo.Def_SlipMain.DefeciencyID AS [ ], 
-- 	    isnull(dbo.CM_CPI.LastName, '''') + '', '' + isnull(dbo.CM_CPI.FirstName, '''') + '' '' + isnull(dbo.CM_CPI.Middlename, '''') AS [Patient Name], 
-- 		(select DisplayCode from LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
-- 		replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
-- 		dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number], 
-- 		(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
-- 		(select convert(varchar(10), isnull(DischargeDate, AdmitDate), 111) from AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
-- 		dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],				
-- 		(select DisplayCode from DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status]
-- 	from dbo.Def_SlipMain
-- 	left join dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
-- 	left join dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID			
-- 	WHERE (isnull(dbo.Def_SlipMain.DefMainStatus, 0) <> 8) 
-- 		AND (isnull(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else isnull(Def_SlipMain.HospitalID, 0) end) 	
-- 	AND (dbo.CM_CPI.LastName LIKE ''' + left(@SearchString, @NameSplit-1) + '%'' 
-- 	AND dbo.CM_CPI.FirstName LIKE ''' + Stuff(@SearchString,1, @NameSplit, '') + '%''
-- 	AND dbo.CM_CPI.IsDeleted = 2) 
--     and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end) ' +
--     	@ExtraSearch + 
-- 	' order by dbo.CM_CPI.LastName DESC, dbo.CM_CPI.FirstName'
-- 
--     execute (@SQL)
-- end
-- 
-- ELSE IF @FieldName = 'UserDescription'
-- BEGIN
-- 	set @SQL = 'select top 999 dbo.Def_SlipMain.DefeciencyID AS [ ], 
-- 		(select UserDescription from LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider Name],
-- 		(select DisplayCode from LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
-- 		replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
-- 		dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number], 
-- 		(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
-- 		(select convert(varchar(10), isnull(DischargeDate, AdmitDate), 111) from AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
-- 	    isnull(dbo.CM_CPI.LastName, '''') + '', '' + isnull(dbo.CM_CPI.FirstName, '''') + '' '' + isnull(dbo.CM_CPI.Middlename, '''') AS [Patient Name], 
-- 		dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],				
-- 		(select DisplayCode from DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status]
-- 	from dbo.Def_SlipMain
-- 	left join dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
-- 	left join dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID			
-- 	WHERE (isnull(dbo.Def_SlipMain.DefMainStatus, 0) <> 8) 
-- 		AND (isnull(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else isnull(Def_SlipMain.HospitalID, 0) end) 	
-- 	AND (dbo.Def_SlipMain.DefDrNumber IN (select Code from LU_Provider WHERE UserDescription LIKE ''' + @SearchString + '%'')) 
--     and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end) ' +
--     	@ExtraSearch + 
-- 	' order by [Provider #]'
--     EXECUTE(@SQL)
-- end
-- --Ticket 9030. Unique Bar Code Volume
-- ELSE IF @FieldName = 'BarCodeVolume'
-- BEGIN
-- 
-- 	set @SQL = 'select top 999 dbo.Def_SlipMain.DefeciencyID AS [ ], 
-- 		(select UserDescription from LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider Name],
-- 		(select DisplayCode from LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
-- 		replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
-- 		dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number], 
-- 		(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
-- 		(select convert(varchar(10), isnull(DischargeDate, AdmitDate), 111) from AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
-- 	    isnull(dbo.CM_CPI.LastName, '''') + '', '' + isnull(dbo.CM_CPI.FirstName, '''') + '' '' + isnull(dbo.CM_CPI.Middlename, '''') AS [Patient Name], 
-- 		dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],				
-- 		(select DisplayCode from DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status]
-- 	from dbo.Def_SlipMain
-- 	left join dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
-- 	left join dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID			
-- 	WHERE (isnull(dbo.Def_SlipMain.DefMainStatus, 0) <> 8) 
-- 		AND (isnull(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else isnull(Def_SlipMain.HospitalID, 0) end) 	
-- 	AND (isnull(dbo.CM_CPI_Volume.BarCodeVolume, '''') LIKE ''' + @SearchString + '%'') 
--     and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end) ' +
--     	@ExtraSearch + 
-- 	' order by [Provider #]'
--     EXECUTE(@SQL)
-- end
-- 
-- ELSE IF  @DataType in (11, 12, 13) --PR-01739
-- BEGIN
-- 	Declare @Where as varchar(1000)
-- 	if right(@SearchString, 2) = '00' 
-- 	Begin
-- 		set @where = '(' + @FieldName + ' >= convert(DateTime, ''' + left(@SearchString, 8) + '01'') and ' + @FieldName + ' < dateadd(M, 1, convert(DateTime, ''' + left(@SearchString, 8) + '01''))) '
-- 	end
-- 	Else if (isdate(@SearchString) = 0) 
-- 		set @SearchString = '1950/01/01'
-- 	If isnull(@where, '') = ''
-- 	        set @where = @FieldName + ' = convert(DateTime, ''' + @SearchString + ''') '
--  	select @SQL = 
-- 		'select top 999 dbo.Def_SlipMain.DefeciencyID AS [ ],
-- 		convert (varchar(10), ' + @FieldName + ', 111) AS [' + @FieldDescription + '],  
-- 		replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
-- 		dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number], 
-- 		(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
-- 		(select convert(varchar(10), isnull(DischargeDate, AdmitDate), 111) from AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
-- 		isnull(dbo.CM_CPI.LastName, '''') + '', '' + isnull(dbo.CM_CPI.FirstName, '''') + '' '' + isnull(dbo.CM_CPI.Middlename, '''') AS [Patient Name], 
-- 		dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],
-- 		(select DisplayCode from LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
-- 		(select DisplayCode from DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status]
-- 		from dbo.Def_SlipMain
-- 		left join dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
-- 		left join dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID
-- 		WHERE (isnull(dbo.Def_SlipMain.DefMainStatus, 0) <> 8) 
-- 		AND (isnull(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else isnull(Def_SlipMain.HospitalID, 0) end) 	
--         and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end)
-- 		AND ' + @where + 
--         @ExtraSearch + 	        
--         ' order by ' + @FieldName 
--  	EXECUTE(@SQL)
-- end
-- ELSE
-- BEGIN
-- 	select @SQL = 
-- 		'select top 999 dbo.Def_SlipMain.DefeciencyID AS [ ], ' +
-- 		@FieldName + ' AS [' + @FieldDescription + '],  
-- 		replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
-- 		dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number], 
-- 		(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
-- 		(select convert(varchar(10), isnull(DischargeDate, AdmitDate), 111) from AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
-- 		isnull(dbo.CM_CPI.LastName, '''') + '', '' + isnull(dbo.CM_CPI.FirstName, '''') + '' '' + isnull(dbo.CM_CPI.Middlename, '''') AS [Patient Name], 
-- 		dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],
-- 		(select DisplayCode from LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
-- 		(select DisplayCode from DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status]
-- 		from dbo.Def_SlipMain
-- 		left join dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
-- 		left join dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID
-- 		WHERE (isnull(dbo.Def_SlipMain.DefMainStatus, 0) <> 8) 
-- 		AND (isnull(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else isnull(Def_SlipMain.HospitalID, 0) end) 	
--         and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end)
-- 		AND ' + @FieldName + ' LIKE ''%' + @SearchString + '%''' +
--         @ExtraSearch + 	
--         ' order by ' + @FieldName 
--     --print @sql
-- 	EXECUTE(@SQL)
-- end




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





--exec F_SearchCC_Chart '123', ' 000000123', 1, 500004, 1, 0 



-- Called by the New Cancer Care Record Form (Locates Chart to user in new record).
CREATE                  PROCEDURE [F_SearchCC_Chart]
	@SearchString as VarChar(50), 
	@SearchString2 as VarChar(50),
	@SearchType as Int,
	@UserID as int = 1,
	@Exact as int = 0,
	@HospID as varchar(100) = '0',
	@SearchByHCN as int = 2
AS 

Set Nocount on
	Declare @Select as NVarchar(1500)
	Declare @SQL as NVarchar(1500)

	--Chart Audits, Prefixs, VIP and Top X parameters
	Declare @SearchPrefix as NVarChar(50)
	Declare @SearchPrefix_Org as NVarChar(100) --PR - 05450
	Declare @ShowVip as NVarChar(1)
	Declare @TopX as NVarChar(3)
	Declare @SearchAudit as int
	Declare @SQLTopX as NVarChar(30)

	--13507: Stops ' from screwing it up
	Set @SearchString = replace(@SearchString, '''', '''''')
	Set @SearchString2 = replace(@SearchString2, '''', '''''')

	Select @SearchPrefix = isnull(searchchartprefix, ''), @ShowVip = isnull(showvip, 0) from u_users where code = @UserID
	set @SearchPrefix_Org = @SearchPrefix   --PR - 05450
	If @SearchPrefix <> ''
		Set @SearchPrefix = ' and Chartnumber like ''' + @SearchPrefix + '%'' '
	If @HospID = '0'
		Select top 1 @TopX = isnull(TopSearch, '999'), @SearchAudit = EnableSearchAudit  FROM H_HospitalProfile 
	else	
		Select top 1 @TopX = isnull(TopSearch, '999'), @SearchAudit = EnableSearchAudit  FROM H_HospitalProfile where isnull(Code, 0) = @HospID
	Set @SQLTopX = 'Select distinct top ' + @TopX + ' ' 
	Declare @TempTable as NVarChar(100)
	set @TempTable = '##SearchTmp' + replace(convert(nvarchar(100), getdate(), 114), ':', '')

	insert into AU_Search Values (675, @SearchString, @UserID, GetDate(), 'Chart Number') --PR - 06295

IF @SearchType = 1
BEGIN
 	-- 01: DISEASE REGISTRY 
	if @Exact = 0 --PR-03514
		Set @SQL = @SQLTopX + ' PatientID AS [ ], PatientID AS [_],
				(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(C.HospitalID, 0)) as [Hosp ID],
				(case when DeathIndicator = 1 then ''Y'' else ''N'' end) as [Deceased],
				--(SELECT TOP 1 AA1 FROM CC_Demographic WHERE IsCurrent = 1 AND ChartNumber = C.ChartNumber ORDER BY AbstractID DESC) AS [Unique Register ID (AA1)],
				REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'')  AS [Chart Number],
				ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''')  + '' '' + ISNULL(MiddleName, '''') AS [Full Name],
				CONVERT(VARCHAR(10), BirthDate, 111) AS [Birth Date],
		        HealthCareNumber as [Health Care Number]		
		into ' + @TempTable + ' FROM CM_CPI C
		WHERE IsDeleted = 2 ' + @SearchPrefix + '
		AND ' + (case when @SearchByHCN = 1 then 'HealthCareNumber LIKE ''' + @SearchString + '%'' '
		              else '(ChartNumber LIKE ''' + @SearchString + '%'' OR ChartNumber LIKE ''' + @SearchString2 +'%'')
		--AND C.ChartNumber NOT IN (SELECT ChartNumber FROM CC_Demographic WHERE IsCurrent = 1) ' end) + '
		AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end) 
		ORDER BY [Hosp ID], ' + (case when @SearchByHCN = 1 then '[Health Care Number]' else '[Chart Number]' end)
	else
		Set @SQL = @SQLTopX + ' PatientID AS [ ], PatientID AS [_],
				(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(C.HospitalID, 0)) as [Hosp ID],
				(case when DeathIndicator = 1 then ''Y'' else ''N'' end) as [Deceased],
				--(SELECT TOP 1 AA1 FROM CC_Demographic WHERE IsCurrent = 1 AND ChartNumber = C.ChartNumber ORDER BY AbstractID DESC) AS [Unique Register ID (AA1)],
				REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'')  AS [Chart Number],
				ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''')  + '' '' + ISNULL(MiddleName, '''') AS [Full Name],
				CONVERT(VARCHAR(10), BirthDate, 111) AS [Birth Date],
		        HealthCareNumber as [Health Care Number]		
		into ' + @TempTable + ' FROM CM_CPI C
		WHERE IsDeleted = 2 ' + @SearchPrefix + '
		AND ' + (case when @SearchByHCN = 1 then 'HealthCareNumber = ''' + @SearchString + ''' '
		              else '(ChartNumber = ''' + @SearchString + ''' OR ChartNumber = ''' + @SearchString2 + ''') ' end) + '
		--AND C.ChartNumber NOT IN (SELECT ChartNumber FROM CC_Demographic WHERE IsCurrent = 1)
		AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end) 
		ORDER BY [Hosp ID], ' + (case when @SearchByHCN = 1 then '[Health Care Number]' else '[Chart Number]' end)
END

ELSE IF @SearchType = 2
BEGIN
    --PR - 05450
    if len(@SearchPrefix_Org) > 0 and len(isnull(@SearchString, '')) > 0
    begin
        if charindex(@SearchPrefix_Org, @SearchString) <> 1
        begin
            set @SearchString = @SearchPrefix_Org + @SearchString
        end
    end
 	-- 02: NDFP Enrollment  NP-00083: Jan 28 replace first field for AbstractID and added Sequence # 
	if @Exact = 0 --PR-03514
		Set @SQL = @SQLTopX + ' D.AbstractID AS [ ], LinkID AS [_],
				(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(D.HospitalID, 0)) as [Hosp ID],
				(select (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = D.ChartNumber) as [Deceased],
				--(SELECT TOP 1 AA1 FROM CC_Demographic WHERE IsCurrent = 1 AND ChartNumber = C.ChartNumber ORDER BY AbstractID DESC) AS [Unique Register ID (AA1)],
				REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'')  AS [Chart Number],
				ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''')  + '' '' + ISNULL(MiddleName, '''') AS [Full Name],
				CONVERT(VARCHAR(10), BirthDate, 111) AS [Birth Date], DR.DiseaseSequenceNum AS [Sequence],  --NP-00083 NDFP association with specific disease registration --,
		        HealthCareNumber as [Health Care Number]		
		into ' + @TempTable + ' FROM CC_Demographic D, CC_DiseaseRegister DR
		WHERE AppID = 675 and D.AbstractID = DR.AbstractID
		--AND IsDeleted = 2 ' 
		+ @SearchPrefix + '
		AND ' + (case when @SearchByHCN = 1 then 'HealthCareNumber LIKE ''' + @SearchString + '%'' '
		              else '(ChartNumber LIKE ''' + @SearchString + '%'' OR ChartNumber LIKE ''' + @SearchString2 +'%'')' end) + '
		AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end) 
		ORDER BY [Hosp ID], ' + (case when @SearchByHCN = 1 then '[Health Care Number]' else '[Chart Number]' end)
	else
		Set @SQL = @SQLTopX + ' D.AbstractID AS [ ], LinkID AS [_],
				(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(D.HospitalID, 0)) as [Hosp ID],
				(select (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = D.ChartNumber) as [Deceased],
				--(SELECT TOP 1 AA1 FROM CC_Demographic WHERE IsCurrent = 1 AND ChartNumber = C.ChartNumber ORDER BY AbstractID DESC) AS [Unique Register ID (AA1)],
				REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'')  AS [Chart Number],
				ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''')  + '' '' + ISNULL(MiddleName, '''') AS [Full Name],
				CONVERT(VARCHAR(10), BirthDate, 111) AS [Birth Date], DR.DiseaseSequenceNum AS [Sequence],  --NP-00083 NDFP association with specific disease registration --,
		        HealthCareNumber as [Health Care Number]		
		into ' + @TempTable + ' FROM CC_Demographic D, CC_DiseaseRegister DR
		WHERE AppID = 675 and D.AbstractID = DR.AbstractID
		--AND IsDeleted = 2 ' 
		+ @SearchPrefix + '
		AND ' + (case when @SearchByHCN = 1 then 'HealthCareNumber = ''' + @SearchString + ''' '
		              else '(ChartNumber = ''' + @SearchString + ''' OR ChartNumber = ''' + @SearchString2 +''')' end) + '
		AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end) 
		ORDER BY [Hosp ID], ' + (case when @SearchByHCN = 1 then '[Health Care Number]' else '[Chart Number]' end)
END

	--print @sql
	exec sp_executesql @sql

	If @ShowVip = '2'
	Begin
		set @SQL = 'delete ' + @TempTable + ' where [Chart Number] in (select replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') 
			from CM_CPI where isnull(secret, 0) = 1 and replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')
			in (select [Chart Number] from ' + @TempTable + '))'
		Exec(@SQL)
	End
	Set nocount off
		set @SQL = 'select * From ' + @TempTable
		exec(@SQL)
		set @SQL = 'drop table ' + @TempTable
		exec(@SQL)








GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Called by the New CCRS Record Form (Locates Chart to user in new record).
CREATE  PROCEDURE [F_SearchCCRS_Chart]
	@SearchString as VarChar(50), 
	@SearchString2 as VarChar(50),
	@SearchType as Int,
	@UserID as int = 1,
	@Exact as int = 0,
	@HospID as varchar(100) = '0'
AS 
Set Nocount on
	Declare @Select as NVarchar(2000)
	Declare @SQL as NVarchar(2000)

--Chart Audits, Prefixs, VIP and Top X parameters
	Declare @SearchPrefix as NVarChar(50)
	Declare @ShowVip as NVarChar(1)
	Declare @TopX as NVarChar(3)
	Declare @SearchAudit as int
	Declare @SQLTopX as NVarChar(30)

--13507: Stops ' from screwing it up
Set @SearchString = replace(@SearchString, '''', '''''')
Set @SearchString2 = replace(@SearchString2, '''', '''''')

	Select @SearchPrefix = isnull(searchchartprefix, ''), @ShowVip = isnull(showvip, 0) from u_users where code = @UserID
	If @SearchPrefix <> ''
		Set @SearchPrefix = ' and Chartnumber like ''' + @SearchPrefix + '%'' '
	If @HospID = '0'
		Select top 1 @TopX = isnull(TopSearch, '999'), @SearchAudit = EnableSearchAudit  FROM H_HospitalProfile 
	else	
		Select top 1 @TopX = isnull(TopSearch, '999'), @SearchAudit = EnableSearchAudit  FROM H_HospitalProfile where isnull(Code, 0) = @HospID
	Set @SQLTopX = 'Select distinct top ' + @TopX + ' ' 
	Declare @TempTable as NVarChar(100)
	set @TempTable = '##SearchTmp' + replace(convert(nvarchar(100), getdate(), 114), ':', '')

	Set @Select = @SQLTopX + ' LinkID AS [ ], LinkID AS [_],
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CRS_Demographic.HospitalID, 0)) as [Hosp ID],
		(select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = CRS_Demographic.ChartNumber AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end)) as [Deceased],
		AA1 AS [Unique Register ID (AA1)],
		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'')  AS [Chart Number],
		ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''')  + '' '' + ISNULL(MiddleName, '''') AS [Full Name],
		CONVERT(VARCHAR(10), BirthDate, 111) AS [Birth Date],
		CONVERT(VARCHAR(10), AdmitDate, 111) AS [Date Stay Began],
		(SELECT (CASE WHEN Code = 14501 THEN ''0A'' ELSE DisplayCode END) FROM LU_CodeFile WHERE LookUpID = 47001 AND Code = AA8) AS [Assess Type]			
	into ' + @TempTable + ' FROM CRS_Demographic WHERE IsCurrent = 1 AND IsDeleted = 2 ' + @SearchPrefix + '
	AND (ChartNumber LIKE ''' + @SearchString + '%'' OR ChartNumber LIKE ''' + @SearchString2 +'%'') '

	insert into AU_Search Values (470, @SearchString, @UserID, GetDate(), 'Chart Number') --PR - 06295

IF @SearchType = 1
BEGIN
 	-- 01A: ADMIT BACK GROUND- 
	Set @SQL = @SQLTopX + ' PatientID AS [ ], PatientID AS [_],
			(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(C.HospitalID, 0)) as [Hosp ID],
			(case when DeathIndicator = 1 then ''Y'' else ''N'' end) as [Deceased],
			(SELECT TOP 1 AA1 FROM CRS_Demographic WHERE IsCurrent = 1 AND ChartNumber = C.ChartNumber ORDER BY AbstractID DESC) AS [Unique Register ID (AA1)],
			REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'')  AS [Chart Number],
			ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''')  + '' '' + ISNULL(MiddleName, '''') AS [Full Name],
			CONVERT(VARCHAR(10), BirthDate, 111) AS [Birth Date],
			--CONVERT(VARCHAR(10), AdmitDate, 111) AS [Date Stay Began],
			'' '' AS [Date Stay Began],
			(SELECT (CASE WHEN Code = 14501 THEN ''0A'' ELSE DisplayCode END) FROM LU_CodeFile WHERE LookUpID = 47001 AND Code = (SELECT TOP 1 AA8 FROM CRS_Demographic WHERE IsCurrent = 1 AND ChartNumber = C.ChartNumber ORDER BY AbstractID DESC)) AS [Assess Type]		
	into ' + @TempTable + ' FROM CM_CPI C
	WHERE IsDeleted = 2 ' + @SearchPrefix + '
	AND (ChartNumber LIKE ''' + @SearchString + '%'' OR ChartNumber LIKE ''' + @SearchString2 +'%'')
	AND C.ChartNumber NOT IN (SELECT ChartNumber FROM CRS_Demographic WHERE IsCurrent = 1 AND (AA8 <> 14507 AND AA8 <> 14508 AND AA8 <> 14509 and  AA8 <> 14500))
	AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end) 
	ORDER BY [Hosp ID], [Chart Number]'
END

ELSE IF @SearchType = 2
BEGIN
	-- 00: DEMO CHANGES
	Set @SQL = @SQLTopX + ' LinkID AS [ ],  LinkID AS [_],
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(D.HospitalID, 0)) as [Hosp ID],
		(select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = D.ChartNumber AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end)) as [Deceased],
		AA1 AS [Unique Register ID (AA1)],
		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'')  AS [Chart Number],
		ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''')  + '' '' + ISNULL(MiddleName, '''') AS [Full Name],
		CONVERT(VARCHAR(10), BirthDate, 111) AS [Birth Date],
		CONVERT(VARCHAR(10), AdmitDate, 111) AS [Date Stay Began],
		(SELECT (CASE WHEN Code = 14501 THEN ''0A'' ELSE DisplayCode END) FROM LU_CodeFile WHERE LookUpID = 47001 AND Code = (SELECT AA8 FROM CRS_Demographic WHERE LinkID = D.LinkID AND IsCurrent = 1 AND (ChartNumber LIKE ''' + @SearchString + '%'' OR ChartNumber LIKE ''' + @SearchString2 +'%''))) AS [Assess Type]		
	into ' + @TempTable + ' FROM CRS_Demographic D
	WHERE D.AA8 = 14501 AND ISNULL(IsSubmited, 0) = 1
	AND IsDeleted = 2 ' + @SearchPrefix + '
	AND (ChartNumber LIKE ''' + @SearchString + '%'' OR ChartNumber LIKE ''' + @SearchString2 +'%'')
	--AND ChartNumber IN (SELECT ChartNumber FROM CRS_Demographic WHERE IsCurrent = 1 AND (AA8 <> 14507 AND AA8 <> 14508 AND AA8 <> 14509))	
	--AND AA1 NOT IN (SELECT AA1 FROM CRS_Demographic WHERE (AA8 = 14500 AND ISNULL(IsSubmited, 2) <> 1))
	AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end) 
	ORDER BY [Hosp ID], [Chart Number]'	
	--print @sql
END

ELSE IF @SearchType = 3
BEGIN
	-- 01: ADMIT ASSESSMENT
    --Ticket ?
	--set @SQL = @Select + ' AND (IsCurrent = 1 AND (AA8 = 14500 OR AA8 = 14501 OR 
    --    (AA8 between 14507 and 14510 AND not exists (select * from CRS_Demographic c where c.LinkID = CRS_Demographic.LinkID and AA8 = 14501)))
	set @SQL = @Select + ' AND (IsCurrent = 1 AND (AA8 = 14500 OR AA8 = 14501 or (AA8 = 14510 and (select a.abstractid from crs_demographic a where a.linkid = CRS_Demographic.linkid and a.aa8 = 14502) is null ) ))
	AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end) 
	ORDER BY [Hosp ID], [Chart Number]'
END

ELSE IF @SearchType = 4
BEGIN
	-- 02: FULL ASSESS/ 03: FULL ASSESS CHANGE/ 05: QUARTER ASSESS/ 06: DISCH, NO RETURN/ 07: DISCH RETURN
	--PR - 05160 add update record 17 and project 18
	--set @SQL = @Select + ' AND (IsCurrent = 1 AND (AA8 = 14500 OR AA8 = 14502 OR AA8 = 14503 OR AA8 = 14504 OR AA8 = 14505 OR AA8 = 14506 OR AA8 = 14510 OR AA8 = 14511))
	set @SQL = @Select + ' AND (IsCurrent = 1 AND (AA8 in (14500, 14502, 14503, 14504, 14505, 14506, 14510, 14511, 203626, 203627)))
	AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end) 
	ORDER BY [Hosp ID], [Chart Number]'
END

ELSE IF @SearchType = 5
BEGIN
 	-- 04: FULL ASSESS CORRECT 
	--PR-02008
	--set @SQL = @Select + ' AND (IsCurrent = 1 AND (AA8 = 14502 OR AA8 = 14503 OR AA8 = 14504 OR AA8 = 14505))
	set @SQL = @Select + ' AND (IsCurrent = 1 AND (AA8 = 14502 OR AA8 = 14503 OR AA8 = 14504 OR AA8 = 14505 OR AA8 = 14507 OR AA8 = 14508 OR AA8 = 14509))
	AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end) 
	ORDER BY [Hosp ID], [Chart Number]'
END

ELSE IF @SearchType = 6
BEGIN
	-- 08: DISCH, NO ASSESSMENT
	set @SQL = @Select + ' AND (IsCurrent = 1 AND (AA8 = 14500 OR AA8 = 14501))
	AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end) 
	ORDER BY [Hosp ID], [Chart Number]'
END

ELSE IF @SearchType = 7
BEGIN
	-- 09: RE-ENTRY
    --PR - 03941
	--set @SQL = @Select + ' AND (IsCurrent = 1 AND (AA8 = 14508))  
	set @SQL = @Select + ' AND (IsCurrent = 1 AND (AA8 in (14507, 14508, 14509)))
	AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end) 
	ORDER BY [Hosp ID], [Chart Number]'
END

ELSE IF @SearchType = 8
BEGIN	
	-- 10: QUARTER CHANGES	
	--PR-02325
	--set @SQL = @Select + ' AND (IsCurrent = 1 AND (AA8 = 14506 OR AA8 = 14511))
	--PR-02325 - (This was a quick fix)
-- 	set @SQL = @Select + ' AND (IsCurrent = 1 AND (AA8 = 14506 OR AA8 = 14511 OR AA8 = 14507 OR AA8 = 14508 OR AA8 = 14509))
-- 	AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end) 
-- 	ORDER BY [Hosp ID], [Chart Number]'
	set @SQL = @Select + ' and ChartNumber in (select ChartNumber from CRS_Demographic where AA8 = 14506)
	AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end) 
	ORDER BY [Hosp ID], [Chart Number]'
END

ELSE IF @SearchType = 9 --ED-02133
BEGIN
	-- 17: UPDATE CHANGES
	Set @SQL = @SQLTopX + ' LinkID AS [ ],  LinkID AS [_],
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(D.HospitalID, 0)) as [Hosp ID],
		(select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = D.ChartNumber AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end)) as [Deceased],
		AA1 AS [Unique Register ID (AA1)],
		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'')  AS [Chart Number],
		ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''')  + '' '' + ISNULL(MiddleName, '''') AS [Full Name],
		CONVERT(VARCHAR(10), BirthDate, 111) AS [Birth Date],
		CONVERT(VARCHAR(10), AdmitDate, 111) AS [Date Stay Began],
		(SELECT (CASE WHEN Code = 14501 THEN ''0A'' ELSE DisplayCode END) FROM LU_CodeFile WHERE LookUpID = 47001 AND Code = (SELECT AA8 FROM CRS_Demographic WHERE LinkID = D.LinkID AND IsCurrent = 1 AND (ChartNumber LIKE ''' + @SearchString + '%'' OR ChartNumber LIKE ''' + @SearchString2 +'%''))) AS [Assess Type]		
	into ' + @TempTable + ' FROM CRS_Demographic D
	WHERE D.AA8 = 14501 AND ISNULL(IsSubmited, 0) = 1
	AND IsDeleted = 2 ' + @SearchPrefix + '
	AND (ChartNumber LIKE ''' + @SearchString + '%'' OR ChartNumber LIKE ''' + @SearchString2 +'%'')
	AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end) 
	ORDER BY [Hosp ID], [Chart Number]'	
END

--print @sql
	exec sp_executesql @sql

	If @ShowVip = '2'
	Begin
		set @SQL = 'delete ' + @TempTable + ' where [Chart Number] in (select replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') 
			from CM_CPI where isnull(secret, 0) = 1 and replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')
			in (select [Chart Number] from ' + @TempTable + '))'
		Exec(@SQL)
	End
	Set nocount off
		set @SQL = 'select * From ' + @TempTable
		exec(@SQL)
		set @SQL = 'drop table ' + @TempTable
		exec(@SQL)
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- Called by the New CCRS Record Form (Locates Chart to user in new record).
CREATE PROCEDURE [F_SearchCCRS_Chart_OLD]
	@SearchString as VarChar(50), 
	@SearchString2 as VarChar(50),
	@SearchType as Int
AS 

IF @SearchType = 1
BEGIN
 	-- 01A: ADMIT BACK GROUND- 
	SELECT DISTINCT PatientID AS [ ], PatientID AS [ ],
			' ' AS [Unique Register ID (AA1)],
			REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, ' ', '0')  AS [Chart Number],
			ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '')  + ' ' + ISNULL(MiddleName, '') AS [Full Name],
			CONVERT(VARCHAR(10), BirthDate, 111) AS [Birth Date],
			'' AS [Assess Type]			
	FROM CM_CPI 
	WHERE IsDeleted = 2
	AND (ChartNumber LIKE @SearchString + '%' OR ChartNumber LIKE @SearchString2 +'%')
	AND CM_CPI.ChartNumber NOT IN (SELECT ChartNumber FROM CRS_Demographic WHERE IsCurrent = 1 AND (AA8 <> 14507 AND AA8 <> 14508 AND AA8 <> 14509))
	ORDER BY [Chart Number]
END

ELSE IF @SearchType = 2
BEGIN
	-- 00: DEMO CHANGES
	SELECT DISTINCT CM_CPI.PatientID AS [ ], CRS_Demographic.LinkID AS [ ],
		CRS_Demographic.AA1 AS [Unique Register ID (AA1)],
		REPLACE(SPACE(10-LEN(CM_CPI.ChartNumber)) + CM_CPI.ChartNumber, ' ', '0')  AS [Chart Number],
		ISNULL(CM_CPI.LastName, '') + ', ' + ISNULL(CM_CPI.FirstName, '')  + ' ' + ISNULL(CM_CPI.MiddleName, '') AS [Full Name],
		CONVERT(VARCHAR(10), CM_CPI.BirthDate, 111) AS [Birth Date],
		'' AS [Assess Type]			
	FROM CM_CPI INNER JOIN CRS_Demographic ON dbo.CM_CPI.ChartNumber = dbo.CRS_Demographic.ChartNumber 
	WHERE CRS_Demographic.AA8 = 14501 AND ISNULL(IsSubmited, 0) = 1
	AND CM_CPI.IsDeleted = 2
	AND (CM_CPI.ChartNumber LIKE @SearchString + '%' OR CM_CPI.ChartNumber LIKE @SearchString2 +'%')
	AND CM_CPI.ChartNumber IN (SELECT ChartNumber FROM CRS_Demographic WHERE IsCurrent = 1 AND (AA8 <> 14507 AND AA8 <> 14508 AND AA8 <> 14509))
	ORDER BY [Chart Number]
END

ELSE IF @SearchType = 3
BEGIN
	-- 01: ADMIT ASSESSMENT
	SELECT DISTINCT CM_CPI.PatientID AS [ ], CRS_Demographic.LinkID AS [ ],
		CRS_Demographic.AA1 AS [Unique Register ID (AA1)],
		REPLACE(SPACE(10-LEN(CM_CPI.ChartNumber)) + CM_CPI.ChartNumber, ' ', '0')  AS [Chart Number],
		ISNULL(CM_CPI.LastName, '') + ', ' + ISNULL(CM_CPI.FirstName, '')  + ' ' + ISNULL(CM_CPI.MiddleName, '') AS [Full Name],
		CONVERT(VARCHAR(10), CM_CPI.BirthDate, 111) AS [Birth Date],
		(SELECT (CASE WHEN Code = 14501 THEN '0A' ELSE DisplayCode END) FROM LU_CodeFile WHERE LookUpID = 47001 AND Code = AA8) AS [Assess Type]			
	FROM CM_CPI INNER JOIN CRS_Demographic ON dbo.CM_CPI.ChartNumber = dbo.CRS_Demographic.ChartNumber 
	WHERE CRS_Demographic.IsCurrent = 1
	AND CM_CPI.IsDeleted = 2
	AND (CM_CPI.ChartNumber LIKE @SearchString + '%' OR CM_CPI.ChartNumber LIKE @SearchString2 +'%')
	AND CM_CPI.ChartNumber IN (SELECT ChartNumber FROM CRS_Demographic WHERE IsCurrent = 1 AND (AA8 = 14500 OR AA8 = 14501))
	ORDER BY [Chart Number]
END

ELSE IF @SearchType = 4
BEGIN
	-- 02: FULL ASSESS/ 03: FULL ASSESS CHANGE/ 05: QUARTER ASSESS/ 06: DISCH, NO RETURN/ 07: DISCH RETURN
	SELECT DISTINCT CM_CPI.PatientID AS [ ], CRS_Demographic.LinkID AS [ ],
		CRS_Demographic.AA1 AS [Unique Register ID (AA1)],
		REPLACE(SPACE(10-LEN(CM_CPI.ChartNumber)) + CM_CPI.ChartNumber, ' ', '0')  AS [Chart Number],
		ISNULL(CM_CPI.LastName, '') + ', ' + ISNULL(CM_CPI.FirstName, '')  + ' ' + ISNULL(CM_CPI.MiddleName, '') AS [Full Name],
		CONVERT(VARCHAR(10), CM_CPI.BirthDate, 111) AS [Birth Date],
		(SELECT (CASE WHEN Code = 14501 THEN '0A' ELSE DisplayCode END) FROM LU_CodeFile WHERE LookUpID = 47001 AND Code = AA8) AS [Assess Type]			
	FROM CM_CPI INNER JOIN CRS_Demographic ON dbo.CM_CPI.ChartNumber = dbo.CRS_Demographic.ChartNumber 
	WHERE CRS_Demographic.IsCurrent = 1
	AND CM_CPI.IsDeleted = 2
	AND (CM_CPI.ChartNumber LIKE @SearchString + '%' OR CM_CPI.ChartNumber LIKE @SearchString2 +'%')
	AND CM_CPI.ChartNumber IN (SELECT ChartNumber FROM CRS_Demographic WHERE IsCurrent = 1 AND (AA8 = 14502 OR AA8 = 14503 OR AA8 = 14504 OR AA8 = 14505 OR AA8 = 14506 OR AA8 = 14510 OR AA8 = 14511))
	ORDER BY [Chart Number]
END

ELSE IF @SearchType = 5
BEGIN
 	-- 04: FULL ASSESS CORRECT 
	SELECT DISTINCT CM_CPI.PatientID AS [ ], CRS_Demographic.LinkID AS [ ],
		CRS_Demographic.AA1 AS [Unique Register ID (AA1)],
		REPLACE(SPACE(10-LEN(CM_CPI.ChartNumber)) + CM_CPI.ChartNumber, ' ', '0')  AS [Chart Number],
		ISNULL(CM_CPI.LastName, '') + ', ' + ISNULL(CM_CPI.FirstName, '')  + ' ' + ISNULL(CM_CPI.MiddleName, '') AS [Full Name],
		CONVERT(VARCHAR(10), CM_CPI.BirthDate, 111) AS [Birth Date],
		(SELECT (CASE WHEN Code = 14501 THEN '0A' ELSE DisplayCode END) FROM LU_CodeFile WHERE LookUpID = 47001 AND Code = AA8) AS [Assess Type]
	FROM CM_CPI INNER JOIN CRS_Demographic ON dbo.CM_CPI.ChartNumber = dbo.CRS_Demographic.ChartNumber 
	WHERE CRS_Demographic.IsCurrent = 1
	AND CM_CPI.IsDeleted = 2
	AND (CM_CPI.ChartNumber LIKE @SearchString + '%' OR CM_CPI.ChartNumber LIKE @SearchString2 +'%')
	AND CM_CPI.ChartNumber IN (SELECT ChartNumber FROM CRS_Demographic WHERE IsCurrent = 1 AND (AA8 = 14502 OR AA8 = 14503 OR AA8 = 14504 OR AA8 = 14505))
	ORDER BY [Chart Number]
END

ELSE IF @SearchType = 6
BEGIN
	-- 08: DISCH, NO ASSESSMENT
	SELECT DISTINCT CM_CPI.PatientID AS [ ], CRS_Demographic.LinkID AS [ ],
		CRS_Demographic.AA1 AS [Unique Register ID (AA1)],
		REPLACE(SPACE(10-LEN(CM_CPI.ChartNumber)) + CM_CPI.ChartNumber, ' ', '0')  AS [Chart Number],
		ISNULL(CM_CPI.LastName, '') + ', ' + ISNULL(CM_CPI.FirstName, '')  + ' ' + ISNULL(CM_CPI.MiddleName, '') AS [Full Name],
		CONVERT(VARCHAR(10), CM_CPI.BirthDate, 111) AS [Birth Date],
		(SELECT (CASE WHEN Code = 14501 THEN '0A' ELSE DisplayCode END) FROM LU_CodeFile WHERE LookUpID = 47001 AND Code = AA8) AS [Assess Type]			
	FROM CM_CPI INNER JOIN CRS_Demographic ON dbo.CM_CPI.ChartNumber = dbo.CRS_Demographic.ChartNumber 
	WHERE CRS_Demographic.IsCurrent = 1
	AND CM_CPI.IsDeleted = 2
	AND (CM_CPI.ChartNumber LIKE @SearchString + '%' OR CM_CPI.ChartNumber LIKE @SearchString2 +'%')
	AND CM_CPI.ChartNumber IN (SELECT ChartNumber FROM CRS_Demographic WHERE IsCurrent = 1 AND (AA8 = 14500 OR AA8 = 14501))
	ORDER BY [Chart Number]
END

ELSE IF @SearchType = 7
BEGIN
	-- 09: RE-ENTRY
	SELECT DISTINCT CM_CPI.PatientID AS [ ], CRS_Demographic.LinkID AS [ ],
		CRS_Demographic.AA1 AS [Unique Register ID (AA1)],
		REPLACE(SPACE(10-LEN(CM_CPI.ChartNumber)) + CM_CPI.ChartNumber, ' ', '0')  AS [Chart Number],
		ISNULL(CM_CPI.LastName, '') + ', ' + ISNULL(CM_CPI.FirstName, '')  + ' ' + ISNULL(CM_CPI.MiddleName, '') AS [Full Name],
		CONVERT(VARCHAR(10), CM_CPI.BirthDate, 111) AS [Birth Date],
		(SELECT (CASE WHEN Code = 14501 THEN '0A' ELSE DisplayCode END) FROM LU_CodeFile WHERE LookUpID = 47001 AND Code = AA8) AS [Assess Type]			
	FROM CM_CPI INNER JOIN CRS_Demographic ON dbo.CM_CPI.ChartNumber = dbo.CRS_Demographic.ChartNumber 
	WHERE CRS_Demographic.IsCurrent = 1
	AND CM_CPI.IsDeleted = 2
	AND (CM_CPI.ChartNumber LIKE @SearchString + '%' OR CM_CPI.ChartNumber LIKE @SearchString2 +'%')
	AND CM_CPI.ChartNumber IN (SELECT ChartNumber FROM CRS_Demographic WHERE IsCurrent = 1 AND (AA8 = 14508))
	ORDER BY [Chart Number]
END

ELSE IF @SearchType = 8
BEGIN	
	-- 10: QUARTER CHANGES	
	SELECT DISTINCT CM_CPI.PatientID AS [ ], CRS_Demographic.LinkID AS [ ],
		CRS_Demographic.AA1 AS [Unique Register ID (AA1)],
		REPLACE(SPACE(10-LEN(CM_CPI.ChartNumber)) + CM_CPI.ChartNumber, ' ', '0')  AS [Chart Number],
		ISNULL(CM_CPI.LastName, '') + ', ' + ISNULL(CM_CPI.FirstName, '')  + ' ' + ISNULL(CM_CPI.MiddleName, '') AS [Full Name],
		CONVERT(VARCHAR(10), CM_CPI.BirthDate, 111) AS [Birth Date],
		(SELECT (CASE WHEN Code = 14501 THEN '0A' ELSE DisplayCode END) FROM LU_CodeFile WHERE LookUpID = 47001 AND Code = AA8) AS [Assess Type]			
	FROM CM_CPI INNER JOIN CRS_Demographic ON dbo.CM_CPI.ChartNumber = dbo.CRS_Demographic.ChartNumber 
	WHERE CRS_Demographic.IsCurrent = 1
	AND CM_CPI.IsDeleted = 2
	AND (CM_CPI.ChartNumber LIKE @SearchString + '%' OR CM_CPI.ChartNumber LIKE @SearchString2 +'%')
	AND CM_CPI.ChartNumber IN (SELECT ChartNumber FROM CRS_Demographic WHERE IsCurrent = 1 AND (AA8 = 14506 OR AA8 = 14511))
	ORDER BY [Chart Number]
END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Called by the CPI Search Form 
CREATE PROCEDURE [F_SearchChart]
	@AppID as int,
	@FKey as int,
	@SearchString as VarChar(50),
	@SearchString2 as VarChar(50),
	@UserID as int = 1,
	@Exact as int = 0,
	@LogID as int = 0,
	@HospID as varchar(100) = '0',
	@ExtraSearch 	[varchar](1000) = ''
AS 

--NP--00025 - 		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CM_CPI.HospitalID, 0)) as [Hosp ID],

Set nocount on
DECLARE @SQL nVarChar(4000)
DECLARE @DataType int
DECLARE @LookupTable NVarChar(50)
DECLARE @FieldName as NVarChar(50)
DECLARE @NameSplit as int
DECLARE @FieldDescription as NVarChar(50)
DECLARE @Temp as datetime

--13507: Moved to top	
Set @SearchString = replace(@SearchString, '''', '''''')
Set @SearchString2 = replace(@SearchString2, '''', '''''')

	SELECT @DataType = (SELECT DataType FROM U_UsersFields  WHERE AppID = @AppID AND FieldID = @FKey and UserID = @UserID)
	SELECT @LookupTable = (SELECT LookUpTable FROM U_UsersFields  WHERE AppID = @AppID AND FieldID = @FKey and UserID = @UserID)
	SELECT @FieldName = (SELECT SystemName FROM U_Fields  WHERE FieldID = @FKey)
	SELECT @NameSplit = CHARINDEX(',', @SearchString) 
	SELECT @FieldDescription = (SELECT isnull(Header_User, @FieldName) FROM U_UsersFields  WHERE AppID = @AppID AND FieldID = @FKey and UserID = @UserID)
	insert into AU_Search Values (@AppID, @SearchString, @LogID, GetDate(), @FieldDescription)
--Chart Audits, Prefixs, VIP and Top X parameters
	Declare @SearchPrefix as NVarChar(200)  --2.x-0101 expend to 200 from 50
	Declare @SearchPrefix_Org as NVarChar(200) --PR - 05450
	Declare @ShowVip as NVarChar(1)
	Declare @TopX as NVarChar(3)
	Declare @SearchAudit as int
	Declare @SQLTopX as NVarChar(20)
	Select @SearchPrefix = isnull(searchchartprefix, ''), @ShowVip = isnull(showvip, 0) from u_users where code = @UserID
	set @SearchPrefix_Org = @SearchPrefix   --PR - 05450

	If @SearchPrefix <> ''
	    --2.x-0010 Allow still birth prefix, X, Y, Z
		--Set @SearchPrefix = ' and Chartnumber like ''' + @SearchPrefix + '%'' '
		Set @SearchPrefix = ' and (Chartnumber like ''' + @SearchPrefix + '%'' or Chartnumber like ''Z' + @SearchPrefix + '%'' or Chartnumber like ''Y' + @SearchPrefix + '%'' or Chartnumber like ''X' + @SearchPrefix + '%'') '

	If @HospID = '0'
		Select top 1 @TopX = isnull(TopSearch, '999'), @SearchAudit = EnableSearchAudit  FROM H_HospitalProfile 
	else	
		Select top 1 @TopX = isnull(TopSearch, '999'), @SearchAudit = EnableSearchAudit  FROM H_HospitalProfile where isnull(Code, 0) = @HospID
	Set @SQLTopX = 'Select top ' + @TopX + ' ' 
	SET @NameSplit = CHARINDEX(',', @SearchString) 
	Declare @TempTable as NVarChar(100)
	set @TempTable = '##SearchTmp' + replace(convert(nvarchar(100), getdate(), 114), ':', '')
	DECLARE @FieldDesc   NVarChar(150)
	SELECT @FieldDesc   = InHouseDesc FROM U_Fields  WHERE FieldID = @FKey
	--insert into AU_Search Values (@AppID, @SearchString, @LogID, GetDate(), @FieldDesc)


	--EN-00043
   if @FKey = 45006 -- TERMINAL DIGIT SORT
    begin
 	declare @order  NVarChar(500)

-- 	declare @TDigit as varchar(10)
-- 	declare @TDigitR as varchar(10)
-- 	declare @TDigitH as varchar(10)
-- 
-- 	select @TDigitR = TerminalDigit from H_RegionProfile
-- 	if @HospID = '0' 
-- 		select top 1 @TDigitH = TerminalDigit from H_HospitalProfile 
-- 	else
-- 		select top 1 @TDigitH = TerminalDigit from H_HospitalProfile where HospitalID = @HospID
-- 	
-- 	set @TDigit = @TDigitR
-- 	if len(@TDigitH) <> 0 and isnull(@TDigitH, '0') <> '0' set @TDigit = @TDigitH
-- 	--set @TDigit = '926315'
-- 	
-- 	declare @Pos1 as varchar(1)
-- 	declare @Len1 as varchar(1)
-- 	declare @Pos2 as varchar(1)
-- 	declare @Len2 as varchar(1)
-- 	declare @Pos3 as varchar(1)
-- 	declare @Len3 as varchar(1)
-- 	declare @Pos4 as varchar(1)
-- 	declare @Len4 as varchar(1)
-- 	declare @Pos5 as varchar(1)
-- 	declare @Len5 as varchar(1)
-- 
-- 	declare @OrdT as varchar(400)
-- 
-- 	if isnumeric(substring(@TDigit, 1, 1)) = 1 
-- 		set @Pos1 = substring(@TDigit, 1, 1)
-- 	if isnumeric(substring(@TDigit, 2, 1)) = 1 
-- 		set @Len1 = substring(@TDigit, 2, 1)
-- 	if isnumeric(substring(@TDigit, 3, 1)) = 1 
-- 		set @Pos2 = substring(@TDigit, 3, 1)
-- 	if isnumeric(substring(@TDigit, 4, 1)) = 1 
-- 		set @Len2 = substring(@TDigit, 4, 1)
-- 	if isnumeric(substring(@TDigit, 5, 1)) = 1 
-- 		set @Pos3 = substring(@TDigit, 5, 1)
-- 	if isnumeric(substring(@TDigit, 6, 1)) = 1 
-- 		set @Len3 = substring(@TDigit, 6, 1)
-- 	if isnumeric(substring(@TDigit, 7, 1)) = 1 
-- 		set @Pos4 = substring(@TDigit, 7, 1)
-- 	if isnumeric(substring(@TDigit, 8, 1)) = 1 
-- 		set @Len4 = substring(@TDigit, 8, 1)
-- 	if isnumeric(substring(@TDigit, 9, 1)) = 1 
-- 		set @Pos5 = substring(@TDigit, 9, 1)
-- 	if isnumeric(substring(@TDigit, 10, 1)) = 1 
-- 		set @Len5 = substring(@TDigit, 10, 1)
-- 
-- -- 	if len(@Pos1) <> 0 and len(@Len1) <> 0
-- -- 		set @OrdT = ' substring(replace(space(10-len([Chart #])) + [Chart #], '' '', ''0''), ' + @Pos1 + ', ' + @Len1 + '), '
-- -- 		
-- -- 	if len(@Pos2) <> 0 and len(@Len2) <> 0
-- -- 		set @OrdT = @OrdT + ' substring(replace(space(10-len([Chart #])) + [Chart #], '' '', ''0''), ' + @Pos2 + ', ' + @Len2 + '), '
-- -- 
-- -- 	if len(@Pos3) <> 0 and len(@Len3) <> 0
-- -- 		set @OrdT = @OrdT + ' substring(replace(space(10-len([Chart #])) + [Chart #], '' '', ''0''), ' + @Pos3 + ', ' + @Len3 + '), '
-- -- 
-- -- 	if len(@Pos4) <> 0 and len(@Len4) <> 0
-- -- 		set @OrdT = @OrdT + ' substring(replace(space(10-len([Chart #])) + [Chart #], '' '', ''0''), ' + @Pos4 + ', ' + @Len4 + '), '
-- -- 
-- -- 	if len(@Pos5) <> 0 and len(@Len5) <> 0
-- -- 		set @OrdT = @OrdT + ' substring(replace(space(10-len([Chart #])) + [Chart #], '' '', ''0''), ' + @Pos5 + ', ' + @Len5 + '), '
-- 
-- 	if len(@Pos1) <> 0 and len(@Len1) <> 0
-- 		set @OrdT = ' substring(replace(space(10-len([ChartNumber])) + [ChartNumber], '' '', ''0''), ' + @Pos1 + ', ' + @Len1 + '), '
-- 		
-- 	if len(@Pos2) <> 0 and len(@Len2) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len([ChartNumber])) + [ChartNumber], '' '', ''0''), ' + @Pos2 + ', ' + @Len2 + '), '
-- 
-- 	if len(@Pos3) <> 0 and len(@Len3) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len([ChartNumber])) + [ChartNumber], '' '', ''0''), ' + @Pos3 + ', ' + @Len3 + '), '
-- 
-- 	if len(@Pos4) <> 0 and len(@Len4) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len([ChartNumber])) + [ChartNumber], '' '', ''0''), ' + @Pos4 + ', ' + @Len4 + '), '
-- 
-- 	if len(@Pos5) <> 0 and len(@Len5) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len([ChartNumber])) + [ChartNumber], '' '', ''0''), ' + @Pos5 + ', ' + @Len5 + '), '
-- 
-- 	if len(@OrdT) <> 0 
-- 		set @OrdT = left(@OrdT, len(@OrdT) - 1)
-- 
-- 	set @SQL = @SQLTopX + ' PatientID as [ ], 
-- 		case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
-- 		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #],
-- 		ISNULL(LastName, '''') + '', '' + 
-- 		ISNULL(FirstName, '''') + '' '' + 
-- 		ISNULL(MiddleName, '''') AS [Full Name],
-- 		dbo.LU_Gender_I.DisplayCode AS [Gender], 
-- 		CONVERT (VarChar(10), BirthDate, 111) AS [Birth Date] 
-- 		into ' + @TempTable + '  FROM dbo.CM_CPI 			
-- 		LEFT JOIN dbo.LU_Gender_I 
-- 		ON dbo.CM_CPI.Gender = dbo.LU_Gender_I.Code 
-- 		WHERE  (ChartNumber LIKE ''' + @SearchString + '%'' OR ChartNumber LIKE ''' + @SearchString2 +'%'')
-- 		AND IsDeleted = 2' + @SearchPrefix + '
-- 		AND (ISNULL(CM_CPI.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(CM_CPI.HospitalID, 0) end) '
-- 		+ @ExtraSearch 
-- 
-- 	set @order = ''
-- 	if len(@OrdT) <> 0 
-- 	        set @order = ' order by ' + @OrdT
-- 
    --PR - 04434 set the search field in the first column
	set @SQL = @SQLTopX + ' PatientID as [ ], 
		(select top 1 TerminalChart from CM_Terminal where PatientID = CM_CPI.PatientID) as [SearchItem#], 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CM_CPI.HospitalID, 0)) as [Hosp ID],
		case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #],
		ISNULL(LastName, '''') + '', '' + 
		ISNULL(FirstName, '''') + '' '' + 
		ISNULL(MiddleName, '''') AS [Full Name],
		dbo.LU_Gender_I.DisplayCode AS [Gender], 
		CONVERT (VarChar(10), BirthDate, 111) AS [Birth Date] 
		into ' + @TempTable + '  FROM dbo.CM_CPI 			
		LEFT JOIN dbo.LU_Gender_I 
		ON dbo.CM_CPI.Gender = dbo.LU_Gender_I.Code 
		where PatientID in (select PatientID from CM_Terminal where TerminalChart Like ''' + @SearchString + '%'' or MaskTerminal Like ''' + @SearchString + '%'')
		AND IsDeleted = 2' + @SearchPrefix + '
		AND (ISNULL(CM_CPI.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(CM_CPI.HospitalID, 0) end) '
		+ @ExtraSearch 

	set @order = ' order by [Hosp ID], (select TerminalChart from CM_Terminal where PatientID = CM_CPI.PatientID) '
	set @sql = @sql + @order
	--print @sql 
        exec sp_executesql @sql 
        set @FieldDescription = 'Terminal #'
    end

else IF @FieldName = 'ChartNumber' 
BEGIN
    --PR - 05450
    if len(@SearchPrefix_Org) > 0 and len(isnull(@SearchString, '')) > 0
    begin
        if charindex(@SearchPrefix_Org, @SearchString) <> 1
        begin
            set @SearchString = @SearchPrefix_Org + @SearchString
        end
    end
	IF @Exact = 0
		SELECT @SQL = @SQLTopX + ' PatientID as [ ], 
			ChartNumber AS [SearchItem#],
			(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CM_CPI.HospitalID, 0)) as [Hosp ID],
			case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
			REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #],
			ISNULL(LastName, '''') + '', '' + 
			ISNULL(FirstName, '''') + '' '' + 
			ISNULL(MiddleName, '''') AS [Full Name],
			dbo.LU_Gender_I.DisplayCode AS [Gender], 
			CONVERT (VarChar(10), BirthDate, 111) AS [Birth Date] 
			into ' + @TempTable + '  FROM dbo.CM_CPI 			
			LEFT JOIN dbo.LU_Gender_I 
			ON dbo.CM_CPI.Gender = dbo.LU_Gender_I.Code 
			WHERE (ChartNumber LIKE ''' + @SearchString + '%'' OR ChartNumber LIKE ''Z' + @SearchString + '%'' OR ChartNumber LIKE ''Y' + @SearchString + '%'' OR ChartNumber LIKE ''X' + @SearchString + '%'' OR ChartNumber LIKE ''' + @SearchString2 +'%'')
			AND IsDeleted = 2' + @SearchPrefix + '
			AND (ISNULL(CM_CPI.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(CM_CPI.HospitalID, 0) end) '
			+ @ExtraSearch + '
			ORDER BY [Hosp ID], [Chart #] DESC'
	ELSE
		SELECT @SQL = @SQLTopX + ' PatientID as [ ], 
			ChartNumber AS [SearchItem#],
			(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CM_CPI.HospitalID, 0)) as [Hosp ID],
			case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
			REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #],
			ISNULL(LastName, '''') + '', '' + 
			ISNULL(FirstName, '''') + '' '' + 
			ISNULL(MiddleName, '''') AS [Full Name],
			dbo.LU_Gender_I.DisplayCode AS [Gender], 
			CONVERT (VarChar(10), BirthDate, 111) AS [Birth Date] 
			into ' + @TempTable + '  FROM dbo.CM_CPI 			
			LEFT JOIN dbo.LU_Gender_I 
			ON dbo.CM_CPI.Gender = dbo.LU_Gender_I.Code 
			WHERE  (ChartNumber = ''' + @SearchString + ''' OR ChartNumber = ''Z' + @SearchString + ''' OR ChartNumber = ''Y' + @SearchString + ''' OR ChartNumber = ''X' + @SearchString + ''' OR ChartNumber = ''' + @SearchString2 +''')
			AND IsDeleted = 2' + @SearchPrefix + '
			AND (ISNULL(CM_CPI.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(CM_CPI.HospitalID, 0) end) '
			+ @ExtraSearch + '
			ORDER BY [Hosp ID], [Chart #] DESC'

	--print @sql			
	exec sp_executesql @sql
END

--12821
else IF @FieldName = 'MasterChart' 
BEGIN
	--PR - 05566:  
	IF @Exact = 0
		SELECT @SQL = @SQLTopX + ' PatientID as [ ], 
       		(select top 1 replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') from CM_CPI C2 where C2.PatientID = C1.MasterChart) AS [SearchItem#],
			(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(C1.HospitalID, 0)) as [Hosp ID],
			case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
			REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #],
			ISNULL(LastName, '''') + '', '' + 
			ISNULL(FirstName, '''') + '' '' + 
			ISNULL(MiddleName, '''') AS [Full Name],
			dbo.LU_Gender_I.DisplayCode AS [Gender], 
			CONVERT (VarChar(10), BirthDate, 111) AS [Birth Date] 
			into ' + @TempTable + '  FROM dbo.CM_CPI C1			
			LEFT JOIN dbo.LU_Gender_I 
			ON C1.Gender = dbo.LU_Gender_I.Code 
            where C1.MasterChart in (select PatientID from CM_CPI where ChartNumber LIKE ''' + @SearchString + '%'' OR ChartNumber LIKE ''' + @SearchString2 +'%'')
			AND IsDeleted = 2' + @SearchPrefix + '
			AND (ISNULL(C1.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(C1.HospitalID, 0) end) '
			+ @ExtraSearch + '
			ORDER BY [Hosp ID], [SearchItem#] DESC'

	ELSE
		SELECT @SQL = @SQLTopX + ' PatientID as [ ], 
       		(select top 1 replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') from CM_CPI C2 where C2.PatientID = C1.MasterChart) AS [SearchItem#],
			(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(C1.HospitalID, 0)) as [Hosp ID],
			case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
			REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #],
			ISNULL(LastName, '''') + '', '' + 
			ISNULL(FirstName, '''') + '' '' + 
			ISNULL(MiddleName, '''') AS [Full Name],
			dbo.LU_Gender_I.DisplayCode AS [Gender], 
			CONVERT (VarChar(10), BirthDate, 111) AS [Birth Date] 
			into ' + @TempTable + '  FROM dbo.CM_CPI C1			
			LEFT JOIN dbo.LU_Gender_I 
			ON C1.Gender = dbo.LU_Gender_I.Code 
            where C1.MasterChart in (select PatientID from CM_CPI where ChartNumber = ''' + @SearchString + ''' OR ChartNumber = ''' + @SearchString2 +''')
			AND IsDeleted = 2' + @SearchPrefix + '
			AND (ISNULL(C1.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(C1.HospitalID, 0) end) '
			+ @ExtraSearch + '
			ORDER BY [Hosp ID], [SearchItem#] DESC'
	--print @sql		
	exec sp_executesql @sql
END
ELSE IF @FieldName = 'BirthDate' 
BEGIN

	--EN-00081
	if right(@SearchString, 5) = '00/00' 
	Begin
		SELECT @SQL = @SQLTopX + ' PatientID as [ ], 
			CONVERT (VarChar(10), BirthDate, 111) AS [SearchItem#],
			(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CM_CPI.HospitalID, 0)) as [Hosp ID],
			case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
			REPLACE(SPACE(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #] ,
			ISNULL(LastName, '''') + '', '' + 
			ISNULL(FirstName, '''') + '' '' + 
			ISNULL(MiddleName, '''') AS [Full Name],
			dbo.LU_Gender_I.DisplayCode AS [Gender],
			CONVERT (VarChar(10), BirthDate, 111) AS [Birth Date]
	 		into ' + @TempTable + '  FROM dbo.CM_CPI LEFT JOIN dbo.LU_Gender_I 
		            ON dbo.CM_CPI.Gender = dbo.LU_Gender_I.Code
			WHERE (Birthdate >= Convert(DateTime, ''' + left(@SearchString, 5) + '01/01'') and BirthDate  <= convert(DateTime, ''' + left(@SearchString, 5) + '12/31'')) 
			AND IsDeleted = 2 ' + @SearchPrefix + ' 
			AND (ISNULL(CM_CPI.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(CM_CPI.HospitalID, 0) end)  '
			+ @ExtraSearch + '
			ORDER BY [Hosp ID], Birthdate'
	END
       	Else if right(@SearchString, 2) = '00' 
	Begin
		SELECT @SQL = @SQLTopX + ' PatientID as [ ], 
			CONVERT (VarChar(10), BirthDate, 111) AS [SearchItem#],
			(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CM_CPI.HospitalID, 0)) as [Hosp ID],
			case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
			ISNULL(LastName, '''') + '', '' + 
			ISNULL(FirstName, '''') + '' '' + 
			ISNULL(MiddleName, '''') AS [Full Name],
			REPLACE(SPACE(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #] ,
			dbo.LU_Gender_I.DisplayCode AS [Gender],
			CONVERT (VarChar(10), BirthDate, 111) AS [Birth Date]
	 		into ' + @TempTable + '  FROM dbo.CM_CPI LEFT JOIN dbo.LU_Gender_I 
		            ON dbo.CM_CPI.Gender = dbo.LU_Gender_I.Code
			WHERE (Birthdate >= Convert(DateTime, ''' + left(@SearchString, 8) + '01'') and BirthDate  < dateadd(M, 1, Convert(DateTime, ''' + left(@SearchString, 8) + '01''))) 
			AND IsDeleted = 2 ' + @SearchPrefix + ' 
			AND (ISNULL(CM_CPI.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(CM_CPI.HospitalID, 0) end)  '
			+ @ExtraSearch + '
			ORDER BY [Hosp ID], Birthdate'
	END
       	Else 
	BEGIN
		if (isdate(@SearchString) = 0)  set @SearchString = '1950/01/01'

		SELECT @SQL = @SQLTopX + ' PatientID as [ ], 
			CONVERT (VarChar(10), BirthDate, 111) AS [SearchItem#],
			(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CM_CPI.HospitalID, 0)) as [Hosp ID],
			case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
			ISNULL(LastName, '''') + '', '' + 
			ISNULL(FirstName, '''') + '' '' + 
			ISNULL(MiddleName, '''') AS [Full Name],
			REPLACE(SPACE(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #] ,
			dbo.LU_Gender_I.DisplayCode AS [Gender],
			CONVERT (VarChar(10), BirthDate, 111) AS [Birth Date]
	 		into ' + @TempTable + '  FROM dbo.CM_CPI LEFT JOIN dbo.LU_Gender_I 
		            ON dbo.CM_CPI.Gender = dbo.LU_Gender_I.Code
			WHERE (Birthdate  = Convert(DateTime, ''' + @SearchString + '''))
			AND IsDeleted = 2 ' + @SearchPrefix + ' 
			AND (ISNULL(CM_CPI.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(CM_CPI.HospitalID, 0) end) '
			+ @ExtraSearch + '
			ORDER BY [Hosp ID], BirthDate' 
	END

	exec sp_executesql @sql
END

ELSE IF @FieldName = 'LastName' AND @NameSplit = 0 and @Exact = 0 --EN-00141
BEGIN
	--13507: Moved to top	
	--Set @SearchString = replace(@SearchString, '''', '''''')
	SELECT @SQL = @SQLTopX + ' cm_cpi.PatientID AS [ ], 
        LastName as [SearchItem#],
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CM_CPI.HospitalID, 0)) as [Hosp ID],
		case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #],
		ISNULL(LastName, '''') + '', '' + 
		ISNULL(FirstName, '''') + '' '' + 
		ISNULL(MiddleName, '''') AS [Full Name],
		dbo.LU_Gender_I.DisplayCode AS [Gender], 
		CONVERT (VarChar(10), BirthDate, 111) AS [Birth Date] 
		into ' + @TempTable + '  FROM dbo.CM_CPI --LEFT OUTER JOIN dbo.CM_Alias ON dbo.CM_CPI.PatientID = dbo.CM_Alias.PatientID
		LEFT JOIN dbo.LU_Gender_I 
		ON dbo.CM_CPI.Gender = dbo.LU_Gender_I.Code 
		WHERE (LastName Like ''' + ltrim(@SearchString) + '%'') -- or LastAlias Like ''' + ltrim(@SearchString) + '%'')
		AND IsDeleted = 2' + @SearchPrefix + ' 
		AND (ISNULL(CM_CPI.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(CM_CPI.HospitalID, 0) end) '
		+ @ExtraSearch + '
		ORDER BY [Hosp ID], LastName DESC, FirstName'
	exec sp_executesql @sql
END
ELSE IF @FieldName = 'LastName' AND @NameSplit > 0 and @Exact = 0 --EN-00141
BEGIN
	--13507: Moved to top	
	--Set @SearchString = replace(@SearchString, '''', '''''')
	Set @NameSplit = CHARINDEX(',', @SearchString) 
	SELECT @SQL = @SQLTopX + ' PatientID AS [ ], 
        LastName as [SearchItem#],
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CM_CPI.HospitalID, 0)) as [Hosp ID],
		case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
		REPLACE(SPACE(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #] ,
		ISNULL(LastName, '''') + '', '' + 
		ISNULL(FirstName, '''') + '' '' + 
		ISNULL(MiddleName, '''') AS [Full Name],
		dbo.LU_Gender_I.DisplayCode AS [Gender], 
		CONVERT (VarChar(10), BirthDate, 111) AS [Birth Date] 
		into ' + @TempTable + '  FROM dbo.CM_CPI 			
		LEFT JOIN dbo.LU_Gender_I 
		ON dbo.CM_CPI.Gender = dbo.LU_Gender_I.Code 
		WHERE LastName LIKE ''' + ltrim(Left(@SearchString, @NameSplit-1)) + '%'' 
		AND FirstName LIKE ''' + ltrim(Stuff(@SearchString,1, @NameSplit, '')) + '%'' 
		AND IsDeleted = 2' + @SearchPrefix + ' 
		AND (ISNULL(CM_CPI.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(CM_CPI.HospitalID, 0) end) '
		+ @ExtraSearch + '
		ORDER BY [Hosp ID], LastName DESC, FirstName'
	--print @sql
	exec sp_executesql @sql
END


ELSE IF @FieldName = 'LastName' AND @NameSplit = 0 and @Exact = 1 --EN-00141
BEGIN
	--13507: Moved to top	
	--Set @SearchString = replace(@SearchString, '''', '''''')
	SELECT @SQL = @SQLTopX + ' cm_cpi.PatientID AS [ ], 
        LastName as [SearchItem#],
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CM_CPI.HospitalID, 0)) as [Hosp ID],
		case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #],
		ISNULL(LastName, '''') + '', '' + 
		ISNULL(FirstName, '''') + '' '' + 
		ISNULL(MiddleName, '''') AS [Full Name],
		dbo.LU_Gender_I.DisplayCode AS [Gender], 
		CONVERT (VarChar(10), BirthDate, 111) AS [Birth Date] 
		into ' + @TempTable + '  FROM dbo.CM_CPI LEFT OUTER JOIN dbo.CM_Alias ON dbo.CM_CPI.PatientID = dbo.CM_Alias.PatientID
		LEFT JOIN dbo.LU_Gender_I ON dbo.CM_CPI.Gender = dbo.LU_Gender_I.Code 
		WHERE (LastName Like ''' + ltrim(@SearchString) + '%'' or LastAlias Like ''' + ltrim(@SearchString) + '%'')
		AND IsDeleted = 2' + @SearchPrefix + ' 
		AND (ISNULL(CM_CPI.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(CM_CPI.HospitalID, 0) end) '
		+ @ExtraSearch + '
		ORDER BY [Hosp ID], LastName DESC, FirstName'
	exec sp_executesql @sql
END
ELSE IF @FieldName = 'LastName' AND @NameSplit > 0 and @Exact = 1 --EN-00141
BEGIN
	--13507: Moved to top	
	--Set @SearchString = replace(@SearchString, '''', '''''')
	Set @NameSplit = CHARINDEX(',', @SearchString) 
	SELECT @SQL = @SQLTopX + ' cm_cpi.PatientID AS [ ], 
        LastName as [SearchItem#],
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CM_CPI.HospitalID, 0)) as [Hosp ID],
		case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
		REPLACE(SPACE(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #] ,
		ISNULL(LastName, '''') + '', '' + 
		ISNULL(FirstName, '''') + '' '' + 
		ISNULL(MiddleName, '''') AS [Full Name],
		dbo.LU_Gender_I.DisplayCode AS [Gender], 
		CONVERT (VarChar(10), BirthDate, 111) AS [Birth Date] 
		into ' + @TempTable + '  FROM dbo.CM_CPI LEFT OUTER JOIN dbo.CM_Alias ON dbo.CM_CPI.PatientID = dbo.CM_Alias.PatientID
		LEFT JOIN dbo.LU_Gender_I 
		ON dbo.CM_CPI.Gender = dbo.LU_Gender_I.Code 
		WHERE ((LastName LIKE ''' + ltrim(Left(@SearchString, @NameSplit-1)) + '%'' 
		AND FirstName LIKE ''' + ltrim(Stuff(@SearchString,1, @NameSplit, '')) + '%'') 
		or (LastAlias LIKE ''' + ltrim(Left(@SearchString, @NameSplit-1)) + '%'' 
 		AND FirstAlias LIKE ''' + ltrim(Stuff(@SearchString,1, @NameSplit, '')) + '%''))
		AND IsDeleted = 2' + @SearchPrefix + ' 
		AND (ISNULL(CM_CPI.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(CM_CPI.HospitalID, 0) end) '
		+ @ExtraSearch + '
		ORDER BY [Hosp ID], LastName DESC, FirstName'

	--print @sql
	exec sp_executesql @sql
END
--Commet it out because this is not approved.
-- ELSE IF @FieldName = 'LastAlias' AND @NameSplit = 0
-- BEGIN
--  	Set @SearchString = replace(@SearchString, '''', '''''')
-- 	SELECT @SQL = @SQLTopX + ' cm_cpi.PatientID AS [ ], 
-- 		case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
-- 		ISNULL(LastName, '''') + '', '' + 
-- 		ISNULL(FirstName, '''') + '' '' + 
-- 		ISNULL(MiddleName, '''') AS [Full Name],
-- 		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #],
-- 		dbo.LU_Gender_I.DisplayCode AS [Gender], 
-- 		CONVERT (VarChar(10), BirthDate, 111) AS [Birth Date], 
-- 		ISNULL(LastAlias, '''') + '', '' + 
-- 		ISNULL(FirstAlias, '''') + '' '' + 
-- 		ISNULL(MiddleAlias, '''') AS [Alternate Full Name]
-- 		into ' + @TempTable + '  FROM dbo.CM_CPI 
--             inner join dbo.CM_Alias ON CM_CPI.PatientID = dbo.CM_Alias.PatientID
-- 		LEFT JOIN dbo.LU_Gender_I ON dbo.CM_CPI.Gender = dbo.LU_Gender_I.Code 
-- 		WHERE LastAlias Like ''' + @SearchString + '%''
--         and IsDeleted = 2' + @SearchPrefix + ' 
-- 		AND (ISNULL(CM_CPI.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(CM_CPI.HospitalID, 0) end) '
-- 		+ @ExtraSearch + '
-- 		ORDER BY [Hosp ID], LastName DESC, FirstName'
-- 	exec sp_executesql @sql
--     --print @sql
--     
-- END
-- ELSE IF @FieldName = 'LastAlias' AND @NameSplit > 0
-- BEGIN
-- 	Set @SearchString = replace(@SearchString, '''', '''''')
-- 	Set @NameSplit = CHARINDEX(',', @SearchString) 
--  
-- 	SELECT @SQL = @SQLTopX + ' cm_cpi.PatientID AS [ ], 
-- 		case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
-- 		ISNULL(LastName, '''') + '', '' + 
-- 		ISNULL(FirstName, '''') + '' '' + 
-- 		ISNULL(MiddleName, '''') AS [Full Name],
-- 		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #],
-- 		dbo.LU_Gender_I.DisplayCode AS [Gender], 
-- 		CONVERT (VarChar(10), BirthDate, 111) AS [Birth Date],
-- 		ISNULL(LastAlias, '''') + '', '' + 
-- 		ISNULL(FirstAlias, '''') + '' '' + 
-- 		ISNULL(MiddleAlias, '''') AS [Alter Full Name]
-- 		into ' + @TempTable + '  FROM dbo.CM_CPI 
--             inner join dbo.CM_Alias ON CM_CPI.PatientID = dbo.CM_Alias.PatientID
--     		LEFT JOIN dbo.LU_Gender_I ON dbo.CM_CPI.Gender = dbo.LU_Gender_I.Code 
-- 		WHERE LastAlias LIKE ''' + Left(@SearchString, @NameSplit-1) + '%'' 
-- 		AND FirstAlias LIKE ''' + Stuff(@SearchString,1, @NameSplit, '') + '%''
--         And IsDeleted = 2' + @SearchPrefix + ' 
-- 		AND (ISNULL(CM_CPI.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(CM_CPI.HospitalID, 0) end) '
-- 		+ @ExtraSearch + '
-- 		ORDER BY [Hosp ID], LastName DESC, FirstName'
-- 	exec sp_executesql @sql
--     --print @sql
-- 
-- END
ELSE IF @DataType in (11, 12, 13) --PR-01739
BEGIN
	Declare @Where as NVarChar(1000)

	--EN-00081
	if right(@SearchString, 5) = '00/00' 
		set @where = '(' + @FieldName + ' >= Convert(DateTime, ''' + left(@SearchString, 5) + '01/01'') and ' + @FieldName + ' <= convert(DateTime, ''' + left(@SearchString, 5) + '12/31'')) '

	else if right(@SearchString, 2) = '00' 
		set @where = '(' + @FieldName + ' >= Convert(DateTime, ''' + left(@SearchString, 8) + '01'') and ' + @FieldName + ' < dateadd(M, 1, Convert(DateTime, ''' + left(@SearchString, 8) + '01''))) '
       	Else if (isdate(@SearchString) = 0) 
	set @SearchString = '1950/01/01'
	If isnull(@where, '') = ''
	        set @where = @FieldName + ' = Convert(DateTime, ''' + @SearchString + ''') '

	SELECT @SQL = @SQLTopX + ' PatientID as [ ], 
        CONVERT (VarChar(10), ' + @FieldName + ', 111) AS [SearchItem#],  
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CM_CPI.HospitalID, 0)) as [Hosp ID],
		case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
		REPLACE(SPACE(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #] ,
		ISNULL(LastName, '''') + '', '' + 
		ISNULL(FirstName, '''') + '' '' + 
		ISNULL(MiddleName, '''') AS [Full Name],
		dbo.LU_Gender_I.DisplayCode AS [Gender], 
		CONVERT (VarChar(10), BirthDate, 111) AS [Birth Date] 
 		into ' + @TempTable + '  FROM dbo.CM_CPI LEFT JOIN dbo.LU_Gender_I 
	            ON dbo.CM_CPI.Gender = dbo.LU_Gender_I.Code
		WHERE ' + @Where + '
		AND IsDeleted = 2' + @SearchPrefix + ' 
		AND (ISNULL(CM_CPI.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(CM_CPI.HospitalID, 0) end) '
		+ @ExtraSearch + '
		ORDER BY [Hosp ID], ' + @FieldName 
	exec sp_executesql @sql
END
ELSE
BEGIN	SELECT @SQL = @SQLTopX + ' PatientID as [ ], 
		' + @FieldName + ' AS [SearchItem#],  
        (select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CM_CPI.HospitalID, 0)) as [Hosp ID],
		case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #], 
		ISNULL(LastName, '''') + '', '' + 
		ISNULL(FirstName, '''') + '' '' + 
		ISNULL(MiddleName, '''') AS [Full Name],
		dbo.LU_Gender_I.DisplayCode AS [Gender], 
		CONVERT (VarChar(10), BirthDate, 111) AS [Birth Date] 
		into ' + @TempTable + '  FROM dbo.CM_CPI 			
		LEFT JOIN dbo.LU_Gender_I 
		ON dbo.CM_CPI.Gender = dbo.LU_Gender_I.Code 
		WHERE ' + @FieldName + ' LIKE ''%' + @SearchString + '%''  
		AND IsDeleted = 2' + @SearchPrefix + ' 
		AND (ISNULL(CM_CPI.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(CM_CPI.HospitalID, 0) end) '
		+ @ExtraSearch + '
		ORDER BY [Hosp ID], ' + @FieldName 
	
	exec sp_executesql @sql
End
If @ShowVip = '2'
Begin
	set @SQL = 'delete ' + @TempTable + ' where [Chart #] in (select replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') 
		from CM_CPI where isnull(secret, 0) = 1 and replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')
		in (select [Chart #] from ' + @TempTable + '))'
	Exec(@SQL)
End
If @SearchAudit = 1
Begin
	Declare @CurDTime as Datetime
	Set @CurDTime = getdate()
	set @SQL = 'insert into AU_SearchDetail select ' + cast(@Appid as varchar(10)) + ', [ ], ''' + Cast(@LogID as varchar(10)) + ''', ''' + convert(varchar(30), @CurDTime, 120) + ''' as Field2 from ' + @TempTable
	exec(@SQL)
end
Set nocount off
	set @SQL = 'select [ ], [' + @FieldDescription + '] = [SearchItem#], [Hosp ID], [Deceased], [Chart #], [Full Name], [Gender], [Birth Date] From ' + @TempTable
    --print @sql
	exec(@SQL)
	set @SQL = 'drop table ' + @TempTable
	exec(@SQL)







GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec F_SearchCJRR_Chart '123', ' 000000123', 1, 500004, 1, 0 
-- Called by the New CJRR Record Form (Locates Chart to user in new record).
CREATE PROCEDURE [F_SearchCJRR_Chart]
	@SearchString as varchar(50), 
	@SearchString2 as varchar(50),
	@SearchType as int,
	@UserID as int = 1,
	@Exact as int = 0,
	@HospID as varchar(100) = '0'
AS 

set NoCount on
	declare @select as Nvarchar(1500)
	declare @SQL as Nvarchar(1500)

	--Chart Audits, Prefixs, VIP and Top X parameters
	declare @SearchPrefix as Nvarchar(50)
	declare @SearchPrefix_Org as Nvarchar(100) --PR - 05450
	declare @ShowVip as Nvarchar(1)
	declare @TopX as Nvarchar(3)
	declare @SearchAudit as int
	declare @SQLTopX as Nvarchar(30)

	--13507: Stops ' from screwing it up
	set @SearchString = replace(@SearchString, '''', '''''')
	set @SearchString2 = replace(@SearchString2, '''', '''''')

	select @SearchPrefix = isnull(searchchartprefix, ''), @ShowVip = isnull(showvip, 0) from u_users where code = @UserID
	set @SearchPrefix_Org = @SearchPrefix   --PR - 05450
	if @SearchPrefix <> ''
		set @SearchPrefix = ' and Chartnumber like ''' + @SearchPrefix + '%'' '
	if @HospID = '0'
		select top 1 @TopX = isnull(TopSearch, '999'), @SearchAudit = EnableSearchAudit  from H_HospitalProfile 
	else	
		select top 1 @TopX = isnull(TopSearch, '999'), @SearchAudit = EnableSearchAudit  from H_HospitalProfile where isnull(Code, 0) = @HospID
	set @SQLTopX = 'select distinct top ' + @TopX + ' ' 
	
	declare @TempTable as Nvarchar(100)
	set @TempTable = '##SearchTmp' + replace(convert(nvarchar(100), getdate(), 114), ':', '')

	insert into AU_Search Values (40000, @SearchString, @UserID, GetDate(), 'Chart Number') --PR - 06295

if @SearchType in (1, 2) --= 1 
begin
	if @Exact = 0 --PR-03514
		set @SQL = @SQLTopX + ' PatientID AS [ ], PatientID AS [_],
				(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(C.HospitalID, 0)) as [Hosp ID],
				(case when Deathindicator = 1 then ''Y'' else ''N'' end) as [Deceased],				
				replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')  AS [Chart Number],
				isnull(LastName, '''') + '', '' + isnull(FirstName, '''')  + '' '' + isnull(Middlename, '''') AS [Full Name],
				convert(varchar(10), BirthDate, 111) AS [Birth Date] 
		into ' + @TempTable + ' from CM_CPI C
		where IsDeleted = 2 ' + @SearchPrefix + '
		and (ChartNumber like ''' + @SearchString + '%'' or ChartNumber like ''' + @SearchString2 +'%'')
		and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) 
		order by [Hosp ID], [Chart Number]'
	else
		set @SQL = @SQLTopX + ' PatientID AS [ ], PatientID AS [_],
				(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(C.HospitalID, 0)) as [Hosp ID],
				(case when Deathindicator = 1 then ''Y'' else ''N'' end) as [Deceased],
				replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')  AS [Chart Number],
				isnull(LastName, '''') + '', '' + isnull(FirstName, '''')  + '' '' + isnull(Middlename, '''') AS [Full Name],
				convert(varchar(10), BirthDate, 111) AS [Birth Date]
		into ' + @TempTable + ' from CM_CPI C
		where IsDeleted = 2 ' + @SearchPrefix + '
		and (ChartNumber = ''' + @SearchString + ''' or ChartNumber = ''' + @SearchString2 + ''')
		and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) 
		order by [Hosp ID], [Chart Number]'
end

--print @sql
exec sp_executesql @sql

If @ShowVip = '2'
Begin
	set @SQL = 'delete ' + @TempTable + ' where [Chart Number] in (select replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') 
		from CM_CPI where isnull(secret, 0) = 1 and replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')
		in (select [Chart Number] from ' + @TempTable + '))'
	Exec(@SQL)
End
set nocount off
	set @SQL = 'select * from ' + @TempTable
	exec(@SQL)
	set @SQL = 'drop table ' + @TempTable
	exec(@SQL)








GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- Called by the Clinic Search Form 
CREATE         PROCEDURE [F_SearchClinic]
	@FKey 		[int],
	@SearchString 	[varchar](50) = '',
	@SearchString2 [varchar](50) = '',
	@UserID 	[int] = 1,
	@Exact 	[int] = 0,
	@ExtraSearch 	[varchar](1000) = ''
AS 

DECLARE @SQL    varchar(1500)
	DECLARE @select varchar(750)
	DECLARE @where  varchar(500)
	DECLARE @order  varchar(100)

DECLARE @DataType    int
DECLARE @LookupTable varchar(50)
DECLARE @FieldName   varchar(50)
DECLARE @NameSplit   int
DECLARE @FieldDesc   varchar(150)
DECLARE @Temp        datetime
DECLARE @DBTableName varchar(50)
Declare @FieldDT     varchar(20)

SELECT @DataType    = DataType FROM U_UsersFields  WHERE AppID = 451 AND FieldID = @FKey AND UserID = @UserID
SELECT @LookupTable = LookUpTable FROM U_UsersFields  WHERE AppID = 451 AND FieldID = @FKey AND UserID = @UserID
SELECT @FieldName   = SystemName FROM U_Fields  WHERE FieldID = @FKey
SELECT @FieldDesc   = InHouseDesc FROM U_Fields  WHERE FieldID = @FKey
SELECT @DBTableName = Table_Name FROM information_schema.columns WHERE Column_Name = @FieldName and Table_Name like 'CR_%'

SET @NameSplit = CHARINDEX(',', @SearchString) 

IF @FieldName in ('ChartNumber', 'ProviderNumber', 'EncounterNumber', 'AdmitDate', 'LastName')
BEGIN
	IF @FieldName = 'ChartNumber' 
	BEGIN
		IF @Exact = 0
			SET @SQL = 'SELECT TOP 100 PERCENT dbo.CR_Demographic.AbstractID AS [ ], 
			    		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'')  AS [Chart #], 
					(SELECT DisplayCode FROM LU_Provider WHERE Code = ProviderNumber) AS [Provider #], 	
					EncounterNumber AS [Encounter #], 
			    		ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''') + '' '' + ISNULL(MiddleName, '''') AS [Full Name], 
			    		CONVERT(VARCHAR(10), AdmitDate, 111) AS [Admit Date], 
			    		CONVERT(VARCHAR(5), AdmitTime, 14) AS [Admit Time] 
				FROM dbo.CR_Demographic INNER JOIN dbo.CR_Visit ON dbo.CR_Demographic.AbstractID = dbo.CR_Visit.AbstractID
				WHERE (ChartNumber Like ''' + @SearchString + '%'' OR ChartNumber LIKE ''' + @SearchString2 +'%'')
				AND IsDeleted = 2 '
				+ @ExtraSearch + '
				ORDER BY [Chart #] Desc, AdmitDate DESC'
		ELSE
			SET @SQL = 'SELECT TOP 100 PERCENT dbo.CR_Demographic.AbstractID AS [ ], 
			    		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'')  AS [Chart #], 
					(SELECT DisplayCode FROM LU_Provider WHERE Code = ProviderNumber) AS [Provider #], 	
					EncounterNumber AS [Encounter #], 
			    		ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''') + '' '' + ISNULL(MiddleName, '''') AS [Full Name], 
			    		CONVERT(VARCHAR(10), AdmitDate, 111) AS [Admit Date], 
			    		CONVERT(VARCHAR(5), AdmitTime, 14) AS [Admit Time] 
				FROM dbo.CR_Demographic INNER JOIN dbo.CR_Visit ON dbo.CR_Demographic.AbstractID = dbo.CR_Visit.AbstractID
				WHERE (ChartNumber = ''' + @SearchString + ''' OR ChartNumber = ''' + @SearchString2 +''')
				AND IsDeleted = 2 '
				+ @ExtraSearch + '
				ORDER BY [Chart #] Desc, AdmitDate DESC'

		EXECUTE(@SQL)
		RETURN 0
	END
	
	ELSE IF @FieldName = 'ProviderNumber'     	
	BEGIN
		SET @SQL = 'SELECT TOP 100 PERCENT dbo.CR_Demographic.AbstractID AS [ ], 
				(SELECT DisplayCode FROM LU_Provider WHERE Code = ProviderNumber) AS [Provider #], 
		    		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'')  AS [Chart #], 
				EncounterNumber AS [Encounter #], 
		    		ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''') + '' '' + ISNULL(MiddleName, '''') AS [Full Name], 
		    		CONVERT(VARCHAR(10), AdmitDate, 111) AS [Admit Date], 
		    		CONVERT(VARCHAR(5), AdmitTime, 14) AS [Admit Time] 
			FROM dbo.CR_Demographic INNER JOIN dbo.CR_Visit ON dbo.CR_Demographic.AbstractID = dbo.CR_Visit.AbstractID
			WHERE EncounterNumber Like ''' + @SearchString + '%''
		  	AND IsDeleted = 2 '
			+ @ExtraSearch + '
		    	ORDER BY EncounterNumber DESC'
		EXECUTE(@SQL)
		RETURN 0
	END
	
	ELSE IF @FieldName = 'EncounterNumber'     	
	BEGIN
		SET @SQL = 'SELECT TOP 100 PERCENT dbo.CR_Demographic.AbstractID AS [ ], 
				EncounterNumber AS [Encounter #], 
		    		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'')  AS [Chart #], 
				(SELECT DisplayCode FROM LU_Provider WHERE Code = ProviderNumber) AS [Provider #], 	
		    		ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''') + '' '' + ISNULL(MiddleName, '''') AS [Full Name], 
		    		CONVERT(VARCHAR(10), AdmitDate, 111) AS [Admit Date], 
		    		CONVERT(VARCHAR(5), AdmitTime, 14) AS [Admit Time] 
			FROM dbo.CR_Demographic INNER JOIN dbo.CR_Visit ON dbo.CR_Demographic.AbstractID = dbo.CR_Visit.AbstractID
			WHERE EncounterNumber Like ''' + @SearchString + '%''
	    		AND IsDeleted = 2 '
			+ @ExtraSearch + '
	    		ORDER BY EncounterNumber DESC'
		EXECUTE(@SQL)
		RETURN 0
	END
	
	ELSE IF @FieldName = 'AdmitDate' 
	BEGIN
		SET @SQL = 'SELECT TOP 100 PERCENT dbo.CR_Demographic.AbstractID AS [ ], 
		    		CONVERT(VARCHAR(10), AdmitDate, 111) AS [Admit Date], 
		    		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'')  AS [Chart #], 
				(SELECT DisplayCode FROM LU_Provider WHERE Code = ProviderNumber) AS [Provider #], 	
				EncounterNumber AS [Encounter #], 
		    		ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''') + '' '' + ISNULL(MiddleName, '''') AS [Full Name], 
		    		CONVERT(VARCHAR(5), AdmitTime, 14) AS [Admit Time] 
			FROM dbo.CR_Demographic INNER JOIN dbo.CR_Visit ON dbo.CR_Demographic.AbstractID = dbo.CR_Visit.AbstractID
			WHERE  AdmitDate >= Convert(Datetime, ''' + @SearchString + ''') 
			AND IsDeleted = 2 '
			+ @ExtraSearch + '
			ORDER BY AdmitDate'
		EXECUTE(@SQL)
		RETURN 0
	END
	
	ELSE IF @FieldName = 'LastName' AND @NameSplit = 0
	BEGIN
		SET @SearchString = REPLACE(@SearchString, '''', '''''')
		SET @SQL = 'SELECT TOP 100 PERCENT dbo.CR_Demographic.AbstractID AS [ ], 
		    		ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''') + '' '' + ISNULL(MiddleName, '''') AS [Full Name], 
		    		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'')  AS [Chart #], 
				(SELECT DisplayCode FROM LU_Provider WHERE Code = ProviderNumber) AS [Provider #], 	
				EncounterNumber AS [Encounter #], 
		    		CONVERT(VARCHAR(10), AdmitDate, 111) AS [Admit Date], 
		    		CONVERT(VARCHAR(5), AdmitTime, 14) AS [Admit Time] 
			FROM dbo.CR_Demographic INNER JOIN dbo.CR_Visit ON dbo.CR_Demographic.AbstractID = dbo.CR_Visit.AbstractID
			WHERE LastName Like ''' + @SearchString + '%'' 
			AND IsDeleted = 2 '
			+ @ExtraSearch + '
			ORDER BY LastName DESC, FirstName, AdmitDate DESC'
		EXECUTE(@SQL)
		RETURN 0
	END
	
	ELSE IF @FieldName = 'LastName' AND @NameSplit > 0
	BEGIN
		SET @SearchString = REPLACE(@SearchString, '''', '''''')
		SET @SQL = 'SELECT TOP 100 PERCENT dbo.CR_Demographic.AbstractID AS [ ], 
		    		ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''') + '' '' + ISNULL(MiddleName, '''') AS [Full Name], 
		    		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'')  AS [Chart #], 
				(SELECT DisplayCode FROM LU_Provider WHERE Code = ProviderNumber) AS [Provider #], 	
				EncounterNumber AS [Encounter #], 
		    		CONVERT(VARCHAR(10), AdmitDate, 111) AS [Admit Date], 
		    		CONVERT(VARCHAR(5), AdmitTime, 14) AS [Admit Time] 
			FROM dbo.CR_Demographic INNER JOIN dbo.CR_Visit ON dbo.CR_Demographic.AbstractID = dbo.CR_Visit.AbstractID
			WHERE LastName Like ''' + RTRIM(LTRIM(LEFT(@SearchString, @NameSplit-1))) + '%'' 
			AND FirstName Like ''' + RTRIM(LTRIM(STUFF(@SearchString, 1, @NameSplit, ''))) + '%'' 
			AND IsDeleted = 2 '
			+ @ExtraSearch + '
			ORDER BY LastName DESC, FirstName, AdmitDate DESC'
		EXECUTE(@SQL)
		RETURN 0
	END
END

ELSE 
BEGIN
	SET @FieldDesc = '[' + @FieldDesc + '] = ' + (CASE @DataType 
				WHEN 11 THEN 'CONVERT(VARCHAR(10), ' + @FieldName + ', 111), ' 
				WHEN 12 THEN 'CONVERT(VARCHAR(10), ' + @FieldName + ', 111), ' --PR-01739
				WHEN 13 THEN 'CONVERT(VARCHAR(10), ' + @FieldName + ', 111), ' --PR-01739
				WHEN 15 THEN 'CONVERT(VARCHAR(5), ' + @FieldName + ', 14), '  
				ELSE '' + @FieldName + ', '  END)

	SET @select = 'SELECT TOP 100 PERCENT [ ] = ab.AbstractID, '  +
			@FieldDesc +			
			'REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'')  AS [Chart #], 
			(SELECT DisplayCode FROM LU_Provider WHERE Code = ProviderNumber) AS [Provider #], 	
			EncounterNumber AS [Encounter #], 
			ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''') + '' '' + ISNULL(MiddleName, '''') AS [Full Name], 
			CONVERT(VARCHAR(10), AdmitDate, 111) AS [Admit Date], 
			CONVERT(VARCHAR(5), AdmitTime, 14) AS [Admit Time] 
		FROM dbo.CR_Demographic INNER JOIN dbo.CR_Visit ON dbo.CR_Demographic.AbstractID = dbo.CR_Visit.AbstractID'

	-- determine the Where Clause base on datatype
	IF (@DataType in (11, 12, 13))     -- if it is a date --PR-01739
	BEGIN
		IF(ISDATE(@SearchString) = 0) SET @SearchString = '1950/01/01'
			SET @where = @FieldName + ' >= CONVERT(DateTime, ''' + @SearchString + ''') '
	END

	ELSE IF (@DataType = 15) -- if it is a time
	BEGIN
		SET @SearchString = (CASE CHARINDEX(':', @SearchString) WHEN 1 THEN '00' + @SearchString WHEN 2 THEN '0' + @SearchString ELSE @SearchString END)
		SET @SearchString = REPLACE(@SearchString, ':', '')
		SET @SearchString = (CASE LEN(@SearchString)  WHEN 0 THEN '00:00' WHEN 1 THEN '00:0' + @SearchString WHEN 2 THEN '00:' + @SearchString WHEN 3 THEN '0' + LEFT(@SearchString, 1) + ':' + RIGHT(@SearchString, 2)  WHEN 4 THEN LEFT(@SearchString, 2) + ':' + RIGHT(@SearchString, 2) ELSE LEFT(@SearchString, 2) + ':' + SUBSTRING(@SearchString, 2, 2) END)
	        --if (isdate(@SearchString) = 0) Set @SearchString = '23:59:59' --PR-03191
	        --set @where = @FieldName + ' >= ''1899-12-30 ' + @SearchString + ''' ' --PR-03191
		if (isdate(@SearchString) = 0) Set @SearchString = '23:59' --PR-03191
		set @where = 'convert(NVarChar(5), ' + @FieldName + ', 14) >= ''' + @SearchString + ''' ' --PR-03191
	END

	ELSE -- all other cases
	BEGIN
		SELECT @FieldDT = Data_Type FROM information_schema.columns WHERE Column_Name = @FieldName and Table_Name like 'CR_%'
		IF(@FieldDT = 'int') 
		BEGIN
			IF (@SearchString = '') SET @SearchString = '0'
				SET @where = @FieldName + ' >= ' + @SearchString + ' '
		END
		ELSE SET @where = @FieldName + ' LIKE ''%' + @SearchString + '%'' '
	END

	SET @where =  'WHERE IsDeleted = 2 AND ' + @where + @ExtraSearch
	SET @order = 'ORDER BY ' + @FieldName + ', AdmitDate DESC'
		
	SELECT @sql = @select + @where + @order
	EXECUTE(@SQL)
	RETURN 0
END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





--Used to get the ID of a record (Amcare at this point) to Clone the Abstract
CREATE PROCEDURE [F_SearchCloneVisits]
	@CareType as int,
	@AbstractID as int,
	@ChartNumber as varchar(10),
	@MISCode as int, 
	@HospID as int = 0
AS 

IF @MISCode = 0 
	SELECT AbstractID AS [ ],
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Abstract.HospitalID, 0)) as [Hosp ID],
		EncounterNumber AS [Encounter #], 
		REPLACE(SPACE(3-LEN(ISNULL(CONVERT(VARCHAR(3),EncounterSequence), 0))) + ISNULL(CONVERT(VARCHAR(3),EncounterSequence), 0), ' ', '0') AS [Enc. Seq.], 	
		(SELECT CIHIValue FROM LU_MISCode WHERE Code = MISCode)  AS [M.I.S. Code], 
		CONVERT(VARCHAR(10), AdmitDate, 111) AS [Register Date], 
	   	CONVERT (VARCHAR(5), AdmitTime, 14) AS [Register Time],
		CONVERT(VARCHAR(10), DischargeDate, 111) AS [Disposition Date], 
	   	CONVERT (VARCHAR(5), DischargeTime, 14) AS [Disposition Time],
		(SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Complete Status],
		(SELECT CIHIValue FROM ICD_DiagFile10 WHERE Code = (SELECT DiagnosisCode FROM AB_Diagnosis WHERE AB_Diagnosis.AbstractID = AB_Abstract.AbstractID AND DiagnosisOccurrence = 1)) AS [Diag Code],
		(SELECT CIHIValue FROM ICD_ProcFile10 WHERE Code = (SELECT IntervCode FROM AB_Intervention WHERE AB_Intervention.AbstractID = AB_Abstract.AbstractID AND IntervOccurrence = 1)) AS [Interv Code]
	FROM dbo.AB_Abstract
	WHERE ICDType = 'T' AND CareType = @CareType AND AbstractID <> @AbstractID AND ChartNumber = @ChartNumber AND IsDeleted = 2	
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end) 
	order by [Hosp ID], AdmitDate desc
ELSE
	SELECT AbstractID AS [ ],
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Abstract.HospitalID, 0)) as [Hosp ID],
		EncounterNumber AS [Encounter #], 
		REPLACE(SPACE(3-LEN(ISNULL(CONVERT(VARCHAR(3),EncounterSequence), 0))) + ISNULL(CONVERT(VARCHAR(3),EncounterSequence), 0), ' ', '0') AS [Enc. Seq.], 	
		(SELECT CIHIValue FROM LU_MISCode WHERE Code = MISCode)  AS [M.I.S. Code], 
		CONVERT(VARCHAR(10), AdmitDate, 111) AS [Register Date], 
	   	CONVERT (VARCHAR(5), AdmitTime, 14) AS [Register Time],
		CONVERT(VARCHAR(10), DischargeDate, 111) AS [Disposition Date], 
	   	CONVERT (VARCHAR(5), DischargeTime, 14) AS [Disposition Time],
		(SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Complete Status],
		(SELECT CIHIValue FROM ICD_DiagFile10 WHERE Code = (SELECT DiagnosisCode FROM AB_Diagnosis WHERE AB_Diagnosis.AbstractID = AB_Abstract.AbstractID AND DiagnosisOccurrence = 1)) AS [Diag Code],
		(SELECT CIHIValue FROM ICD_ProcFile10 WHERE Code = (SELECT IntervCode FROM AB_Intervention WHERE AB_Intervention.AbstractID = AB_Abstract.AbstractID AND IntervOccurrence = 1)) AS [Interv Code]
	FROM dbo.AB_Abstract
	WHERE ICDType = 'T' AND CareType = 5 AND AbstractID <> @AbstractID AND ChartNumber = @ChartNumber AND MISCode = @MISCode AND IsDeleted = 2
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
	order by [Hosp ID], AdmitDate desc


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--Used to get the ID of a record to Clone the Abstract
CREATE PROCEDURE [F_SearchCloneVisits_OMHRS]
	@AppID as int,
	@AbstractID as int,
	@ChartNumber as varchar(10),
	@HospID as int = 0
AS 

	select AA.AbstractID as [ ],
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AA.HospitalID, 0)) as [Hosp ID],
        		Z1 as [Record #],
		ChartNumber as [Chart #],
		AA3 as [Case #], 
		convert (varchar(10), AdmitDate, 111) as [Date Stay Began], 
	   	convert (varchar(5), AdmitTime, 14) as [Time Stay Began],
		convert (varchar(10), A1, 111) as [Assessment Date], 
	   	convert (varchar(5), AssessTime, 14) as [Assessment Time],
        (select isnull(DisplayCode, '') + ' - ' + isnull(UserDescription, '') from LU_CodeFile where Code = Z1) AS [Type],
		(select CIHIValue from LU_AbstractStatus where Code = IsCompleted) as [Status]
    from OMHRS_SecAA AA inner join OMHRS_SecA A on AA.AbstractID = A.AbstractID inner join OMHRS_RecInfo R on AA.AbstractID = R.AbstractID	
    where AppID = @AppID
    and isnull(ChartNumber, '') = isnull(@ChartNumber, '')
    and isnull(AA.AbstractID, 0) <> isnull(@AbstractID, 0)
    and isnull(IsDeleted, 0) = 2	
    and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
    order by [Hosp ID], AdmitDate desc


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE    PROCEDURE [F_SearchDeficiency_Abstract]
	@SearchCode as Integer,
	@ChartNumber as VarChar(10)
AS 
	IF @SearchCode <> 0
		BEGIN
			SELECT AbstractID,  CONVERT(VarChar(10), DischargeDate, 111) AS [Discharge Date],  
				ICDType + ': ' + 
				CONVERT(VarChar(1), (SELECT DisplayCode FROM LU_CareType WHERE Code = CareType)) + ': ' + 
				EncounterNumber + ' - ' + 
				REPLACE(SPACE(3-LEN(ISNULL(CONVERT(VARCHAR(3), EncounterSequence), 0))) + ISNULL(CONVERT(VARCHAR(3), EncounterSequence), 0), ' ', '0')  AS [Abstract Information]
			FROM AB_Abstract
			WHERE AbstractID = @SearchCode
			AND IsDeleted = 2
			ORDER BY DischargeDate DESC
		END
	ELSE
		BEGIN
			SELECT AbstractID,  CONVERT(VarChar(10), DischargeDate, 111) AS [Discharge Date],  
				ICDType + ': ' + 
				CONVERT(VarChar(1), (SELECT DisplayCode FROM LU_CareType WHERE Code = CareType)) + ': ' + 
				EncounterNumber + ' - ' + 
				REPLACE(SPACE(3-LEN(ISNULL(CONVERT(VARCHAR(3), EncounterSequence), 0))) + ISNULL(CONVERT(VARCHAR(3), EncounterSequence), 0), ' ', '0')  AS [Abstract Information]
			FROM AB_Abstract
			WHERE ChartNumber = @ChartNumber
			AND IsDeleted = 2
			ORDER BY DischargeDate DESC
		END
	RETURN 0



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE  PROCEDURE [F_SearchDeficiency_Chart]
   @SearchCode as Integer,
   @SearchString as VarChar(50), 
   @SearchString2 as VarChar(50),
   @HospID as int = 0
AS 

   IF @SearchCode <> 0
       BEGIN
           SELECT PatientID, ChartNumber, isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') AS [Patient Name]
           FROM CM_CPI
           WHERE PatientID = @SearchCode
       END
   ELSE
       BEGIN
           SELECT top 999 PatientID, ChartNumber, isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') AS [Patient Name]
           FROM CM_CPI
           WHERE ChartNumber LIKE @SearchString + '%' OR ChartNumber LIKE @SearchString2 + '%'
           and ChartNumber in (select ChartNumber from CM_CPI where (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)) 
	   --AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end) 	
       END
   RETURN 0



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [F_SearchDeficiency_List]
	@FKey as int,
	@SearchString as VarChar(50),
	@SearchString2 as VarChar(50),
	@UserID as int = 1,
	@Exact as int = 0,
	@HospID as varchar(10) = '0',
	@ExtraSearch 	[varchar](1000) = ''
AS 
DECLARE @SQL nVarChar(3000)
DECLARE @DataType int
DECLARE @FieldName as VarChar(50)
DECLARE @FieldDescription as VarChar(50)
DECLARE @NameSplit as int

Declare @ShowVip as NVarChar(1) --PR - 06295

set nocount on

SELECT @DataType = (SELECT DataType FROM U_UsersFields  WHERE AppID = 15 AND FieldID = @FKey and UserID = @UserID)
SELECT @FieldName = (SELECT SystemName FROM U_Fields  WHERE FieldID = @FKey)
SELECT @FieldDescription = (SELECT isnull(Header_User, @FieldName) FROM U_UsersFields  WHERE AppID = 15 AND FieldID = @FKey and UserID = @UserID)
SELECT @NameSplit = CHARINDEX(',', @SearchString) 
select @ShowVip = isnull(showvip, 0) from u_users where code = @UserID

--PR - 04434
if @FieldName = 'barcodevolume'
    SELECT @FieldDescription = (SELECT isnull(Header_User, @FieldName) FROM U_UsersFields  WHERE AppID = 1 AND FieldID = @FKey and UserID = @UserID)


--13507: Moved to top	
Set @SearchString = replace(@SearchString, '''', '''''')
Set @SearchString2 = replace(@SearchString2, '''', '''''')

if @HospID is null set @HospID = 0

declare @TopX as nvarchar(3)
declare @SQLTopX as nvarchar(20)
declare @TempDB nvarchar(100)
Declare @SearchAudit as int

--declare @SearchPrefix as nvarchar(50)
--declare @ShowVip as nvarchar(1)
--select @SearchPrefix = isnull(SearchChartPrefix, ''), @ShowVip = isnull(ShowVIP, 0) from U_Users where Code = @UserID
--if @SearchPrefix <> ''
--	set @SearchPrefix = ' and cm_cpi.Chartnumber like ''' + @SearchPrefix + '%'' '

if @HospID = '0'
	select top 1 @TopX = isnull(TopSearch, '999'), @SearchAudit = EnableSearchAudit from H_HospitalProfile 
else	
	select top 1 @TopX = isnull(TopSearch, '999'), @SearchAudit = EnableSearchAudit from H_HospitalProfile where isnull(Code, 0) = @HospID

if isnull(@TopX, '') in ('', '0') set @TopX = '999'
set @SQLTopX = ' top ' + @TopX + ' ' 

set @TempDB = '##SearchDeficiency' + replace(replace(replace(replace(convert(varchar(50), getdate(), 121), '-', ''), ':', ''), ' ', ''), '.', '') + 
            cast(isnull(@HospID, 0) as varchar(10)) + cast(isnull(@UserID, 0) as varchar(10))

	insert into AU_Search Values (15, @SearchString, @UserID, GetDate(), @FieldDescription) --PR - 06295

--EN-00043
if @FKey = 45006 -- TERMINAL DIGIT SORT
    begin
 	declare @order as varchar(400)
-- 	declare @OrdT as varchar(400)

-- 	declare @TDigit as varchar(10)
-- 	declare @TDigitR as varchar(10)
-- 	declare @TDigitH as varchar(10)
-- 
-- 	select @TDigitR = TerminalDigit from H_RegionProfile
-- 	if @HospID = '0' 
-- 		select top 1 @TDigitH = TerminalDigit from H_HospitalProfile 
-- 	else
-- 		select top 1 @TDigitH = TerminalDigit from H_HospitalProfile where HospitalID = @HospID
-- 	
-- 	set @TDigit = @TDigitR
-- 	if len(@TDigitH) <> 0 and isnull(@TDigitH, '0') <> '0' set @TDigit = @TDigitH
-- 	--set @TDigit = '926315'
-- 	
-- 	declare @Pos1 as varchar(1)
-- 	declare @Len1 as varchar(1)
-- 	declare @Pos2 as varchar(1)
-- 	declare @Len2 as varchar(1)
-- 	declare @Pos3 as varchar(1)
-- 	declare @Len3 as varchar(1)
-- 	declare @Pos4 as varchar(1)
-- 	declare @Len4 as varchar(1)
-- 	declare @Pos5 as varchar(1)
-- 	declare @Len5 as varchar(1)
-- 
-- 	if isnumeric(substring(@TDigit, 1, 1)) = 1 
-- 		set @Pos1 = substring(@TDigit, 1, 1)
-- 	if isnumeric(substring(@TDigit, 2, 1)) = 1 
-- 		set @Len1 = substring(@TDigit, 2, 1)
-- 	if isnumeric(substring(@TDigit, 3, 1)) = 1 
-- 		set @Pos2 = substring(@TDigit, 3, 1)
-- 	if isnumeric(substring(@TDigit, 4, 1)) = 1 
-- 		set @Len2 = substring(@TDigit, 4, 1)
-- 	if isnumeric(substring(@TDigit, 5, 1)) = 1 
-- 		set @Pos3 = substring(@TDigit, 5, 1)
-- 	if isnumeric(substring(@TDigit, 6, 1)) = 1 
-- 		set @Len3 = substring(@TDigit, 6, 1)
-- 	if isnumeric(substring(@TDigit, 7, 1)) = 1 
-- 		set @Pos4 = substring(@TDigit, 7, 1)
-- 	if isnumeric(substring(@TDigit, 8, 1)) = 1 
-- 		set @Len4 = substring(@TDigit, 8, 1)
-- 	if isnumeric(substring(@TDigit, 9, 1)) = 1 
-- 		set @Pos5 = substring(@TDigit, 9, 1)
-- 	if isnumeric(substring(@TDigit, 10, 1)) = 1 
-- 		set @Len5 = substring(@TDigit, 10, 1)
-- 
-- 	if len(@Pos1) <> 0 and len(@Len1) <> 0
-- 		set @OrdT = ' substring(replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0''), ' + @Pos1 + ', ' + @Len1 + '), '
-- 		
-- 	if len(@Pos2) <> 0 and len(@Len2) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0''), ' + @Pos2 + ', ' + @Len2 + '), '
-- 
-- 	if len(@Pos3) <> 0 and len(@Len3) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0''), ' + @Pos3 + ', ' + @Len3 + '), '
-- 
-- 	if len(@Pos4) <> 0 and len(@Len4) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0''), ' + @Pos4 + ', ' + @Len4 + '), '
-- 
-- 	if len(@Pos5) <> 0 and len(@Len5) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0''), ' + @Pos5 + ', ' + @Len5 + '), '
-- 
-- 	if len(@OrdT) <> 0 
-- 		set @OrdT = left(@OrdT, len(@OrdT) - 1)
-- 
-- 	set @SQL = 'SELECT top 999 dbo.Def_SlipMain.DefeciencyID AS [DID], 
-- 			REPLACE(SPACE(10-LEN(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
-- 			dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number], 
-- 			(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
-- 			(SELECT CONVERT(VARCHAR(10), isnull(DischargeDate, AdmitDate), 111) FROM AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
-- 			ISNULL(dbo.CM_CPI.LastName, '''') + '', '' + ISNULL(dbo.CM_CPI.FirstName, '''') + '' '' + ISNULL(dbo.CM_CPI.MiddleName, '''') AS [Patient Name], 
-- 			dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],
-- 			(SELECT DisplayCode FROM LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
-- 			(SELECT DisplayCode FROM DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status]
-- 		FROM dbo.Def_SlipMain
-- 		LEFT JOIN dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
-- 		LEFT JOIN dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID
-- 		WHERE (ISNULL(dbo.Def_SlipMain.DefMainStatus, 0)  not in (8, 11)) 
-- 		AND (ISNULL(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else ISNULL(Def_SlipMain.HospitalID, 0) end) 	
-- 		AND (dbo.CM_CPI.ChartNumber LIKE ''' + @SearchString + '%'' OR ChartNumber LIKE ''' + @SearchString2 + '%'') 
--         and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end) '  
-- 	+ @ExtraSearch 
-- 
-- 	set @order = ''
-- 	if len(@OrdT) <> 0 
-- 	        set @order = ' order by ' + @OrdT
-- 
--EN-00183 Add Hospital Link
--dbo.Def_SlipMain.DefeciencyID AS [DID]
	set @SQL = 'SELECT ' + @SQLTopX + '
			(select TerminalChart from CM_Terminal where PatientID = Def_SlipMain.DefPatientID) as [SearchItem#], 
            dbo.Def_SlipMain.DefID AS [DID], 
            CH.DisplayCode as [Chart Hospital Link],
			REPLACE(SPACE(10-LEN(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
            VH.DisplayCode as [Volume Hospital Link],
			dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number], 
			(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
			(SELECT CONVERT(VARCHAR(10), isnull(DischargeDate, AdmitDate), 111) FROM AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
			ISNULL(dbo.CM_CPI.LastName, '''') + '', '' + ISNULL(dbo.CM_CPI.FirstName, '''') + '' '' + ISNULL(dbo.CM_CPI.MiddleName, '''') AS [Patient Name], 
            DH.DisplayCode as [Def. Hospital Link],
			dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],
			(SELECT DisplayCode FROM LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
			(SELECT DisplayCode FROM DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status] into ' + @TempDB + ' 
		FROM dbo.Def_SlipMain
    		LEFT JOIN dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
	    	LEFT JOIN dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID
            left join H_HospitalProfile DH on DH.Code = Def_SlipMain.HospitalID
            left join H_HospitalProfile CH on CH.Code = CM_CPI.HospitalID
            left join H_HospitalProfile VH on VH.Code = CM_CPI_Volume.HospitalID
		WHERE (ISNULL(dbo.Def_SlipMain.DefMainStatus, 0) not in (8, 11)) 
		AND (ISNULL(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else ISNULL(Def_SlipMain.HospitalID, 0) end) 	
		and Def_SlipMain.DefPatientID in (select PatientID from CM_Terminal where TerminalChart Like ''' + @SearchString + '%'' or MaskTerminal Like ''' + @SearchString + '%'')
        and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end) '  
	+ @ExtraSearch 

	set @order = ' order by (select TerminalChart from CM_Terminal where PatientID = Def_SlipMain.DefPatientID) '
	set @sql = @sql + @order 
	--print @sql
        exec sp_executesql @sql 
        set @FieldDescription = 'Terminal #'
    end

else IF @FieldName = 'DefPatientID' 
BEGIN
			--(SELECT UserDescription FROM LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider Name],
	IF @Exact = 0 
		set @SQL = 'SELECT ' + @SQLTopX + ' 
            dbo.Def_SlipMain.DefID AS [DID], 
            [SearchItem#] = dbo.CM_CPI.ChartNumber,
            CH.DisplayCode as [Chart Hospital Link],
			REPLACE(SPACE(10-LEN(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
            VH.DisplayCode as [Volume Hospital Link],
			dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number], 
			(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
			(SELECT CONVERT(VARCHAR(10), isnull(DischargeDate, AdmitDate), 111) FROM AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
		    ISNULL(dbo.CM_CPI.LastName, '''') + '', '' + ISNULL(dbo.CM_CPI.FirstName, '''') + '' '' + ISNULL(dbo.CM_CPI.MiddleName, '''') AS [Patient Name], 
            DH.DisplayCode as [Def. Hospital Link],
			dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],
			(SELECT DisplayCode FROM LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
			(SELECT DisplayCode FROM DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status] into ' + @TempDB + '
		FROM dbo.Def_SlipMain
		LEFT JOIN dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
		LEFT JOIN dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID
            left join H_HospitalProfile DH on DH.Code = Def_SlipMain.HospitalID
            left join H_HospitalProfile CH on CH.Code = CM_CPI.HospitalID
            left join H_HospitalProfile VH on VH.Code = CM_CPI_Volume.HospitalID
		WHERE (ISNULL(dbo.Def_SlipMain.DefMainStatus, 0) not in (8, 11)) 
		AND (ISNULL(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else ISNULL(Def_SlipMain.HospitalID, 0) end) 	
		AND (dbo.CM_CPI.ChartNumber LIKE ''' + @SearchString + '%'' OR ChartNumber LIKE ''' + @SearchString2 + '%'') 
        and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end) '  +
		@ExtraSearch +
		' ORDER BY [Chart Number] '
		
	ELSE
		set @SQL = 'SELECT ' + @SQLTopX + ' 
            dbo.Def_SlipMain.DefID AS [DID], 
            [SearchItem#] = dbo.CM_CPI.ChartNumber,
            CH.DisplayCode as [Chart Hospital Link],
			REPLACE(SPACE(10-LEN(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
            VH.DisplayCode as [Volume Hospital Link],
			dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number], 
			(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
			(SELECT CONVERT(VARCHAR(10), isnull(DischargeDate, AdmitDate), 111) FROM AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
    		ISNULL(dbo.CM_CPI.LastName, '''') + '', '' + ISNULL(dbo.CM_CPI.FirstName, '''') + '' '' + ISNULL(dbo.CM_CPI.MiddleName, '''') AS [Patient Name], 
            DH.DisplayCode as [Def. Hospital Link],
			dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],
			(SELECT DisplayCode FROM LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
			(SELECT DisplayCode FROM DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status] into ' + @TempDB + '
		FROM dbo.Def_SlipMain
		LEFT JOIN dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
		LEFT JOIN dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID
            left join H_HospitalProfile DH on DH.Code = Def_SlipMain.HospitalID
            left join H_HospitalProfile CH on CH.Code = CM_CPI.HospitalID
            left join H_HospitalProfile VH on VH.Code = CM_CPI_Volume.HospitalID
		WHERE (ISNULL(dbo.Def_SlipMain.DefMainStatus, 0) not in (8, 11)) 
		AND (ISNULL(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else ISNULL(Def_SlipMain.HospitalID, 0) end) 	
		AND (dbo.CM_CPI.ChartNumber = ''' + @SearchString + ''' OR ChartNumber = ''' + @SearchString2 + ''') 
        and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end) '  +
		@ExtraSearch + 
		' ORDER BY [Chart Number]'
    --print @sql
	execute (@SQL)
END

ELSE IF @FieldName = 'DefVolumeID'
BEGIN
	set @SQL = 'SELECT ' + @SQLTopX + ' 
        dbo.Def_SlipMain.DefID AS [DID], 
		dbo.CM_CPI_Volume.VolumeNumber AS [SearchItem#],
        CH.DisplayCode as [Chart Hospital Link],
		REPLACE(SPACE(10-LEN(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
        VH.DisplayCode as [Volume Hospital Link],
		dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number],
		(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
		(SELECT CONVERT(VARCHAR(10), isnull(DischargeDate, AdmitDate), 111) FROM AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
   		ISNULL(dbo.CM_CPI.LastName, '''') + '', '' + ISNULL(dbo.CM_CPI.FirstName, '''') + '' '' + ISNULL(dbo.CM_CPI.MiddleName, '''') AS [Patient Name], 
        DH.DisplayCode as [Def. Hospital Link],
		dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],
		(SELECT DisplayCode FROM LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
		(SELECT DisplayCode FROM DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status] into ' + @TempDB + '
	FROM dbo.Def_SlipMain
	LEFT JOIN dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
	LEFT JOIN dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID
            left join H_HospitalProfile DH on DH.Code = Def_SlipMain.HospitalID
            left join H_HospitalProfile CH on CH.Code = CM_CPI.HospitalID
            left join H_HospitalProfile VH on VH.Code = CM_CPI_Volume.HospitalID
	WHERE (ISNULL(dbo.Def_SlipMain.DefMainStatus, 0) not in (8, 11)) 
		AND (ISNULL(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else ISNULL(Def_SlipMain.HospitalID, 0) end) 	
   	AND(dbo.Def_SlipMain.DefVolumeID IN (SELECT VolumeID FROM CM_CPI_Volume WHERE VolumeNumber LIKE ''' + @SearchString + '%'')) 
    and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end) '  +
    	@ExtraSearch + 	   
	' ORDER BY [Volume Number]'

    execute (@SQL)
END

ELSE IF @FieldName = 'DefeciencyID'
BEGIN
	set @SQL = 'SELECT ' + @SQLTopX + '
        dbo.Def_SlipMain.DefID AS [DID], 
		dbo.Def_SlipMain.DefeciencyID AS [SearchItem#],
        CH.DisplayCode as [Chart Hospital Link],
		REPLACE(SPACE(10-LEN(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
        VH.DisplayCode as [Volume Hospital Link],
		dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number],
		(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
		(SELECT CONVERT(VARCHAR(10), isnull(DischargeDate, AdmitDate), 111) FROM AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
	    ISNULL(dbo.CM_CPI.LastName, '''') + '', '' + ISNULL(dbo.CM_CPI.FirstName, '''') + '' '' + ISNULL(dbo.CM_CPI.MiddleName, '''') AS [Patient Name], 
        DH.DisplayCode as [Def. Hospital Link],
		dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],
		(SELECT DisplayCode FROM LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
		(SELECT DisplayCode FROM DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status] into ' + @TempDB + '
	FROM dbo.Def_SlipMain
    	LEFT JOIN dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
    	LEFT JOIN dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID
        left join H_HospitalProfile DH on DH.Code = Def_SlipMain.HospitalID
        left join H_HospitalProfile CH on CH.Code = CM_CPI.HospitalID
        left join H_HospitalProfile VH on VH.Code = CM_CPI_Volume.HospitalID
	WHERE (ISNULL(dbo.Def_SlipMain.DefMainStatus, 0) not in (8, 11)) 
		AND (ISNULL(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else ISNULL(Def_SlipMain.HospitalID, 0) end) 	
    	AND (dbo.Def_SlipMain.DefeciencyID LIKE ''' + @SearchString + '%'') 
        and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end)  ' +
    	@ExtraSearch + 	
	' ORDER BY [Header Ref. ID]'

    execute (@SQL)
END

ELSE IF @FieldName = 'DefDrNumber'
BEGIN
		--(SELECT UserDescription FROM LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider Name],
	set @SQL = 'SELECT ' + @SQLTopX + ' 
        dbo.Def_SlipMain.DefID AS [DID], 
		(SELECT DisplayCode FROM LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [SearchItem#],
        CH.DisplayCode as [Chart Hospital Link],
		REPLACE(SPACE(10-LEN(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
        VH.DisplayCode as [Volume Hospital Link],
		dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number], 
		(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
		(SELECT CONVERT(VARCHAR(10), isnull(DischargeDate, AdmitDate), 111) FROM AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
	    ISNULL(dbo.CM_CPI.LastName, '''') + '', '' + ISNULL(dbo.CM_CPI.FirstName, '''') + '' '' + ISNULL(dbo.CM_CPI.MiddleName, '''') AS [Patient Name], 
        DH.DisplayCode as [Def. Hospital Link],
		dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],				
		(SELECT DisplayCode FROM LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
		(SELECT DisplayCode FROM DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status] into ' + @TempDB + '
	FROM dbo.Def_SlipMain
    	LEFT JOIN dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
    	LEFT JOIN dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID			
        left join H_HospitalProfile DH on DH.Code = Def_SlipMain.HospitalID
        left join H_HospitalProfile CH on CH.Code = CM_CPI.HospitalID
        left join H_HospitalProfile VH on VH.Code = CM_CPI_Volume.HospitalID
	WHERE (ISNULL(dbo.Def_SlipMain.DefMainStatus, 0) not in (8, 11)) 
		AND (ISNULL(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else ISNULL(Def_SlipMain.HospitalID, 0) end) 	
    	AND (dbo.Def_SlipMain.DefDrNumber IN (SELECT Code FROM LU_Provider WHERE DisplayCode LIKE ''' + @SearchString + '%'')) 
        and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end)   ' +
    	@ExtraSearch + 
	' ORDER BY [Provider #]'

    execute (@SQL)
END

ELSE IF @FieldName = 'DefPatLastName' AND @NameSplit = 0
BEGIN
	--13507: Moved to top	
	--Set @SearchString = replace(@SearchString, '''', '''''')
	set @SQL = 'SELECT ' + @SQLTopX + ' 
        dbo.Def_SlipMain.DefID AS [DID], 
	    ISNULL(dbo.CM_CPI.LastName, '''') AS [SearchItem#], 
        CH.DisplayCode as [Chart Hospital Link],
		REPLACE(SPACE(10-LEN(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
        VH.DisplayCode as [Volume Hospital Link],
		dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number], 
		(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
		(SELECT CONVERT(VARCHAR(10), isnull(DischargeDate, AdmitDate), 111) FROM AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
	    ISNULL(dbo.CM_CPI.LastName, '''') + '', '' + ISNULL(dbo.CM_CPI.FirstName, '''') + '' '' + ISNULL(dbo.CM_CPI.MiddleName, '''') AS [Patient Name], 
        DH.DisplayCode as [Def. Hospital Link],
		dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],				
		(SELECT DisplayCode FROM LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
		(SELECT DisplayCode FROM DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status] into ' + @TempDB + '
	FROM dbo.Def_SlipMain
    	LEFT JOIN dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
    	LEFT JOIN dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID			
        left join H_HospitalProfile DH on DH.Code = Def_SlipMain.HospitalID
        left join H_HospitalProfile CH on CH.Code = CM_CPI.HospitalID
        left join H_HospitalProfile VH on VH.Code = CM_CPI_Volume.HospitalID
	WHERE (ISNULL(dbo.Def_SlipMain.DefMainStatus, 0) not in (8, 11)) 
		AND (ISNULL(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else ISNULL(Def_SlipMain.HospitalID, 0) end) 	
    	AND (dbo.CM_CPI.LastName Like ''' + @SearchString + '%'' AND dbo.CM_CPI.IsDeleted = 2) 
        and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end)    ' +
    	@ExtraSearch + 
	' ORDER BY dbo.CM_CPI.LastName DESC, dbo.CM_CPI.FirstName'
    
    execute (@SQL)
END

ELSE IF @FieldName = 'DefPatLastName' AND @NameSplit > 0
BEGIN
	--13507: Moved to top	
	--Set @SearchString = replace(@SearchString, '''', '''''')
	Set @NameSplit = CHARINDEX(',', @SearchString) 
	--Set @SearchString = replace(@SearchString, '''', '''''')
	set @SQL = 'SELECT ' + @SQLTopX + ' 
        dbo.Def_SlipMain.DefID AS [DID], 
	    ISNULL(dbo.CM_CPI.LastName, '''') AS [SearchItem#], 
        CH.DisplayCode as [Chart Hospital Link],
		REPLACE(SPACE(10-LEN(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
        VH.DisplayCode as [Volume Hospital Link],
		dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number], 
		(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
		(SELECT CONVERT(VARCHAR(10), isnull(DischargeDate, AdmitDate), 111) FROM AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
	    ISNULL(dbo.CM_CPI.LastName, '''') + '', '' + ISNULL(dbo.CM_CPI.FirstName, '''') + '' '' + ISNULL(dbo.CM_CPI.MiddleName, '''') AS [Patient Name], 
        DH.DisplayCode as [Def. Hospital Link],
		dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],				
		(SELECT DisplayCode FROM LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
		(SELECT DisplayCode FROM DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status] into ' + @TempDB + '
	FROM dbo.Def_SlipMain
    	LEFT JOIN dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
    	LEFT JOIN dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID			
        left join H_HospitalProfile DH on DH.Code = Def_SlipMain.HospitalID
        left join H_HospitalProfile CH on CH.Code = CM_CPI.HospitalID
        left join H_HospitalProfile VH on VH.Code = CM_CPI_Volume.HospitalID
	WHERE (ISNULL(dbo.Def_SlipMain.DefMainStatus, 0) not in (8, 11)) 
		AND (ISNULL(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else ISNULL(Def_SlipMain.HospitalID, 0) end) 	
	AND (dbo.CM_CPI.LastName LIKE ''' + Left(@SearchString, @NameSplit-1) + '%'' 
	AND dbo.CM_CPI.FirstName LIKE ''' + Stuff(@SearchString,1, @NameSplit, '') + '%''
	AND dbo.CM_CPI.IsDeleted = 2) 
    and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end)    ' +
    	@ExtraSearch + 
	' ORDER BY dbo.CM_CPI.LastName DESC, dbo.CM_CPI.FirstName'

    execute (@SQL)
END

ELSE IF @FieldName = 'UserDescription'
BEGIN
	set @SQL = 'SELECT ' + @SQLTopX + ' 
        dbo.Def_SlipMain.DefID AS [DID], 
		(SELECT UserDescription FROM LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [SearchItem#],
        CH.DisplayCode as [Chart Hospital Link],
		REPLACE(SPACE(10-LEN(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
        VH.DisplayCode as [Volume Hospital Link],
		dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number], 
		(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
		(SELECT CONVERT(VARCHAR(10), isnull(DischargeDate, AdmitDate), 111) FROM AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
	    ISNULL(dbo.CM_CPI.LastName, '''') + '', '' + ISNULL(dbo.CM_CPI.FirstName, '''') + '' '' + ISNULL(dbo.CM_CPI.MiddleName, '''') AS [Patient Name], 
        DH.DisplayCode as [Def. Hospital Link],
		dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],				
		(SELECT DisplayCode FROM LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
		(SELECT DisplayCode FROM DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status] into ' + @TempDB + '
	FROM dbo.Def_SlipMain
    	LEFT JOIN dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
    	LEFT JOIN dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID			
        left join H_HospitalProfile DH on DH.Code = Def_SlipMain.HospitalID
        left join H_HospitalProfile CH on CH.Code = CM_CPI.HospitalID
        left join H_HospitalProfile VH on VH.Code = CM_CPI_Volume.HospitalID
	WHERE (ISNULL(dbo.Def_SlipMain.DefMainStatus, 0) not in (8, 11)) 
		AND (ISNULL(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else ISNULL(Def_SlipMain.HospitalID, 0) end) 	
	AND (dbo.Def_SlipMain.DefDrNumber IN (SELECT Code FROM LU_Provider WHERE UserDescription LIKE ''' + @SearchString + '%'')) 
    and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end)   ' +
    	@ExtraSearch + 
	' ORDER BY [Provider #]'
    set @FieldDescription = 'Provider Name'
    EXECUTE(@SQL)
END
--Ticket 9030. Unique Bar Code Volume
ELSE IF @FieldName = 'BarCodeVolume'
BEGIN

	set @SQL = 'SELECT ' + @SQLTopX + ' 
        dbo.Def_SlipMain.DefID AS [DID], 
--		(SELECT UserDescription FROM LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider Name],
        dbo.CM_CPI_Volume.BarCodeVolume as [SearchItem#], 
        CH.DisplayCode as [Chart Hospital Link],
		REPLACE(SPACE(10-LEN(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
        VH.DisplayCode as [Volume Hospital Link],
		dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number], 
		(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
		(SELECT CONVERT(VARCHAR(10), isnull(DischargeDate, AdmitDate), 111) FROM AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
	    ISNULL(dbo.CM_CPI.LastName, '''') + '', '' + ISNULL(dbo.CM_CPI.FirstName, '''') + '' '' + ISNULL(dbo.CM_CPI.MiddleName, '''') AS [Patient Name], 
        DH.DisplayCode as [Def. Hospital Link],
		dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],				
		(SELECT DisplayCode FROM LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
		(SELECT DisplayCode FROM DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status] into ' + @TempDB + '
	FROM dbo.Def_SlipMain
    	LEFT JOIN dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
    	LEFT JOIN dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID			
        left join H_HospitalProfile DH on DH.Code = Def_SlipMain.HospitalID
        left join H_HospitalProfile CH on CH.Code = CM_CPI.HospitalID
        left join H_HospitalProfile VH on VH.Code = CM_CPI_Volume.HospitalID
	WHERE (ISNULL(dbo.Def_SlipMain.DefMainStatus, 0) not in (8, 11)) 
		AND (ISNULL(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else ISNULL(Def_SlipMain.HospitalID, 0) end) 	
	AND (isnull(dbo.CM_CPI_Volume.BarCodeVolume, '''') LIKE ''' + @SearchString + '%'') 
    and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end)  ' +
    	@ExtraSearch + 
	' ORDER BY [Provider #]'
    
    EXECUTE(@SQL)
END

ELSE IF  @DataType in (11, 12, 13) --PR-01739
BEGIN
	Declare @Where as VarChar(1000)
	--EN-00081
	if right(@SearchString, 5) = '00/00' 
		set @where = '(' + @FieldName + ' >= Convert(DateTime, ''' + left(@SearchString, 5) + '01/01'') and ' + @FieldName + ' <= convert(DateTime, ''' + left(@SearchString, 5) + '12/31'')) '

	else if right(@SearchString, 2) = '00' 
		set @where = '(' + @FieldName + ' >= Convert(DateTime, ''' + left(@SearchString, 8) + '01'') and ' + @FieldName + ' < dateadd(M, 1, Convert(DateTime, ''' + left(@SearchString, 8) + '01''))) '

	Else if (isdate(@SearchString) = 0) 
		set @SearchString = '1950/01/01'

	If isnull(@where, '') = ''
	        set @where = @FieldName + ' = Convert(DateTime, ''' + @SearchString + ''') '
 	SELECT @SQL = 
		'SELECT ' + @SQLTopX + ' 
        dbo.Def_SlipMain.DefID AS [DID], 
		CONVERT (VarChar(10), ' + @FieldName + ', 111) AS [SearchItem#],  
        CH.DisplayCode as [Chart Hospital Link],
		REPLACE(SPACE(10-LEN(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
        VH.DisplayCode as [Volume Hospital Link],
		dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number], 
		(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
		(SELECT CONVERT(VARCHAR(10), isnull(DischargeDate, AdmitDate), 111) FROM AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
		ISNULL(dbo.CM_CPI.LastName, '''') + '', '' + ISNULL(dbo.CM_CPI.FirstName, '''') + '' '' + ISNULL(dbo.CM_CPI.MiddleName, '''') AS [Patient Name], 
        DH.DisplayCode as [Def. Hospital Link],
		dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],
		(SELECT DisplayCode FROM LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
		(SELECT DisplayCode FROM DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status] into ' + @TempDB + '
		FROM dbo.Def_SlipMain
    		LEFT JOIN dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
    		LEFT JOIN dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID
            left join H_HospitalProfile DH on DH.Code = Def_SlipMain.HospitalID
            left join H_HospitalProfile CH on CH.Code = CM_CPI.HospitalID
            left join H_HospitalProfile VH on VH.Code = CM_CPI_Volume.HospitalID
		WHERE (ISNULL(dbo.Def_SlipMain.DefMainStatus, 0) not in (8, 11)) 
		AND (ISNULL(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else ISNULL(Def_SlipMain.HospitalID, 0) end) 	
        and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end)   
		AND ' + @where + 
        @ExtraSearch + 	        
        ' ORDER BY ' + @FieldName 
 	EXECUTE(@SQL)
END
ELSE
BEGIN
	SELECT @SQL = 
		'SELECT ' + @SQLTopX + ' 
        dbo.Def_SlipMain.DefID AS [DID], ' + 
		@FieldName + ' AS [SearchItem#],  
        CH.DisplayCode as [Chart Hospital Link], 
		REPLACE(SPACE(10-LEN(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'') AS [Chart Number], 
        VH.DisplayCode as [Volume Hospital Link],
		dbo.CM_CPI_Volume.VolumeNumber AS [Volume Number], 
		(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [Volume Type], 
		(SELECT CONVERT(VARCHAR(10), isnull(DischargeDate, AdmitDate), 111) FROM AB_Main WHERE UniversalID = dbo.Def_SlipMain.DefAbstractID) AS [Visit Date],
		ISNULL(dbo.CM_CPI.LastName, '''') + '', '' + ISNULL(dbo.CM_CPI.FirstName, '''') + '' '' + ISNULL(dbo.CM_CPI.MiddleName, '''') AS [Patient Name], 
        DH.DisplayCode as [Def. Hospital Link],
		dbo.Def_SlipMain.DefeciencyID AS [Header Ref. ID],
		(SELECT DisplayCode FROM LU_Provider WHERE Code = dbo.Def_SlipMain.DefDrNumber) AS [Provider #],
		(SELECT DisplayCode FROM DefLU_ChartStatus WHERE Code = dbo.Def_SlipMain.DefMainStatus) AS [Status] into ' + @TempDB + '
		FROM dbo.Def_SlipMain
    		LEFT JOIN dbo.CM_CPI ON dbo.Def_SlipMain.DefPatientID = dbo.CM_CPI.PatientID
    		LEFT JOIN dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID
            left join H_HospitalProfile DH on DH.Code = Def_SlipMain.HospitalID
            left join H_HospitalProfile CH on CH.Code = CM_CPI.HospitalID
            left join H_HospitalProfile VH on VH.Code = CM_CPI_Volume.HospitalID
		WHERE (ISNULL(dbo.Def_SlipMain.DefMainStatus, 0) not in (8, 11)) 
		AND (ISNULL(Def_SlipMain.HospitalID, 0) = 0 OR ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else ISNULL(Def_SlipMain.HospitalID, 0) end) 	
        and (isnull(dbo.CM_CPI.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(dbo.CM_CPI.HospitalID, 0) end) ' +
        (case when isnull(@SearchString, '') = '' then '' else ' AND ' + @FieldName + ' LIKE ''%' + @SearchString + '%'' ' end) +
        @ExtraSearch + 	
        ' ORDER BY ' + @FieldName 
    --print @sql
	EXECUTE(@SQL)
END

If @ShowVip <> '1'
Begin
	set @SQL = 'delete ' + @TempDB + ' where [Chart Number] in (select replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') 
		from CM_CPI where isnull(secret, 0) = 1 and replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')
		in (select [Chart Number] from ' + @TempDB + '))'
	Exec(@SQL)
End

--print @sql
If @SearchAudit = 1
Begin
    set @sql = 'insert into AU_SearchDetail select 15, [DID], ' + cast(isnull(@UserID, 0) as varchar(10)) + ', getdate() as Field2 from ' + @TempDB  
    exec (@sql)
end


set @sql = 'select [DID], [' + @FieldDescription + '] = [SearchItem#], [Chart Hospital Link], [Chart Number], [Volume Hospital Link], [Volume Number], [Volume Type], [Visit Date], [Patient Name], [Def. Hospital Link], [Header Ref. ID], [Provider #], [Status] from  ' + @TempDB 
exec (@sql)
set nocount off
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE       PROCEDURE [F_SearchDeficiency_VH]
	@SearchCode as Integer,
	@ChartNumber as VarChar(10),
    @HospID as int = 0
AS 
	IF @SearchCode <> 0
		BEGIN
			SELECT UniversalID,  CONVERT(VarChar(10), DischargeDate, 111) AS [Discharge Date],  
				isnull(ICDType, '') + ': ' + 
				CONVERT(VarChar(1), (SELECT DisplayCode FROM LU_CareType WHERE Code = AppType)) + ': ' + 
				isnull(EncounterNumber, '') + ' - ' + 
				REPLACE(SPACE(3-LEN(ISNULL(CONVERT(VARCHAR(3), EncounterSequence), 0))) + ISNULL(CONVERT(VARCHAR(3), EncounterSequence), 0), ' ', '0')  AS [Abstract Information]
			FROM AB_Main
			WHERE UniversalID = @SearchCode
			AND IsDeleted = 2 and apptype <> 0
			ORDER BY DischargeDate DESC
		END
	ELSE
		BEGIN
			SELECT UniversalID,  CONVERT(VarChar(10), DischargeDate, 111) AS [Discharge Date],  
				isnull(ICDType, '') + ': ' + 
				CONVERT(VarChar(1), (SELECT DisplayCode FROM LU_CareType WHERE Code = AppType)) + ': ' + 
				isnull(EncounterNumber, '') + ' - ' + 
				REPLACE(SPACE(3-LEN(ISNULL(CONVERT(VARCHAR(3), EncounterSequence), 0))) + ISNULL(CONVERT(VARCHAR(3), EncounterSequence), 0), ' ', '0')  AS [Abstract Information]
			FROM AB_Main
			WHERE ChartNumber = @ChartNumber
            and ChartNumber in (select ChartNumber from CM_CPI where (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)) 
			AND IsDeleted = 2 and apptype <> 0
			ORDER BY DischargeDate DESC
		END
	RETURN 0



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE  PROCEDURE [F_SearchDeficiency_Volume]
	@SearchCode as Integer,
	@SearchString as VarChar(50),
	@PatientID as Integer,
	@HospID as integer = 0
AS 

	IF @SearchCode <> 0
		BEGIN
			SELECT VolumeID, VolumeNumber AS [Volume Number], ISNULL(CONVERT(VARCHAR(10), VolumeDateFrom, 111), '')+ ' - ' + ISNULL(CONVERT(VARCHAR(10), VolumenDateTo, 111), '') AS [Date Range]
			FROM CM_CPI_Volume
			WHERE VolumeID = @SearchCode
			--AND PatientID = @PatientID
		END
	ELSE
		BEGIN
			SELECT top 999 VolumeID, VolumeNumber AS [Volume Number], ISNULL(CONVERT(VARCHAR(10), VolumeDateFrom, 111), '')+ ' - ' + ISNULL(CONVERT(VARCHAR(10), VolumenDateTo, 111), '') AS [Date Range]
			FROM CM_CPI_Volume
			WHERE VolumeNumber LIKE @SearchString + '%'
			AND PatientID = @PatientID
			AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end) 
		END
	RETURN 0



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--EN-00183
CREATE  procedure [F_SearchDeficiencyByProvider]
    @DefProvider int,
    @HospID int = 0,
    @AccessLockChart int = 1,
    @VIP int = 0
as
select 
    Def.DefID,
    DefHospital = dh.DisplayCode,
    HeaderID = Def.DefeciencyID, 
    DetailID = Act.DefeciencyID,
    DefCode = DCode.DisplayCode,
    DetailStatus = D.DisplayCode,
    CPIHospital = ch.DisplayCode,
    ChartNumber = isnull(cpi.ChartNumber, ''), 
    FullName = isnull(isnull(DefPatFirstName, cpi.FirstName), '') + ' ' + isnull(isnull(DefPatLastName, cpi.LastName), ''),
--    InstitutionNumber = isnull(H.DisplayCode, ''),
    VisitDate = isnull(AB.DischargeDate, AB.AdmitDate),
    Def.DefStartDate, 
    MainDefStatus = isnull(C.DisplayCode, '') 
from Def_SlipMain Def 
    inner join CM_CPI cpi on Def.DefPatientID = cpi.PatientID 
    inner join DefLU_ChartStatus C on Def.DefMainStatus = C.Code 
    inner join Def_Activity Act on Def.DefID = Act.DefID
--    inner join Def_Activity Act on Def.DefeciencyID = Act.HeaderDefID
    inner join DefLU_ChartStatus D on Act.DefStatus = D.Code 
    inner join DefLU_DeficiencyCode DCode on Act.DefCode = DCode.Code 
--    left join H_InstitutionProfile H on Def.DefInstNumber = H.Code 
    left join AB_Main AB on Def.DefAbstractID = AB.UniversalID
    left join H_HospitalProfile dh on Def.HospitalID = dh.code
    left join H_HospitalProfile ch on cpi.HospitalID = ch.code
where C.DisplayCode not in ('C', 'X') and DefDrNumber = @DefProvider
    and D.DisplayCode not in ('C', 'X')
    and (isnull(cpi.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(cpi.HospitalID, 0) end) 
    --PR - 02149
    and (isnull(Def.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(Def.HospitalID, 0) end) 
    --PR-01006
    and ((cpi.LastName not like '%merged%' and cpi.FirstName not like '%merged%') or @AccessLockChart = 1)
    and (@VIP = 1 or isnull(cpi.Secret, 0) <> 1)    --PR - 06095
order by Def.DefeciencyID, Act.DefeciencyID



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--This store procedure 
CREATE procedure [F_SearchDeficiencyBySearch]
    @SearchType     int, 
    @SearchString1  varchar(100),
    @SearchString2  varchar(100),
    @ExactMatch1    int,
    @ExactMatch2    int,
    @HospID int = 0
as
declare @Sql varchar(2000)
set @SearchString1 = replace(@SearchString1, '''', '''''')
set @SearchString2 = replace(@SearchString2, '''', '''''')

if @SearchType = 0    --ChartNumber & Volume
begin
    set @Sql = '
        select top 100 
            Def.DefID,
            dh.DisplayCode as DefHospital,
            Def.DefeciencyID, D.DefeciencyID as DetailID, 
            ch.DisplayCode as CPIHospital, ChartNumber = isnull(cpi.ChartNumber, ''''), 
            FullName = isnull(isnull(DefPatFirstName, cpi.FirstName), '''') + '' '' + isnull(isnull(DefPatLastName, cpi.LastName), ''''),
            InstitutionNumber = isnull(H.DisplayCode, ''''),
            AB.DischargeDate, DefStatus = isnull(C.DisplayCode, ''''), 
            Def.DefStartDate, P.DisplayCode as Provider 
        from Def_SlipMain Def 
            inner join Def_Activity D on Def.DefID = D.DefID
            inner join CM_CPI cpi on Def.DefPatientID = cpi.PatientID 
            inner join DefLU_ChartStatus C on Def.DefMainStatus = C.Code 
            inner join DefLU_ChartStatus DC on D.DefStatus = DC.Code 
            left join H_InstitutionProfile H on Def.DefInstNumber = H.Code 
            left join AB_Main AB on Def.DefAbstractID = AB.UniversalID 
            left join CM_CPI_Volume V on cpi.patientid = V.PatientID and DEF.DefVolumeID = V.VolumeID
            left join LU_Provider P on Def.DefDrNumber = P.Code
            left join H_HospitalProfile dh on Def.HospitalID = dh.code
            left join H_HospitalProfile ch on cpi.HospitalID = ch.code
            left join H_HospitalProfile vh on v.HospitalID = vh.code
        where C.DisplayCode not in (''C'', ''X'') and DC.DisplayCode not in (''C'', ''X'') 
            and cpi.ChartNumber ' +
        (case when @ExactMatch1 = 1 
              then '= ''' + @SearchString1 + ''' ' 
              else 'like ''' + @SearchString1 + '%'' ' end) +
        (case when isnull(@SearchString2, '') <> ''
              then ' and V.VolumeNumber ' + (case when @ExactMatch2 = 1 
                        then '= ''' + @SearchString2 + ''' '
                        else 'like ''%' + @SearchString2 + '%'' ' end)
              else '' end) +
        'and (isnull(cpi.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(cpi.HospitalID, 0) end) 
        order by Def.DefeciencyID, D.DefeciencyID '
    --print @sql
    exec (@sql)
end
else if @SearchType = 1    --Header ID
begin
    select top 100 
        Def.DefID,
        dh.DisplayCode as DefHospital,
        Def.DefeciencyID, D.DefeciencyID as DetailID, 
        ch.DisplayCode as CPIHospital, ChartNumber = isnull(cpi.ChartNumber, ''), 
        FullName = isnull(isnull(DefPatFirstName, cpi.FirstName), '') + ' ' + isnull(isnull(DefPatLastName, cpi.LastName), ''),
        InstitutionNumber = isnull(H.DisplayCode, ''),
        AB.DischargeDate, DefStatus = isnull(C.DisplayCode, ''),
        Def.DefStartDate, 
        P.DisplayCode as Provider  
    from Def_SlipMain Def 
        inner join Def_Activity D on Def.DefID = D.DefID
--EN-00183
--        inner join Def_Activity D on Def.DefeciencyID = D.HeaderDefID
        inner join CM_CPI cpi on Def.DefPatientID = cpi.PatientID 
        inner join DefLU_ChartStatus C on Def.DefMainStatus = C.Code 
        inner join DefLU_ChartStatus DC on D.DefStatus = DC.Code 
        left join H_InstitutionProfile H on Def.DefInstNumber = H.Code 
        left join AB_Main AB on Def.DefAbstractID = AB.UniversalID 
        left join CM_CPI_Volume V on cpi.patientid = V.PatientID and DEF.DefVolumeID = V.VolumeID
        left join LU_Provider P on Def.DefDrNumber = P.Code
        left join H_HospitalProfile dh on Def.HospitalID = dh.code
        left join H_HospitalProfile ch on cpi.HospitalID = ch.code
        left join H_HospitalProfile vh on v.HospitalID = vh.code
    where C.DisplayCode not in ('C', 'X') and DC.DisplayCode not in ('C', 'X') 
        and Def.DefeciencyID = @SearchString1
    and (isnull(cpi.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(cpi.HospitalID, 0) end) 
    order by Def.DefeciencyID, D.DefeciencyID 
end
else if @SearchType = 2    --DEF Detail ID
begin
    select top 100 
        Def.DefID,
        dh.DisplayCode as DefHospital,
        Def.DefeciencyID, D.DefeciencyID as DetailID, 
        ch.DisplayCode as CPIHospital, ChartNumber = isnull(cpi.ChartNumber, ''), 
        FullName = isnull(isnull(DefPatFirstName, cpi.FirstName), '') + ' ' + isnull(isnull(DefPatLastName, cpi.LastName), ''),
        InstitutionNumber = isnull(H.DisplayCode, ''),
        AB.DischargeDate, DefStatus = isnull(C.DisplayCode, ''), 
        Def.DefStartDate, 
        P.DisplayCode as Provider  
    from Def_SlipMain Def 
        inner join Def_Activity D on Def.DefID = D.DefID
--EN-00183
--        inner join Def_Activity D on Def.DefeciencyID = D.HeaderDefID
        inner join CM_CPI cpi on Def.DefPatientID = cpi.PatientID 
        inner join DefLU_ChartStatus C on Def.DefMainStatus = C.Code 
        inner join DefLU_ChartStatus DC on D.DefStatus = DC.Code 
        left join H_InstitutionProfile H on Def.DefInstNumber = H.Code 
        left join AB_Main AB on Def.DefAbstractID = AB.UniversalID 
        left join CM_CPI_Volume V on cpi.patientid = V.PatientID and DEF.DefVolumeID = V.VolumeID
        left join LU_Provider P on Def.DefDrNumber = P.Code
        left join H_HospitalProfile dh on Def.HospitalID = dh.code
        left join H_HospitalProfile ch on cpi.HospitalID = ch.code
        left join H_HospitalProfile vh on v.HospitalID = vh.code
    where C.DisplayCode not in ('C', 'X') and DC.DisplayCode not in ('C', 'X') 
        and D.DefeciencyID = @SearchString1
    and (isnull(cpi.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(cpi.HospitalID, 0) end) 
    order by Def.DefeciencyID, D.DefeciencyID 
end
else if @SearchType = 3 -- Volume
begin
    select top 100 
        Def.DefID,
        dh.DisplayCode as DefHospital,
        Def.DefeciencyID, D.DefeciencyID as DetailID, 
        ch.DisplayCode as CPIHospital, ChartNumber = isnull(cpi.ChartNumber, ''), 
        FullName = isnull(isnull(DefPatFirstName, cpi.FirstName), '') + ' ' + isnull(isnull(DefPatLastName, cpi.LastName), ''),
        InstitutionNumber = isnull(H.DisplayCode, ''),
        AB.DischargeDate, DefStatus = isnull(C.DisplayCode, ''),
        Def.DefStartDate, 
        P.DisplayCode as Provider  
    from Def_SlipMain Def 
        inner join Def_Activity D on Def.DefID = D.DefID
--EN-00183
--        inner join Def_Activity D on Def.DefeciencyID = D.HeaderDefID
        inner join CM_CPI cpi on Def.DefPatientID = cpi.PatientID 
        inner join DefLU_ChartStatus C on Def.DefMainStatus = C.Code 
        inner join DefLU_ChartStatus DC on D.DefStatus = DC.Code 
        left join H_InstitutionProfile H on Def.DefInstNumber = H.Code 
        left join AB_Main AB on Def.DefAbstractID = AB.UniversalID 
        left join CM_CPI_Volume V on cpi.patientid = V.PatientID and DEF.DefVolumeID = V.VolumeID
        left join LU_Provider P on Def.DefDrNumber = P.Code
        left join H_HospitalProfile dh on Def.HospitalID = dh.code
        left join H_HospitalProfile ch on cpi.HospitalID = ch.code
        left join H_HospitalProfile vh on v.HospitalID = vh.code
    where C.DisplayCode not in ('C', 'X') and DC.DisplayCode not in ('C', 'X') 
        and V.BarCodeVolume = @SearchString1        
    and (isnull(cpi.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(cpi.HospitalID, 0) end) 
    order by Def.DefeciencyID, D.DefeciencyID 
end








GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO








CREATE        PROCEDURE [F_SearchHospital]
	@SearchString as VarChar(50),
	@HospID as int = 0
AS 

IF @SearchString = '' 
	If @HospID = 0
		SELECT Code As [ ], DisplayCode as [Hosp ID], UserDescription AS [Name]
		FROM dbo.H_HospitalProfile ORDER BY DisplayCode
	else
		SELECT Code As [ ], DisplayCode as [Hosp ID], UserDescription AS [Name]
		FROM dbo.H_HospitalProfile 
		WHERE (ISNULL(Code, 0) = 0 OR ISNULL(Code, 0) = @HospID)
ELSE
	If @HospID = 0
		SELECT Code As [ ], DisplayCode as [Hosp ID], UserDescription AS [Name]
		FROM dbo.H_HospitalProfile WHERE DisplayCode LIKE @SearchString + '%' ORDER BY DisplayCode
	else
		SELECT Code As [ ], DisplayCode as [Hosp ID], UserDescription AS [Name]
		FROM dbo.H_HospitalProfile 		
		WHERE (ISNULL(Code, 0) = 0 OR ISNULL(Code, 0) = @HospID)
		AND DisplayCode LIKE @SearchString + '%' ORDER BY DisplayCode





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO








-- Called by the Institution Profile Search Form w/ Param to load Institution
-- And the Hosp Prof/Inst Prof w/out Param to load entire list.
CREATE       PROCEDURE [F_SearchInstitution]
	@SearchString as VarChar(50),
	@HospID as int = 0
AS 

IF @SearchString = '' 
	BEGIN
		SELECT 	dbo.H_InstitutionProfile.Code As [ ], 
				(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H_InstitutionProfile.HospitalID, 0)) as [Hosp ID],
				dbo.H_InstitutionProfile.DisplayCode as [Inst. #], 
				dbo.H_InstitutionProfile.UserDescription AS [Name],
				dbo.LU_CareType.DisplayCode As [Care]
		FROM dbo.H_InstitutionProfile 
		LEFT JOIN dbo.LU_CareType
		ON dbo.H_InstitutionProfile.AssociationID = dbo.LU_CareType.Code
		WHERE (ISNULL(H_InstitutionProfile.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(H_InstitutionProfile.HospitalID, 0) end)
		ORDER BY [Hosp ID], dbo.H_InstitutionProfile.DisplayCode
	END

ELSE
	BEGIN
		SELECT 	dbo.H_InstitutionProfile.Code As [ ], 
				(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H_InstitutionProfile.HospitalID, 0)) as [Hosp ID],
				dbo.H_InstitutionProfile.DisplayCode as [Institution Number], 
				dbo.H_InstitutionProfile.UserDescription AS [Name],
				dbo.LU_CareType.DisplayCode As [Care Type]
		FROM dbo.H_InstitutionProfile 
		LEFT JOIN dbo.LU_CareType
		ON dbo.H_InstitutionProfile.AssociationID = dbo.LU_CareType.Code
		WHERE dbo.H_InstitutionProfile.DisplayCode LIKE @SearchString + '%'
		AND (ISNULL(H_InstitutionProfile.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(H_InstitutionProfile.HospitalID, 0) end)
		ORDER BY [Hosp ID], dbo.H_InstitutionProfile.DisplayCode
	END







GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [F_SearchLocator_BarCode]
	@SearchString as VarChar(50),
	@Exact as int = 0,
    @HospID as int = 0,
    @AccessLockChart as int = 1
AS 
--EN-00183
if @Exact = 0

	SELECT top 999 v.VolumeID AS [ ], 
        isnull(ch.DisplayCode, '') as [Chart Hospital Link],
        --PR - 06101
        c.ChartNumber,
		--REPLACE(SPACE(10 - LEN(c.ChartNumber)) + c.ChartNumber, ' ', '0') AS ChartNumber, 
		(select DisplayCode from LoanLU_VolumeType where Code = v.VolumeType) as [Volume Type], 
        vh.DisplayCode as [Volume Hospital Link],
		v.VolumeNumber AS [Volume], 
		ISNULL(c.LastName, '') + ', ' + ISNULL(c.FirstName, '') + ' ' + ISNULL(c.MiddleName, '') AS [Full Name], 
        isnull(D.DisplayCode, '') as [Expirted],
		CONVERT(VarChar(10), c.BirthDate, 111) AS [Birth Date], 
		cl.DisplayCode AS [Current Location],
        FL.DisplayCode AS [Previous Location], 
		PL.DisplayCode AS [Permanent Location],
        v.CLBoxNumber as [Box Number],
		CONVERT(VarChar(10), c.LastVisitDate, 111) AS [Last Visit Date], 
		v.VolumeDateFrom AS [Date From],
		v.VolumenDateTo AS [Date To],
		isnull(Digit.DisplayCode, '') as [Digital]  --TS-222
	FROM dbo.CM_CPI_Volume v inner join
         dbo.CM_CPI c ON v.PatientID = c.PatientID LEFT OUTER JOIN
         dbo.LoanLU_Location CL ON v.CLCurrentLocation = CL.Code LEFT OUTER JOIN
         dbo.LoanLU_Location PL ON v.PermLocation = PL.Code LEFT OUTER JOIN
         dbo.LoanLU_Location FL ON v.CLPreviousLocation = FL.Code LEFT OUTER JOIN
         H_HospitalProfile CH on c.HospitalID = CH.Code LEFT OUTER JOIN
         H_HospitalProfile VH on v.HospitalID = VH.Code left join
         LU_YesNoSystem D on c.DeathIndicator = D.Code left join
            dbo.LoanLU_DigitalIndicator Digit on v.DigitalIndicator = Digit.code
	WHERE (v.BarCodeVolume LIKE @SearchString + '%') AND c.IsDeleted = 2
    	AND (ISNULL(v.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(v.HospitalID, 0) end)
	    AND (ISNULL(c.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(c.HospitalID, 0) end)
        --PR-01006
        and ((LastName not like '%merged%' and FirstName not like '%merged%') or @AccessLockChart = 1)
	ORDER BY c.ChartNumber, v.VolumeNumber

if @Exact = 1
	SELECT top 999 v.VolumeID AS [ ], 
        isnull(ch.DisplayCode, '') as [Chart Hospital Link],
		--PR - 06101
        c.ChartNumber,
		--REPLACE(SPACE(10 - LEN(c.ChartNumber)) + c.ChartNumber, ' ', '0') AS ChartNumber, 
		(select DisplayCode from LoanLU_VolumeType where Code = v.VolumeType) as [Volume Type], 
        vh.DisplayCode as [Volume Hospital Link],
		v.VolumeNumber AS [Volume], 
		ISNULL(c.LastName, '') + ', ' + ISNULL(c.FirstName, '') + ' ' + ISNULL(c.MiddleName, '') AS [Full Name], 
        isnull(D.DisplayCode, '') as [Expirted],
		CONVERT(VarChar(10), c.BirthDate, 111) AS [Birth Date], 
		cl.DisplayCode AS [Current Location],
        FL.DisplayCode AS [Previous Location], 
		PL.DisplayCode AS [Permanent Location],
        v.CLBoxNumber as [Box Number],
		CONVERT(VarChar(10), c.LastVisitDate, 111) AS [Last Visit Date], 
		v.VolumeDateFrom AS [Date From],
		v.VolumenDateTo AS [Date To],
		isnull(Digit.DisplayCode, '') as [Digital]  --TS-222
	FROM dbo.CM_CPI_Volume v inner join
         dbo.CM_CPI c ON v.PatientID = c.PatientID LEFT OUTER JOIN
         dbo.LoanLU_Location CL ON v.CLCurrentLocation = CL.Code LEFT OUTER JOIN
         dbo.LoanLU_Location PL ON v.PermLocation = PL.Code LEFT OUTER JOIN
         dbo.LoanLU_Location FL ON v.CLPreviousLocation = FL.Code LEFT OUTER JOIN
         H_HospitalProfile CH on c.HospitalID = CH.Code LEFT OUTER JOIN
         H_HospitalProfile VH on v.HospitalID = VH.Code left join
         LU_YesNoSystem D on c.DeathIndicator = D.Code left join
            dbo.LoanLU_DigitalIndicator Digit on v.DigitalIndicator = Digit.code
	WHERE (v.BarCodeVolume = @SearchString) AND c.IsDeleted = 2
    	AND (ISNULL(v.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(v.HospitalID, 0) end)
	    AND (ISNULL(c.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(c.HospitalID, 0) end)
        --PR-01006
        and ((LastName not like '%merged%' and FirstName not like '%merged%') or @AccessLockChart = 1)
	ORDER BY c.ChartNumber, v.VolumeNumber
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [F_SearchLocator_ByVolumeID]
	@VolumeID as Int,
    @HospID as int = 0
AS 
    SELECT 
        v.VolumeID AS [ ], 
        isnull(ch.DisplayCode, '') as [Chart Hospital Link],
		--PR - 06101
        c.ChartNumber,
		--REPLACE(SPACE(10 - LEN(c.ChartNumber)) + c.ChartNumber, ' ', '0') AS ChartNumber, 
		(select DisplayCode from LoanLU_VolumeType where Code = v.VolumeType) as [Volume Type], 
        vh.DisplayCode as [Volume Hospital Link],
		v.VolumeNumber AS [Volume], 
		ISNULL(c.LastName, '') + ', ' + ISNULL(c.FirstName, '') + ' ' + ISNULL(c.MiddleName, '') AS [Full Name], 
        isnull(D.DisplayCode, '') as [Expirted],
		CONVERT(VarChar(10), c.BirthDate, 111) AS [Birth Date], 
		cl.DisplayCode AS [Current Location],
        FL.DisplayCode AS [Previous Location], 
		PL.DisplayCode AS [Permanent Location],
        v.CLBoxNumber as [Box Number],
		CONVERT(VarChar(10), c.LastVisitDate, 111) AS [Last Visit Date], 
		v.VolumeDateFrom AS [Date From],
		v.VolumenDateTo AS [Date To],
		isnull(Digit.DisplayCode, '') as [Digital]  --TS-222
	FROM dbo.CM_CPI_Volume v inner join
         dbo.CM_CPI c ON v.PatientID = c.PatientID LEFT OUTER JOIN
         dbo.LoanLU_Location CL ON v.CLCurrentLocation = CL.Code LEFT OUTER JOIN
         dbo.LoanLU_Location PL ON v.PermLocation = PL.Code LEFT OUTER JOIN
         dbo.LoanLU_Location FL ON v.CLPreviousLocation = FL.Code LEFT OUTER JOIN
         H_HospitalProfile CH on c.HospitalID = CH.Code LEFT OUTER JOIN
         H_HospitalProfile VH on v.HospitalID = VH.Code left join
         LU_YesNoSystem D on c.DeathIndicator = D.Code left join
         dbo.LoanLU_DigitalIndicator Digit on v.DigitalIndicator = Digit.code
	WHERE v.VolumeID = @VolumeID
    and (isnull(c.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(c.HospitalID, 0) end) 
    RETURN 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [F_SearchLocator_Chart]
	@SearchString as VarChar(50),
	@SearchString2 as VarChar(50),
	@MatchChart as VarChar(1),
	@MatchVolume as VarChar(1),
	@SearchType as Int,
	@Exact as int = 0,
	@HospID as int = 0,
    @AccessLockChart as int = 1
AS 
DECLARE @NameSplit as int
SELECT @NameSplit = CHARINDEX(',', @SearchString) 
declare @sql varchar(5000)
declare @StartDate varchar(20)
declare @EndDate   varchar(20)
declare @Year      int

if @Exact = 1
begin
    set @MatchChart = 'Y'
    set @MatchVolume = 'Y'
end

--ED-00344
declare @VolSort as int 
declare @HCnt as int 

select @HCnt = count(*) from H_HospitalProfile
-- For multi-hospitals, don't go to the hospital profile at all if we don't have a key
if @HCnt = 1 and @HospID = 0 select top 1 @VolSort = isnull(VolumeSort, 0) from H_HospitalProfile 
if @HospID > 0 select top 1 @VolSort = isnull(VolumeSort, 0) from H_HospitalProfile where HospitalID = @HospID
if isnull(@VolSort, 0) = 0 select top 1 @VolSort = isnull(VolumeSort, 0) from H_RegionProfile
if isnull(@VolSort, 0) = 0 set @VolSort = 200431

IF @SearchType = 1 
BEGIN
        set @SearchString = replace(@SearchString, '''', '''''')
        set @SearchString2 = replace(dbo.RemoveLeadingZero(@SearchString2), '''', '''''')
        set @sql = 'SELECT top 999 v.VolumeID AS [ ], ' +
                		'isnull(ch.DisplayCode, '''') as [Chart Hospital Link], ' +
                --PR - 06101
                'c.ChartNumber, ' +
				--'REPLACE(SPACE(10 - LEN(c.ChartNumber)) + c.ChartNumber, '' '', ''0'') AS ChartNumber, ' +
				'(select DisplayCode from LoanLU_VolumeType where Code = v.VolumeType) as [Volume Type], ' + 
                		'vh.DisplayCode as [Volume Hospital Link], ' +
				'v.VolumeNumber AS [Volume], ' +
				'ISNULL(c.LastName, '''') + '', '' + ISNULL(c.FirstName, '''') + '' '' + ISNULL(c.MiddleName, '''') AS [Full Name], ' +
                		'isnull(D.DisplayCode, '''') as [Expirted], ' +
				'CONVERT(VarChar(10), c.BirthDate, 111) AS [Birth Date], ' +
				'cl.DisplayCode AS [Current Location], ' +
				'FL.DisplayCode AS [Previous Location], ' +
        			'PL.DisplayCode AS [Permanent Location], ' +
                		'v.CLBoxNumber as [Box Number], ' +
				'CONVERT(VarChar(10), c.LastVisitDate, 111) AS [Last Visit Date], ' +
				'v.VolumeDateFrom AS [Date From], ' +
				'v.VolumenDateTo AS [Date To], ' + 
				'isnull(Digit.DisplayCode, '''') as [Digital] ' + --TS-222
			'FROM dbo.CM_CPI_Volume v inner JOIN dbo.CM_CPI c ON v.PatientID = c.PatientID ' +
			'LEFT OUTER JOIN dbo.LoanLU_Location cl ON v.CLCurrentLocation = cl.Code ' + 
			'LEFT OUTER JOIN dbo.LoanLU_Location PL ON v.PermLocation = PL.Code ' + 
			'LEFT OUTER JOIN dbo.LoanLU_Location FL ON v.CLPreviousLocation = FL.Code ' + 
			'LEFT OUTER JOIN H_HospitalProfile ch on  c.HospitalID = ch.code ' + 
			'LEFT JOIN H_HospitalProfile vh on  v.HospitalID = vh.code ' + 
			'LEFT JOIN LU_YesNoSystem D on c.DeathIndicator = D.Code ' + 
			'left join dbo.LoanLU_DigitalIndicator Digit on v.DigitalIndicator = Digit.code ' + 
        	'WHERE c.IsDeleted = 2 ' + 
            		(case when isnull(@SearchString, '') <> '' then ' and ' +
                	(case when @MatchChart = 'Y' 
                      		then '(c.ChartNumber = ''' + @SearchString + ''') ' 
                      		else '(c.ChartNumber LIKE ''' + @SearchString + '%'') ' end) 
                	else '' end) +
            		(case when isnull(@SearchString2, '') <> '' then ' and ' +
                	(case when @MatchVolume = 'Y' 
                      		then '(dbo.RemoveLeadingZero(v.VolumeNumber) = ''' + @SearchString2 + ''') ' 
                      		else '(dbo.RemoveLeadingZero(v.VolumeNumber) LIKE ''' + @SearchString2 + '%'') ' end) 
                	else '' end) + 
            		(case when isnull(@HospID, 0) = 0 then ''
                  		else  'and (ISNULL(c.HospitalID, 0) in (0, ' + cast(@HospID as varchar(10)) + ')) and ' + 
                        	'(ISNULL(v.HospitalID, 0) in (0, ' + cast(@HospID as varchar(10)) + ')) ' end) + ' ' +
            --PR-01006
            		(case when @AccessLockChart <> 1 then
	            		'and (LastName not like ''%merged%'' and FirstName not like ''%merged%'') ' else '' end) --+
                  --else  'and (ISNULL(v.HospitalID, 0) = ' + cast(@HospID as varchar(10)) + ' or ISNULL(v.HospitalID, 0) = 0) ' end) + ' ' +
            -- 13111 sort order by volume descend
			--'ORDER BY c.ChartNumber, dbo.RemoveLeadingZero(v.VolumeNumber) '
			--'ORDER BY c.ChartNumber, v.VolumenDateTo desc, v.VolumeNumber desc ' --RM: 2007/04/03

	--EN-00344
	--'ORDER BY c.ChartNumber, [Chart Hospital Link], [Volume Type], v.VolumenDateTo desc, v.VolumeNumber desc ' --RM: 2007/04/03
	if isnull(@VolSort, 0) = 200432 -- Date To Asc
		set @sql = @sql + 'ORDER BY c.ChartNumber, [Chart Hospital Link], [Volume Type], v.VolumenDateTo asc, v.VolumeNumber asc'
	else if isnull(@VolSort, 0) = 200433 -- Date From Desc
		set @sql = @sql + 'ORDER BY c.ChartNumber, [Chart Hospital Link], [Volume Type], v.VolumeDateFrom desc, v.VolumeNumber desc'
	else if isnull(@VolSort, 0) = 200434 -- Date From Asc
		set @sql = @sql + 'ORDER BY c.ChartNumber, [Chart Hospital Link], [Volume Type], v.VolumeDateFrom asc, v.VolumeNumber asc'
	else if isnull(@VolSort, 0) = 200435 -- Volume Number Desc
		set @sql = @sql + 'ORDER BY c.ChartNumber, [Chart Hospital Link], [Volume Type], v.VolumeNumber desc, v.VolumenDateTo desc'
	else if isnull(@VolSort, 0) = 200436 -- Volume Number Asc
		set @sql = @sql + 'ORDER BY c.ChartNumber, [Chart Hospital Link], [Volume Type], v.VolumeNumber asc, v.VolumenDateTo asc'
	else -- Date To Desc
		set @sql = @sql + 'ORDER BY c.ChartNumber, [Chart Hospital Link], [Volume Type], v.VolumenDateTo desc, v.VolumeNumber desc'
			
	--print @sql
	exec (@sql)
	RETURN 0
-- 		IF @Exact = 0
-- 		BEGIN
-- 			SELECT v.VolumeID AS [ ], 
-- 				REPLACE(SPACE(10 - LEN(c.ChartNumber)) + c.ChartNumber, ' ', '0') AS ChartNumber, 
-- 				v.VolumeNumber AS [Volume], 
-- 				ISNULL(c.LastName, '') + ', ' + ISNULL(c.FirstName, '') + ' ' + ISNULL(c.MiddleName, '') AS [Full Name], 
-- 				CONVERT(VarChar(10), c.BirthDate, 111) AS [Birth Date], 
-- 				dbo.LoanLU_Location.UserDescription AS [Current Location],
-- 				v.VolumeDateFrom AS [Date From],
-- 				v.VolumenDateTo AS [Date To]
-- 			FROM         dbo.CM_CPI_Volume LEFT OUTER JOIN
-- 		                      dbo.LoanLU_Location ON v.CLCurrentLocation = dbo.LoanLU_Location.Code LEFT OUTER JOIN
-- 		                      dbo.CM_CPI ON v.PatientID = c.PatientID
-- 			WHERE (c.ChartNumber LIKE @SearchString + '%') AND c.IsDeleted = 2
-- 			AND (ISNULL(v.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(v.HospitalID, 0) end)
-- 			ORDER BY c.ChartNumber, dbo.RemoveLeadingZero(v.VolumeNumber)
-- 			RETURN 0
-- 		END
-- 		ELSE
-- 		BEGIN
-- 			SELECT v.VolumeID AS [ ], 
-- 				REPLACE(SPACE(10 - LEN(c.ChartNumber)) + c.ChartNumber, ' ', '0') AS ChartNumber, 
-- 				v.VolumeNumber AS [Volume], 
-- 				ISNULL(c.LastName, '') + ', ' + ISNULL(c.FirstName, '') + ' ' + ISNULL(c.MiddleName, '') AS [Full Name], 
-- 				CONVERT(VarChar(10), c.BirthDate, 111) AS [Birth Date], 
-- 				dbo.LoanLU_Location.UserDescription AS [Current Location],
-- 				v.VolumeDateFrom AS [Date From],
-- 				v.VolumenDateTo AS [Date To]
-- 			FROM         dbo.CM_CPI_Volume LEFT OUTER JOIN
-- 		                      dbo.LoanLU_Location ON v.CLCurrentLocation = dbo.LoanLU_Location.Code LEFT OUTER JOIN
-- 		                      dbo.CM_CPI ON v.PatientID = c.PatientID
-- 			WHERE (c.ChartNumber = @SearchString) AND c.IsDeleted = 2
-- 			AND (ISNULL(v.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(v.HospitalID, 0) end)
-- 			ORDER BY c.ChartNumber, dbo.RemoveLeadingZero(v.VolumeNumber)
-- 			RETURN 0
-- 		END
END
ELSE IF @SearchType = 2 AND @NameSplit = 0
	BEGIN
	SET @SearchString = REPLACE(@SearchString, '''', '''''')
	SELECT top 999 v.VolumeID AS [ ], 
        isnull(ch.DisplayCode, '') as [Chart Hospital Link],
        --PR - 06101
        c.ChartNumber, 
		--REPLACE(SPACE(10 - LEN(c.ChartNumber)) + c.ChartNumber, ' ', '0') AS ChartNumber, 
		(select DisplayCode from LoanLU_VolumeType where Code = v.VolumeType) as [Volume Type], 
        vh.DisplayCode as [Volume Hospital Link],
		v.VolumeNumber AS [Volume], 
		ISNULL(c.LastName, '') + ', ' + ISNULL(c.FirstName, '') + ' ' + ISNULL(c.MiddleName, '') AS [Full Name], 
        isnull(D.DisplayCode, '') as [Expirted],
		CONVERT(VarChar(10), c.BirthDate, 111) AS [Birth Date], 
		cl.DisplayCode AS [Current Location],
        FL.DisplayCode AS [Previous Location], 
		PL.DisplayCode AS [Permanent Location],
        v.CLBoxNumber as [Box Number],
		CONVERT(VarChar(10), c.LastVisitDate, 111) AS [Last Visit Date], 
		v.VolumeDateFrom AS [Date From],
		v.VolumenDateTo AS [Date To],
		isnull(Digit.DisplayCode, '') as [Digital]  --TS-222
	FROM dbo.CM_CPI_Volume v inner join
         dbo.CM_CPI c ON v.PatientID = c.PatientID LEFT OUTER JOIN
         dbo.LoanLU_Location CL ON v.CLCurrentLocation = CL.Code LEFT OUTER JOIN
         dbo.LoanLU_Location PL ON v.PermLocation = PL.Code LEFT OUTER JOIN
         dbo.LoanLU_Location FL ON v.CLPreviousLocation = FL.Code LEFT OUTER JOIN
         H_HospitalProfile CH on c.HospitalID = CH.Code LEFT OUTER JOIN
         H_HospitalProfile VH on v.HospitalID = VH.Code left join
         LU_YesNoSystem D on c.DeathIndicator = D.Code left join
         dbo.LoanLU_DigitalIndicator Digit on v.DigitalIndicator = Digit.code

	WHERE (c.LastName LIKE @SearchString + '%') AND c.IsDeleted = 2
	AND (ISNULL(v.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(v.HospitalID, 0) end)
	AND (ISNULL(c.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(c.HospitalID, 0) end)
    --PR-01006
    and ((LastName not like '%merged%' and FirstName not like '%merged%') or @AccessLockChart = 1)
    -- 13111 sort order by volume descend
	--ORDER BY c.LastName, v.VolumeNumber
	--ORDER BY c.LastName, v.VolumenDateTo desc, v.VolumeNumber desc --RM: 2007/04/03
	ORDER BY c.LastName, [Chart Hospital Link], [Volume Type], v.VolumenDateTo desc, v.VolumeNumber desc --RM: 2007/04/03
	RETURN 0
	END
ELSE IF @SearchType = 2 AND @NameSplit > 0
	BEGIN
	SET @SearchString = REPLACE(@SearchString, '''', '''''')
	SET @NameSplit = CHARINDEX(',', @SearchString) 
	SELECT top 999 v.VolumeID AS [ ], 
        isnull(ch.DisplayCode, '') as [Chart Hospital Link],
        --PR - 06101
        c.ChartNumber, 
		--REPLACE(SPACE(10 - LEN(c.ChartNumber)) + c.ChartNumber, ' ', '0') AS ChartNumber, 
		(select DisplayCode from LoanLU_VolumeType where Code = v.VolumeType) as [Volume Type], 
        vh.DisplayCode as [Volume Hospital Link],
		v.VolumeNumber AS [Volume], 
		ISNULL(c.LastName, '') + ', ' + ISNULL(c.FirstName, '') + ' ' + ISNULL(c.MiddleName, '') AS [Full Name], 
        isnull(D.DisplayCode, '') as [Expirted],
		CONVERT(VarChar(10), c.BirthDate, 111) AS [Birth Date], 
		cl.DisplayCode AS [Current Location],
        FL.DisplayCode AS [Previous Location], 
		PL.DisplayCode AS [Permanent Location],
        v.CLBoxNumber as [Box Number],
		CONVERT(VarChar(10), c.LastVisitDate, 111) AS [Last Visit Date], 
		v.VolumeDateFrom AS [Date From],
		v.VolumenDateTo AS [Date To],
		isnull(Digit.DisplayCode, '') as [Digital]  --TS-222
	FROM dbo.CM_CPI_Volume v inner join
         dbo.CM_CPI c ON v.PatientID = c.PatientID LEFT OUTER JOIN
         dbo.LoanLU_Location CL ON v.CLCurrentLocation = CL.Code LEFT OUTER JOIN
         dbo.LoanLU_Location PL ON v.PermLocation = PL.Code LEFT OUTER JOIN
         dbo.LoanLU_Location FL ON v.CLPreviousLocation = FL.Code LEFT OUTER JOIN
         H_HospitalProfile CH on c.HospitalID = CH.Code LEFT OUTER JOIN
         H_HospitalProfile VH on v.HospitalID = VH.Code left join
         LU_YesNoSystem D on c.DeathIndicator = D.Code left join
         dbo.LoanLU_DigitalIndicator Digit on v.DigitalIndicator = Digit.code
	WHERE LastName LIKE + LEFT(@SearchString, @NameSplit-1) + '%' 
	AND FirstName LIKE + STUFF(@SearchString,1, @NameSplit, '') + '%' 
	AND IsDeleted = 2
    and (isnull(c.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(c.HospitalID, 0) end) 
    and (isnull(v.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(v.HospitalID, 0) end) 
    --PR-01006
    and ((LastName not like '%merged%' and FirstName not like '%merged%') or @AccessLockChart = 1) 
--	AND (ISNULL(v.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(v.HospitalID, 0) end)
    -- 13111 sort order by volume descend
	--ORDER BY LastName DESC, FirstName
	--ORDER BY LastName DESC, FirstName, v.VolumenDateTo desc, v.VolumeNumber desc  --RM: 2007/04/03
	ORDER BY LastName DESC, FirstName, [Chart Hospital Link], [Volume Type], v.VolumenDateTo desc, v.VolumeNumber desc  --RM: 2007/04/03
	END
ELSE IF @SearchType = 3
--PR-00212
BEGIN
	if right(@SearchString, 2) = '00' or substring(@SearchString, 6, 2) = '00'
	begin
        if substring(@SearchString, 6, 2) = '00'
        begin
            set @StartDate = left(@SearchString, 5) + '01/'
            set @EndDate = left(@SearchString, 5) + '12/'
        end
        else
        begin
            set @StartDate = left(@SearchString, 8) 
            set @EndDate = left(@SearchString, 8) 
        end
        if right(@SearchString, 2) = '00'
        begin
            set @StartDate = @StartDate + '01'
            set @EndDate = @EndDate + '01'
            if isdate(@EndDate) = 1
		set @EndDate = convert(varchar(20), dateadd(day, -1, dateadd(month, 1, cast(@EndDate as datetime))), 111)
		--EN-00081
                --set @EndDate = cast(dateadd(day, -1, dateadd(month, 1, cast(@EndDate as datetime))) as varchar(20))
        end
        else
        begin
            set @StartDate = @StartDate + right(@SearchString, 2) 
            set @EndDate = @EndDate + right(@SearchString, 2) 
        end	
	--print convert(varchar(10), @StartDate)
	--print convert(varchar(10), @EndDate)
        if isdate(@StartDate) = 1 and isdate(@EndDate) = 1
        	SELECT top 999 v.VolumeID AS [ ], 
                isnull(ch.DisplayCode, '') as [Chart Hospital Link],
                --PR - 06101
                c.ChartNumber, 
        		--REPLACE(SPACE(10 - LEN(c.ChartNumber)) + c.ChartNumber, ' ', '0') AS ChartNumber, 
        		(select DisplayCode from LoanLU_VolumeType where Code = v.VolumeType) as [Volume Type], 
                vh.DisplayCode as [Volume Hospital Link],
        		v.VolumeNumber AS [Volume], 
        		ISNULL(c.LastName, '') + ', ' + ISNULL(c.FirstName, '') + ' ' + ISNULL(c.MiddleName, '') AS [Full Name], 
                isnull(D.DisplayCode, '') as [Expirted],
        		CONVERT(VarChar(10), c.BirthDate, 111) AS [Birth Date], 
        		cl.DisplayCode AS [Current Location],
                FL.DisplayCode AS [Previous Location], 
        		PL.DisplayCode AS [Permanent Location],
                v.CLBoxNumber as [Box Number],
        		CONVERT(VarChar(10), c.LastVisitDate, 111) AS [Last Visit Date], 
        		v.VolumeDateFrom AS [Date From],
        		v.VolumenDateTo AS [Date To],
        		isnull(Digit.DisplayCode, '') as [Digital]  --TS-222
        	FROM dbo.CM_CPI_Volume v inner join
                 dbo.CM_CPI c ON v.PatientID = c.PatientID LEFT OUTER JOIN
                 dbo.LoanLU_Location CL ON v.CLCurrentLocation = CL.Code LEFT OUTER JOIN
                 dbo.LoanLU_Location PL ON v.PermLocation = PL.Code LEFT OUTER JOIN
                 dbo.LoanLU_Location FL ON v.CLPreviousLocation = FL.Code LEFT OUTER JOIN
                 H_HospitalProfile CH on c.HospitalID = CH.Code LEFT OUTER JOIN
                 H_HospitalProfile VH on v.HospitalID = VH.Code left join
                 LU_YesNoSystem D on c.DeathIndicator = D.Code left join
                 dbo.LoanLU_DigitalIndicator Digit on v.DigitalIndicator = Digit.code
    		WHERE (c.BirthDate between CONVERT(DATETIME, @StartDate) and CONVERT(DATETIME, @EndDate))
    		AND c.IsDeleted = 2
    	    and (isnull(c.HospitalID, 0) = 0 OR @HospID = (case @HospID when 0 then 0 else ISNULL(c.HospitalID, 0) end))         	
    	    and (isnull(v.HospitalID, 0) = 0 OR @HospID = (case @HospID when 0 then 0 else ISNULL(v.HospitalID, 0) end))         	
            --PR-01006
            and ((LastName not like '%merged%' and FirstName not like '%merged%') or @AccessLockChart = 1)
    	    --AND (ISNULL(v.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(v.HospitalID, 0) end)    
    	    -- 13111 sort order by volume descend
    		--ORDER BY c.BirthDate, v.VolumeNumber
    		--ORDER BY c.BirthDate, v.VolumenDateTo desc, v.VolumeNumber desc --RM: 2007/04/03
    		ORDER BY c.BirthDate, [Chart Hospital Link], [Volume Type], v.VolumenDateTo desc, v.VolumeNumber desc --RM: 2007/04/03
	end
	else
	begin
        if isdate(@SearchString) = 1
        	SELECT top 999 v.VolumeID AS [ ], 
                isnull(ch.DisplayCode, '') as [Chart Hospital Link],
                --PR - 06101
                c.ChartNumber, 
        		--REPLACE(SPACE(10 - LEN(c.ChartNumber)) + c.ChartNumber, ' ', '0') AS ChartNumber, 
        		(select DisplayCode from LoanLU_VolumeType where Code = v.VolumeType) as [Volume Type], 
                vh.DisplayCode as [Volume Hospital Link],
        		v.VolumeNumber AS [Volume], 
        		ISNULL(c.LastName, '') + ', ' + ISNULL(c.FirstName, '') + ' ' + ISNULL(c.MiddleName, '') AS [Full Name], 
                isnull(D.DisplayCode, '') as [Expirted],
        		CONVERT(VarChar(10), c.BirthDate, 111) AS [Birth Date], 
        		cl.DisplayCode AS [Current Location],
                FL.DisplayCode AS [Previous Location], 
        		PL.DisplayCode AS [Permanent Location],
                v.CLBoxNumber as [Box Number],
        		CONVERT(VarChar(10), c.LastVisitDate, 111) AS [Last Visit Date], 
        		v.VolumeDateFrom AS [Date From],
        		v.VolumenDateTo AS [Date To],
        		isnull(Digit.DisplayCode, '') as [Digital]  --TS-222
        	FROM dbo.CM_CPI_Volume v inner join
                 dbo.CM_CPI c ON v.PatientID = c.PatientID LEFT OUTER JOIN
                 dbo.LoanLU_Location CL ON v.CLCurrentLocation = CL.Code LEFT OUTER JOIN
                 dbo.LoanLU_Location PL ON v.PermLocation = PL.Code LEFT OUTER JOIN
                 dbo.LoanLU_Location FL ON v.CLPreviousLocation = FL.Code LEFT OUTER JOIN
                 H_HospitalProfile CH on c.HospitalID = CH.Code LEFT OUTER JOIN
                 H_HospitalProfile VH on v.HospitalID = VH.Code left join
                 LU_YesNoSystem D on c.DeathIndicator = D.Code left join
                 dbo.LoanLU_DigitalIndicator Digit on v.DigitalIndicator = Digit.code
    		WHERE (c.BirthDate >= CONVERT(DATETIME, @SearchString)) AND c.IsDeleted = 2
        	    and (isnull(c.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(c.HospitalID, 0) end)         	
        	    and (isnull(v.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(v.HospitalID, 0) end)         	
                --PR-01006
                and ((LastName not like '%merged%' and FirstName not like '%merged%') or @AccessLockChart = 1)
    	    --AND (ISNULL(v.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(v.HospitalID, 0) end)    
    	    -- 13111 sort order by volume descend
    		--ORDER BY c.BirthDate, v.VolumeNumber
    		--ORDER BY c.BirthDate, v.VolumenDateTo desc, v.VolumeNumber desc --RM: 2007/04/03
    		ORDER BY c.BirthDate, [Chart Hospital Link], [Volume Type], v.VolumenDateTo desc, v.VolumeNumber desc --RM: 2007/04/03
	end
	
	Return 0
END
ELSE IF @SearchType = 5
--EN-00183
BEGIN
	if right(@SearchString, 2) = '00' or substring(@SearchString, 6, 2) = '00'
	begin
        if substring(@SearchString, 6, 2) = '00'
        begin
            set @StartDate = left(@SearchString, 5) + '01/'
            set @EndDate = left(@SearchString, 5) + '12/'
        end
        else
        begin
            set @StartDate = left(@SearchString, 8) 
            set @EndDate = left(@SearchString, 8) 
        end
        if right(@SearchString, 2) = '00'
        begin
            set @StartDate = @StartDate + '01'
            set @EndDate = @EndDate + '01'
            if isdate(@EndDate) = 1
                set @EndDate = convert(varchar(20), dateadd(day, -1, dateadd(month, 1, cast(@EndDate as datetime))), 111)
        end
        else
        begin
            set @StartDate = @StartDate + right(@SearchString, 2) 
            set @EndDate = @EndDate + right(@SearchString, 2) 
        end
        if isdate(@StartDate) = 1 and isdate(@EndDate) = 1
        	SELECT top 999 v.VolumeID AS [ ], 
                isnull(ch.DisplayCode, '') as [Chart Hospital Link],
                --PR - 06101
                c.ChartNumber, 
        		--REPLACE(SPACE(10 - LEN(c.ChartNumber)) + c.ChartNumber, ' ', '0') AS ChartNumber, 
        		(select DisplayCode from LoanLU_VolumeType where Code = v.VolumeType) as [Volume Type], 
                vh.DisplayCode as [Volume Hospital Link],
        		v.VolumeNumber AS [Volume], 
        		ISNULL(c.LastName, '') + ', ' + ISNULL(c.FirstName, '') + ' ' + ISNULL(c.MiddleName, '') AS [Full Name], 
                isnull(D.DisplayCode, '') as [Expirted],
        		CONVERT(VarChar(10), c.BirthDate, 111) AS [Birth Date], 
        		cl.DisplayCode AS [Current Location],
                FL.DisplayCode AS [Previous Location], 
        		PL.DisplayCode AS [Permanent Location],
                v.CLBoxNumber as [Box Number],
        		CONVERT(VarChar(10), c.LastVisitDate, 111) AS [Last Visit Date], 
        		v.VolumeDateFrom AS [Date From],
        		v.VolumenDateTo AS [Date To],
        		isnull(Digit.DisplayCode, '') as [Digital]  --TS-222
        	FROM dbo.CM_CPI_Volume v inner join
                 dbo.CM_CPI c ON v.PatientID = c.PatientID LEFT OUTER JOIN
                 dbo.LoanLU_Location CL ON v.CLCurrentLocation = CL.Code LEFT OUTER JOIN
                 dbo.LoanLU_Location PL ON v.PermLocation = PL.Code LEFT OUTER JOIN
                 dbo.LoanLU_Location FL ON v.CLPreviousLocation = FL.Code LEFT OUTER JOIN
                 H_HospitalProfile CH on c.HospitalID = CH.Code LEFT OUTER JOIN
                 H_HospitalProfile VH on v.HospitalID = VH.Code left join
                 LU_YesNoSystem D on c.DeathIndicator = D.Code left join
                 dbo.LoanLU_DigitalIndicator Digit on v.DigitalIndicator = Digit.code
    		WHERE (c.LastVisitDate between CONVERT(DATETIME, @StartDate) and Convert(DateTime, @EndDate))
    		AND c.IsDeleted = 2
    	    and (isnull(c.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(c.HospitalID, 0) end)         	
    	    and (isnull(v.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(v.HospitalID, 0) end)         	
            --PR-01006
            and ((LastName not like '%merged%' and FirstName not like '%merged%') or @AccessLockChart = 1)
    	    --AND (ISNULL(v.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(v.HospitalID, 0) end)    
    	    -- 13111 sort order by volume descend
    		--ORDER BY c.BirthDate, v.VolumeNumber
    		--ORDER BY c.LastVisitDate, v.VolumenDateTo desc, v.VolumeNumber desc --RM: 2007/04/03
    		ORDER BY c.LastVisitDate, [Chart Hospital Link], [Volume Type], v.VolumenDateTo desc, v.VolumeNumber desc --RM: 2007/04/03
	end
	else
	begin
        if isdate(@SearchString) = 1
        	SELECT top 999 v.VolumeID AS [ ], 
                isnull(ch.DisplayCode, '') as [Chart Hospital Link],
                --PR - 06101
        		c.ChartNumber, 
        		--REPLACE(SPACE(10 - LEN(c.ChartNumber)) + c.ChartNumber, ' ', '0') AS ChartNumber, 
        		(select DisplayCode from LoanLU_VolumeType where Code = v.VolumeType) as [Volume Type], 
                vh.DisplayCode as [Volume Hospital Link],
        		v.VolumeNumber AS [Volume], 
        		ISNULL(c.LastName, '') + ', ' + ISNULL(c.FirstName, '') + ' ' + ISNULL(c.MiddleName, '') AS [Full Name], 
                isnull(D.DisplayCode, '') as [Expirted],
        		CONVERT(VarChar(10), c.BirthDate, 111) AS [Birth Date], 
        		cl.DisplayCode AS [Current Location],
                FL.DisplayCode AS [Previous Location], 
        		PL.DisplayCode AS [Permanent Location],
                v.CLBoxNumber as [Box Number],
        		CONVERT(VarChar(10), c.LastVisitDate, 111) AS [Last Visit Date], 
        		v.VolumeDateFrom AS [Date From],
        		v.VolumenDateTo AS [Date To],
        		isnull(Digit.DisplayCode, '') as [Digital]  --TS-222
        	FROM dbo.CM_CPI_Volume v inner join
                 dbo.CM_CPI c ON v.PatientID = c.PatientID LEFT OUTER JOIN
                 dbo.LoanLU_Location CL ON v.CLCurrentLocation = CL.Code LEFT OUTER JOIN
                 dbo.LoanLU_Location PL ON v.PermLocation = PL.Code LEFT OUTER JOIN
                 dbo.LoanLU_Location FL ON v.CLPreviousLocation = FL.Code LEFT OUTER JOIN
                 H_HospitalProfile CH on c.HospitalID = CH.Code LEFT OUTER JOIN
                 H_HospitalProfile VH on v.HospitalID = VH.Code left join
                 LU_YesNoSystem D on c.DeathIndicator = D.Code left join
                 dbo.LoanLU_DigitalIndicator Digit on v.DigitalIndicator = Digit.code
    		WHERE (c.LastVisitDate >= CONVERT(DATETIME, @SearchString)) AND c.IsDeleted = 2
    	    and (isnull(c.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(c.HospitalID, 0) end)         	
    	    and (isnull(v.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(v.HospitalID, 0) end)         	
            --PR-01006
            and ((LastName not like '%merged%' and FirstName not like '%merged%') or @AccessLockChart = 1)
    	    --AND (ISNULL(v.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(v.HospitalID, 0) end)    
    	    -- 13111 sort order by volume descend
    		--ORDER BY c.BirthDate, v.VolumeNumber
    		--ORDER BY c.LastVisitDate, v.VolumenDateTo desc, v.VolumeNumber desc --RM: 2007/04/03
    		ORDER BY c.LastVisitDate, [Chart Hospital Link], [Volume Type], v.VolumenDateTo desc, v.VolumeNumber desc --RM: 2007/04/03
	end
	
	Return 0
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Called by the New OMHRS Record Form (Locates Chart to user in new record).
CREATE PROCEDURE [F_SearchOMHRS_Chart]
	@SearchString as VarChar(50), 
	@SearchString2 as VarChar(50),
	@SearchType as Int,
	@UserID as int = 1,
	@Exact as int = 0,
	@HospID as varchar(100) = '0'
AS 
Set Nocount on
	Declare @Select as NVarchar(1500)
	Declare @SQL as NVarchar(2000)
    declare @cw as nvarchar(500)

--Chart Audits, Prefixs, VIP and Top X parameters
	Declare @SearchPrefix as NVarChar(50)
	Declare @ShowVip as NVarChar(1)
	Declare @TopX as NVarChar(3)
	Declare @SearchAudit as int
	Declare @SQLTopX as NVarChar(30)

--13507: Stops ' from screwing it up
Set @SearchString = replace(@SearchString, '''', '''''')
Set @SearchString2 = replace(@SearchString2, '''', '''''')

	Select @SearchPrefix = isnull(searchchartprefix, ''), @ShowVip = isnull(showvip, 0) from u_users where code = @UserID
	If @SearchPrefix <> ''
		Set @SearchPrefix = ' and ChartNumber like ''' + @SearchPrefix + '%'' '
	if 	@SearchPrefix is null set @SearchPrefix = ''    --PR - 06106
	
	If @HospID = '0'
		Select top 1 @TopX = isnull(TopSearch, '999'), @SearchAudit = EnableSearchAudit  FROM H_HospitalProfile 
	else	
		Select top 1 @TopX = isnull(TopSearch, '999'), @SearchAudit = EnableSearchAudit  FROM H_HospitalProfile where isnull(Code, 0) = @HospID
	Set @SQLTopX = 'Select distinct top ' + @TopX + ' ' 
	Declare @TempTable as NVarChar(100)
	set @TempTable = '##SearchTmp' + replace(convert(nvarchar(100), getdate(), 114), ':', '')

    --12738
    if @Exact = 0 
        set @cw = ' and (ChartNumber like ''' + @SearchString + '%'' or ChartNumber LIKE ''' + @SearchString2 +'%'') '
    else
        set @cw = ' and (ChartNumber = ''' + @SearchString + ''' or ChartNumber = ''' + @SearchString2 +''') '

 	Set @Select = @SQLTopX + ' LinkID as [ ], LinkID as [_],
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(OMHRS_SecAA.HospitalID, 0)) as [Hosp ID],
 		(select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = OMHRS_SecAA.ChartNumber) as [Deceased],
       	replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')  as [Chart Number],
		isnull(LastName, '''') + '', '' + isnull(FirstName, '''')  + '' '' + isnull(MiddleName, '''') as [Full Name],
		--convert(varchar(10), BirthDate, 111) as [Birth Date],
		convert(varchar(10), AdmitDate, 111) as [Date Stay Began], --PR-01980
 		(select top 1 isnull(DisplayCode, '''') + '' - '' + isnull(UserDescription, '''') from LU_CodeFile where Code = Z1) as [Assess Type]			
 	into ' + @TempTable + ' from OMHRS_SecAA inner join OMHRS_RecInfo on OMHRS_SecAA.AbstractID = OMHRS_RecInfo.AbstractID
    where IsCurrent = 1 and IsDeleted = 2 ' + @SearchPrefix + @cw + '
 	--and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) 
    '

	insert into AU_Search Values (650, @SearchString, @UserID, GetDate(), 'Chart Number') --PR - 06295


--select @Select, @SearchPrefix, @cw

if @SearchType = 1 or @SearchType = 2
begin
 	-- 3: FULL ADMIT- 7: SHORT STAY
	Set @SQL = @SQLTopX + ' PatientID as [ ], PatientID as [_],
			(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CM_CPI.HospitalID, 0)) as [Hosp ID],
			(case when DeathIndicator = 1 then ''Y'' else ''N'' end) as [Deceased],			
        	replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')  as [Chart Number],
			isnull(LastName, '''') + '', '' + isnull(FirstName, '''')  + '' '' + isnull(MiddleName, '''') as [Full Name],
			convert(varchar(10), BirthDate, 111) as [Birth Date]
 	into ' + @TempTable + ' from CM_CPI 
	where IsDeleted = 2 ' + @SearchPrefix + @cw + '
	and ChartNumber not in (select ChartNumber from OMHRS_SecAA where IsCurrent = 1 and (Z1 <> 200375 and Z1 <> 200377))
	and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end) 
	order by [Hosp ID], [Chart Number]'

	--		replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')  as [Chart Number],
	--set nocount off
	exec sp_executesql @sql
end

else if @SearchType = 3 or @SearchType = 4 or @SearchType = 5
begin
	-- 4: QUARTERLY- 6: CHANGE IN STATUS- 5: DISCHARGE
 	set @SQL = @Select + ' and isnull(CareType, 7) = 7 and (IsCurrent = 1 and (Z1 = 200373 or Z1 = 200374 or Z1 = 200376))
 	order by [Hosp ID], [Chart Number]'

 	exec sp_executesql @sql
end

else if @SearchType = 6
begin
	-- 8: MEDICATIONS
 	set @SQL = @Select + ' and (Z1 <> 200378)
 	order by [Hosp ID], [Chart Number]'

 	exec sp_executesql @sql
end

 	if @ShowVip = '2'
 	begin
 		set @SQL = 'delete ' + @TempTable + ' where [Chart Number] in (select replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') 
 			from CM_CPI where isnull(secret, 0) = 1 and replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')
 			in (select [Chart Number] from ' + @TempTable + '))'
 		exec(@SQL)
 	end

 	set nocount off
--print @sql

	set @SQL = 'select * From ' + @TempTable
	exec(@SQL)
	set @SQL = 'drop table ' + @TempTable
	exec(@SQL)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--Used to get the ID of a record (Amcare at this point) to Clone the Abstract
CREATE PROCEDURE [F_SearchProfileVisits]
	@CareType as int,
	@HospID as int = 0
AS 
	SELECT AbstractID AS [ ],
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Abstract.HospitalID, 0)) as [Hosp ID],
		ChartNumber AS [Chart #],
		EncounterNumber AS [Encounter #], 
		REPLACE(SPACE(3-LEN(ISNULL(CONVERT(VARCHAR(3),EncounterSequence), 0))) + ISNULL(CONVERT(VARCHAR(3),EncounterSequence), 0), ' ', '0') AS [Enc. Seq.], 	
		(SELECT CIHIValue FROM LU_MISCode WHERE Code = MISCode)  AS [M.I.S. Code], 
		CONVERT(VARCHAR(10), AdmitDate, 111) AS [Register Date], 
	   	CONVERT (VARCHAR(5), AdmitTime, 14) AS [Register Time],
		CONVERT(VARCHAR(10), DischargeDate, 111) AS [Disposition Date], 
	   	CONVERT (VARCHAR(5), DischargeTime, 14) AS [Disposition Time],
		(SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Complete Status],
		(SELECT CIHIValue FROM ICD_DiagFile10 WHERE Code = (SELECT DiagnosisCode FROM AB_Diagnosis WHERE AB_Diagnosis.AbstractID = AB_Abstract.AbstractID AND DiagnosisOccurrence = 1)) AS [Diag Code],
		(SELECT CIHIValue FROM ICD_ProcFile10 WHERE Code = (SELECT IntervCode FROM AB_Intervention WHERE AB_Intervention.AbstractID = AB_Abstract.AbstractID AND IntervOccurrence = 1)) AS [Interv Code]
	FROM dbo.AB_Abstract
	WHERE ICDType = 'T' AND CareType = @CareType
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
	order by [Hosp ID], AdmitDate desc


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--Used to get the ID of a record to Clone the Abstract
CREATE PROCEDURE [F_SearchProfileVisits_OMHRS]
	@AppID as int,
	@HospID as int = 0
AS 
	select AA.AbstractID as [ ],
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AA.HospitalID, 0)) as [Hosp ID],	
	        	Z1 as [Record #],
		ChartNumber as [Chart #],
		AA3 as [Case #], 
		convert (varchar(10), AdmitDate, 111) as [Date Stay Began], 
	   	convert (varchar(5), AdmitTime, 14) as [Time Stay Began],
		convert (varchar(10), A1, 111) as [Assessment Date], 
	   	convert (varchar(5), AssessTime, 14) as [Assessment Time],
        (select isnull(DisplayCode, '') + ' - ' + isnull(UserDescription, '') from LU_CodeFile where Code = Z1) AS [Type],
		(select CIHIValue from LU_AbstractStatus where Code = IsCompleted) as [Status]
    from OMHRS_SecAA AA inner join OMHRS_SecA A on AA.AbstractID = A.AbstractID inner join OMHRS_RecInfo R on AA.AbstractID = R.AbstractID	
    where CareType = 107 and AppID = @AppID
    and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
    order by [Hosp ID], AdmitDate desc


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

--exec F_SearchProvider 50004, '',  4,  '0', '',  0 
-- Called by the Provider Search Form
CREATE PROCEDURE [F_SearchProvider]
	@FKey as int,
	@SearchString as VarChar(50),
	@UserID as int = 1, 
	@HospID as varchar(100) = '0',
	@Extrasearch 	[varchar](1000) = '',
	@Exact as int = 0
as 

declare @sql nvarchar(4000)
declare @s as nvarchar(1500) --PR-01830
declare @w as nvarchar(1500) --PR-01830
declare @o as nvarchar(1000) --PR-01830

declare @DataType int
declare @FieldName as VarChar(50)
declare @FieldDescription as VarChar(50)
declare @UseDate as datetime
declare @sUseDate as VarChar(10)

declare @TopX as NVarChar(3) --PR-01830
--PR - 04578
declare @roleid int
set @roleid = (select top 1 roleid from u_users where code = @UserID)
if isnull(@roleid, 0) > 0
	set @UserID = @RoleID

select @DataType = (select DataType from U_UsersFields  where AppID = 1104 and FieldID = @FKey and UserID = @UserID)
select @FieldName = (select SystemName from U_Fields  where FieldID = @FKey)
select @FieldDescription = (select isnull(Header_User, @FieldName) from U_UsersFields  where AppID = 1104 and FieldID = @FKey and UserID = @UserID)

--PR-01830
If @HospID = '0'
	select top 1 @TopX = isnull(TopSearch, '999') from H_HospitalProfile 
else	
	select top 1 @TopX = isnull(TopSearch, '999') from H_HospitalProfile where isnull(Code, 0) = @HospID

set @UseDate = GetDate()

--PR-00549
declare @Srch2 as varchar(50)
--PR-00886
declare @Srch3 as varchar(50)
--13507: Moved to top	
set @SearchString = replace(@SearchString, '''', '''''')


set @sUseDate =  convert(nvarchar(10), @UseDate, 111) 
set @s = ' select top ' + 
 @TopX + ' 
 Code as [ ], 
 ' + @FieldName + ' as [' + @FieldDescription + '],  
 (select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(LU_Provider.HospitalID, 0)) as [Hosp ID],
 DisplayCode as [Provider Number], 
 UserDescription as [Name (Description)],
 CIHIValue as [CIHI Value],
 (select DisplayCode from LU_ProviderService where Code = (select top 1 Code from LLU_ProviderServices where Type = 1 and AssociationID = LU_Provider.Code and (([Validfrom] <= ''' +  @sUseDate + ''') and (''' + @sUseDate + ''' <= [ValidTo])))) as [Service],
 (select DisplayCode from LU_ProviderSpecialty where Code = (select top 1 Code from LLU_ProviderSpecialty where Type = 1 and associationID = LU_Provider.Code and (([Validfrom] <=  ''' + @sUseDate + ''') and (''' + @sUseDate + ''' <= [ValidTo])))) as [Specialty]
from LU_Provider '

if @FieldName = 'DisplayCode' 
begin	
	if @Exact = 0
	begin
		set @Srch2  = @SearchString
		set @Srch3  = @SearchString
		if len(@Srch2) < 5 set @Srch2  = replace(space(5-len(@Srch2)) + @Srch2, ' ', '0') -- PR-00549
		if len(@Srch3) = 5 and left(@Srch3, 1) = '0' set @Srch3 = right(@Srch3, 4)
		if len(@Srch3) = 4 and left(@Srch3, 1) = '0' set @Srch3 = right(@Srch3, 3)
		if len(@Srch3) = 3 and left(@Srch3, 1) = '0' set @Srch3 = right(@Srch3, 2)
		if len(@Srch3) = 2 and left(@Srch3, 1) = '0' set @Srch3 = right(@Srch3, 1)

		set @w = ' where (DisplayCode like ''' + @SearchString + '%'' or DisplayCode like ''' + @Srch2 + '%'' or DisplayCode like ''' + @Srch3 + '%'') 
			and (isnull(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
	end
	else
		set @w = ' where DisplayCode = ''' + @SearchString + '''
			and (isnull(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
	set @o = ' order by DisplayCode '
end

else if @FieldName = 'UserDescription'
begin

	set @w = ' where UserDescription like ''' + @SearchString + '%'' 
		and (isnull(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
	set @o = ' order by UserDescription '
end

else if  @FieldName = 'CIHIValue'
begin		
	if @Exact = 0
	begin
		set @Srch2  = @SearchString
		set @Srch3  = @SearchString
		if len(@Srch2) < 5 set @Srch2  = replace(space(5-len(@Srch2)) + @Srch2, ' ', '0') -- PR-00549
		if len(@Srch3) = 5 and left(@Srch3, 1) = '0' set @Srch3 = right(@Srch3, 4)
		if len(@Srch3) = 4 and left(@Srch3, 1) = '0' set @Srch3 = right(@Srch3, 3)
		if len(@Srch3) = 3 and left(@Srch3, 1) = '0' set @Srch3 = right(@Srch3, 2)
		if len(@Srch3) = 2 and left(@Srch3, 1) = '0' set @Srch3 = right(@Srch3, 1)
	
		set @w = ' where (CIHIValue like ''' + @SearchString + '%'' or CIHIValue like ''' + @Srch2 + '%'' or CIHIValue like ''' + @Srch3 + '%'')
			and (isnull(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
	end	
	else
		set @w = ' where CIHIValue = ''' + @SearchString + '''
			and (isnull(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '

	set @o = ' order by CIHIValue ' 
end

else if  @DataType = 11 or @DataType = 13
begin
	--if RIGHT(@SearchString, 2) = '00' set @SearchString =  LEFT(@SearchString, 8) + '01'	
	--declare @where varchar(500) --PR-00105

	--EN-00081
	if right(@SearchString, 5) = '00/00' 
		set @w = '(' + @FieldName + ' >= Convert(DateTime, ''' + left(@SearchString, 5) + '01/01'') and ' + @FieldName + ' <= convert(DateTime, ''' + left(@SearchString, 5) + '12/31'')) '

	else if right(@SearchString, 2) = '00' 
        	set @w = '(' + @FieldName + ' >= convert(datetime, ''' + left(@SearchString, 8) + '01'') and ' + @FieldName + ' < dateadd(M, 1, convert(datetime, ''' + left(@SearchString, 8) + '01''))) '
        else if (isdate(@SearchString) = 0) 
		set @SearchString = '1950/01/01'
	
	if isnull(@w, '') = ''
            set @w =  ' convert(nvarchar(10), ' + @FieldName + ', 111) = ''' + @SearchString + ''''
	
	--set @sUseDate =  convert(nvarchar(10), @UseDate, 111) 
   		
	set @s = ' select top ' + 
	 @TopX + ' 
	 Code as [ ], 
	 convert (VarChar(10), ' + @FieldName + ', 111) as [' + @FieldDescription + '],  
	 (select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(LU_Provider.HospitalID, 0)) as [Hosp ID],
	 DisplayCode as [Provider Number], 
	 UserDescription as [Name (Description)],
	 CIHIValue as [CIHI Value],
	 (select DisplayCode from LU_ProviderService where Code = (select top 1 Code from LLU_ProviderServices where Type = 1 and associationID = LU_Provider.Code and (([Validfrom] <=  convert(datetime, ''' + @sUseDate + ''') ) and (convert(datetime, ''' + @sUseDate + ''')  <= [ValidTo])))) as [Service],
	 (select DisplayCode from LU_ProviderSpecialty where Code = (select top 1 Code from LLU_ProviderSpecialty where Type = 1 and associationID = LU_Provider.Code and (([Validfrom] <=  convert(datetime, ''' + @sUseDate + ''') ) and (convert(datetime, ''' + @sUseDate + ''')  <= [ValidTo])))) as [Specialty]
	from LU_Provider '

	set @w = ' where ' + @w + 
		' and (isnull(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
	set @o = ' order by ' + @FieldName 
end
else
begin
	--set @sUseDate =  convert(nvarchar(10), @UseDate, 111) 
	--13507: Moved to top	
	--set @SearchString = replace(@SearchString, '''', '''''')

	set @s = ' select top ' + 
	 @TopX + ' 
	 Code as [ ], 
	 ' + @FieldName + ' as [' + @FieldDescription + '],  
	 (select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(LU_Provider.HospitalID, 0)) as [Hosp ID], 
	 DisplayCode as [Provider Number], 
	 UserDescription as [Name (Description)],
	 CIHIValue as [CIHI Value],
	 (select DisplayCode from LU_ProviderService where Code = (select top 1 Code from LLU_ProviderServices where Type = 1 and associationID = LU_Provider.Code and (([Validfrom] <=  convert(datetime, ''' + @sUseDate + ''') ) and (convert(datetime, ''' + @sUseDate + ''')  <= [ValidTo])))) as [Service],
	 (select DisplayCode from LU_ProviderSpecialty where Code = (select top 1 Code from LLU_ProviderSpecialty where Type = 1 and associationID = LU_Provider.Code and (([Validfrom] <=  convert(datetime, ''' + @sUseDate + ''') ) and (convert(datetime, ''' + @sUseDate + ''')  <= [ValidTo])))) as [Specialty]
	from LU_Provider '

	set @w = ' where ' + @FieldName + ' like ''%' + @SearchString + '%''  
	 	and (isnull(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
	set @o = ' order by ' + @FieldName 
end

if len(@Extrasearch) > 0
    set @w = @w + @Extrasearch --EN - 00477


set @sql = @s + @w + @o --PR-01830
--print @sql
exec sp_executesql @sql --PR-01830
return 0


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- Called by the Provider Search Form
create PROCEDURE [F_SearchProvider_ForDefTransfer]
	@HospID as varchar(100) = '0'
as 

	select 
		Code as [ ], 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(LU_Provider.HospitalID, 0)) as [Hosp ID],
		DisplayCode as [Provider Number], 
		UserDescription as [Name (Description)]
	from LU_Provider
	where (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
        and getdate() between validfrom and validto
	order by DisplayCode



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [F_SearchPull_List]
	@SearchString as VarChar(50),
	@FieldName as VarChar(50),
	@ExtraSearch 	[varchar](1000) = '',
    @HospID as int = 0,
    @LogID int
AS 
    --PR-01677
    declare @PullFormat int
	Declare @TopX int
	Declare @SearchAudit as int
    declare @sql varchar(4000)
    declare @TempDB varchar(100)
    set nocount on

	If @HospID = 0
		Select top 1 @TopX = isnull(TopSearch, 999), @SearchAudit = EnableSearchAudit, @PullFormat = (case when isnull(FormatPullID, 0) = 0 then 1 else FormatPullID end) FROM H_HospitalProfile 
	else	
		Select top 1 @TopX = isnull(TopSearch, 999), @SearchAudit = EnableSearchAudit, @PullFormat = (case when isnull(FormatPullID, 0) = 0 then 1 else FormatPullID end) FROM H_HospitalProfile where isnull(Code, 0) = @HospID
    if isnull(@TopX, 0) = 0 set @TopX = 999
    if isnull(@PullFormat, 0) = 0 set @PullFormat = 1

    set @TempDB = '##SearchPullList' + replace(replace(replace(replace(convert(varchar(50), getdate(), 121), '-', ''), ':', ''), ' ', ''), '.', '') + 
                cast(isnull(@HospID, 0) as varchar(10)) + cast(isnull(@LogID, 0) as varchar(10))


    -- set @PullFormat = isnull((select top 1 FormatPullID from H_HospitalProfile where (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)), 1)
    
	if @FieldName = 'PullListID'
    begin
        --PR-01677
        if @PullFormat in (2, 4, 5)
    		set @Sql = 'SELECT Top ' + cast(@TopX as varchar(10)) + ' 
                --EN-00183
                min(pullID) as [PID], -- PullListID AS [ ], 
                --EN-00183 to add hospital
                (select top 1 DisplayCode from H_HospitalProfile where code = dbo.CL_PullList.HospitalID) as [Hospital],
    
    			PullListID AS [Pull Number], 
    
    			Convert(varchar(10), PullDate, 111) AS [Transaction Date], 
    			CONVERT (varchar(5), max(PullTime), 14) AS [Transaction Time],  
               	(SELECT UserDescription FROM dbo.LoanLU_Location WHERE Code = dbo.CL_PullList.PullLocation) AS [Location], 
    			(SELECT UserDescription FROM dbo.LoanLU_Borrower WHERE Code = Puller) AS [Borrower],
    			Convert(varchar(10), max(PullOutDate), 111) AS [Actual Pull Date], 
    			CONVERT (varchar(5), max(PullOutTime), 14) AS [Actual Pull Time] into ' + @TempDB + '
    		FROM dbo.CL_PullList 
    		WHERE (PullListID LIKE ''%' + replace(@SearchString, '''', '''''') + '%'') AND ISNULL(PullListStatus, 0) <> 1 
              ' +  (case when @HospID > 0 then 'AND (ISNULL(HospitalID, 0) = 0 OR HospitalID = ' + cast(@HospID as varchar(10)) + ') ' else '' end) + '
            group by PullListID, PullDate, PullLocation, Puller, HospitalID
    		ORDER BY [Pull Number], [Transaction Date] Desc '

        else
            set @sql = 'select Top ' + cast(@TopX as varchar(10)) + ' 
                MinPullID as [PID], [Hospital], [Pull Number], [Transaction Date], [Transaction Time], [Location], 
    			(SELECT UserDescription FROM dbo.LoanLU_Borrower WHERE Code = (select top 1 Puller from CL_PullList where PullID = MinPullID)) AS [Borrower],
                [Actual Pull Date], [Actual Pull Time] into ' + @TempDB + '
            from
    		(SELECT 
                --EN-00183
                min(pullID) as MinPullID, -- PullListID AS [ ], 
                --EN-00183 to add hospital
                (select top 1 DisplayCode from H_HospitalProfile where code = dbo.CL_PullList.HospitalID) as [Hospital],
    			PullListID AS [Pull Number], 
    			Convert(varchar(10), PullDate, 111) AS [Transaction Date], 
    			CONVERT (varchar(5), max(PullTime), 14) AS [Transaction Time], 
               	(SELECT UserDescription FROM dbo.LoanLU_Location WHERE Code = dbo.CL_PullList.PullLocation) AS [Location], 
    			Convert(varchar(10), max(PullOutDate), 111) AS [Actual Pull Date], 
    			CONVERT (varchar(5), max(PullOutTime), 14) AS [Actual Pull Time]
    		FROM dbo.CL_PullList 
    		WHERE (PullListID LIKE ''%' + replace(@SearchString, '''', '''''') + '%'') AND ISNULL(PullListStatus, 0) <> 1
              ' +  (case when @HospID > 0 then 'AND (ISNULL(HospitalID, 0) = 0 OR HospitalID = ' + cast(@HospID as varchar(10)) + ') ' else '' end) + '
            group by PullListID, PullDate, PullLocation, HospitalID) p
    		ORDER BY [Pull Number], [Transaction Date] Desc'
    end
	Else if @FieldName = 'PullDate'
	BEGIN

		--EN-00081
		if right(@SearchString, 5) = '00/00' 
			--set @where = '(' + @FieldName + ' >= Convert(DateTime, ''' + left(@SearchString, 5) + '01/01'') and ' + @FieldName + ' <= convert(DateTime, ''' + left(@SearchString, 5) + '12/31'')) '
		begin
            --PR-01677
            if @PullFormat in (2, 4, 5)
    			set @sql = 'SELECT Top ' + cast(@TopX as varchar(10)) + ' 
                    --EN-00183
                    min(pullID) as [PID], -- PullListID AS [ ], 
                    --EN-00183 to add hospital
                    (select top 1 DisplayCode from H_HospitalProfile where code = dbo.CL_PullList.HospitalID) as [Hospital],
    
    				Convert(varchar(10), PullDate, 111) AS [Transaction Date], 
    				PullListID AS [Pull Number], 
    				CONVERT (varchar(5), max(PullTime), 14) AS [Transaction Time], 
    		        (SELECT UserDescription FROM dbo.LoanLU_Location WHERE Code = dbo.CL_PullList.PullLocation) AS [Location], 
    				(SELECT UserDescription FROM dbo.LoanLU_Borrower WHERE Code = Puller) AS [Borrower],
        			Convert(varchar(10), max(PullOutDate), 111) AS [Actual Pull Date], 
        			CONVERT (varchar(5), max(PullOutTime), 14) AS [Actual Pull Time] into ' + @TempDB + '
    			FROM dbo.CL_PullList 
    			WHERE (PullDate >= ''' + LEFT(@SearchString, 5) + '01/01''  AND PullDate <= ''' + LEFT(@SearchString, 5) + '12/31'')
--    			WHERE (PullDate >= CONVERT(DATETIME, LEFT(@SearchString, 5) + ''01/01'')  AND PullDate <= CONVERT(DATETIME, LEFT(@SearchString, 5) + ''12/31''))
    			AND ISNULL(PullListStatus, 0) <> 1
              ' +  (case when @HospID > 0 then 'AND (ISNULL(HospitalID, 0) = 0 OR HospitalID = ' + cast(@HospID as varchar(10)) + ') ' else '' end) + '
                group by PullListID, PullDate, PullLocation, Puller, dbo.CL_PullList.HospitalID
    			ORDER BY [Transaction Date] Desc, [Pull Number] '
            else
                set @sql = 'select Top ' + cast(@TopX as varchar(10)) + ' 
                    MinPullID as [PID], [Hospital], [Pull Number], [Transaction Date], [Transaction Time], [Location], 
        			(SELECT UserDescription FROM dbo.LoanLU_Borrower WHERE Code = (select top 1 Puller from CL_PullList where PullID = MinPullID)) AS [Borrower],
                    [Actual Pull Date], [Actual Pull Time] into ' + @TempDB + '
                from
    			(SELECT 
                    --EN-00183
                    min(pullID) as [MinPullID], -- PullListID AS [ ], 
                    --EN-00183 to add hospital
                    (select top 1 DisplayCode from H_HospitalProfile where code = dbo.CL_PullList.HospitalID) as [Hospital],
    
    				Convert(varchar(10), PullDate, 111) AS [Transaction Date], 
    				PullListID AS [Pull Number], 
    				CONVERT (varchar(5), max(PullTime), 14) AS [Transaction Time], 
                   	(SELECT UserDescription FROM dbo.LoanLU_Location WHERE Code = dbo.CL_PullList.PullLocation) AS [Location], 
        			Convert(varchar(10), max(PullOutDate), 111) AS [Actual Pull Date], 
        			CONVERT (varchar(5), max(PullOutTime), 14) AS [Actual Pull Time]
    			FROM dbo.CL_PullList 
    			WHERE (PullDate >= ''' + LEFT(@SearchString, 5) + '01/01'' AND PullDate <= ''' + LEFT(@SearchString, 5) + '12/31'')
--    			WHERE (PullDate >= CONVERT(DATETIME, LEFT(@SearchString, 5) + ''01/01'')  AND PullDate <= CONVERT(DATETIME, LEFT(@SearchString, 5) + ''12/31''))
    			AND ISNULL(PullListStatus, 0) <> 1
              ' +  (case when @HospID > 0 then 'AND (ISNULL(HospitalID, 0) = 0 OR HospitalID = ' + cast(@HospID as varchar(10)) + ') ' else '' end) + '
                group by PullListID, PullDate, PullLocation, dbo.CL_PullList.HospitalID) p
    			ORDER BY [Transaction Date] Desc, [Pull Number] '
		end 

		else IF RIGHT(@SearchString, 2) = '00'
		BEGIN
            --PR-01677
            if @PullFormat in (2, 4, 5)
    			set @sql = 'SELECT Top ' + cast(@TopX as varchar(10)) + ' 
                    --EN-00183
                    min(pullID) as [PID], -- PullListID AS [ ], 
                    --EN-00183 to add hospital
                    (select top 1 DisplayCode from H_HospitalProfile where code = dbo.CL_PullList.HospitalID) as [Hospital],
    
    				Convert(varchar(10), PullDate, 111) AS [Transaction Date], 
    				PullListID AS [Pull Number], 
    				CONVERT (varchar(5), max(PullTime), 14) AS [Transaction Time], 
    		                      	(SELECT UserDescription FROM dbo.LoanLU_Location WHERE Code = dbo.CL_PullList.PullLocation) AS [Location], 
    				(SELECT UserDescription FROM dbo.LoanLU_Borrower WHERE Code = Puller) AS [Borrower],
        			Convert(varchar(10), max(PullOutDate), 111) AS [Actual Pull Date], 
        			CONVERT (varchar(5), max(PullOutTime), 14) AS [Actual Pull Time] into ' + @TempDB + '
    			FROM dbo.CL_PullList 
    			WHERE (PullDate >= ''' + LEFT(@SearchString, 8) + '01'' AND PullDate < DATEADD(M, 1, CONVERT(DATETIME, ''' + LEFT(@SearchString, 8) + '01'')))
--    			WHERE (PullDate >= CONVERT(DATETIME, LEFT(@SearchString, 8) + ''01'')  AND PullDate < DATEADD(M, 1, CONVERT(DATETIME, LEFT(@SearchString, 8) + ''01'')))
    			AND ISNULL(PullListStatus, 0) <> 1
              ' +  (case when @HospID > 0 then 'AND (ISNULL(HospitalID, 0) = 0 OR HospitalID = ' + cast(@HospID as varchar(10)) + ') ' else '' end) + '
                group by PullListID, PullDate, PullLocation, Puller, dbo.CL_PullList.HospitalID
    			ORDER BY [Transaction Date] Desc, [Pull Number] '
            else
                set @Sql = 'select Top ' + cast(@TopX as varchar(10)) + ' 
                    MinPullID as [PID], [Hospital], [Pull Number], [Transaction Date], [Transaction Time], [Location], 
        			(SELECT UserDescription FROM dbo.LoanLU_Borrower WHERE Code = (select top 1 Puller from CL_PullList where PullID = MinPullID)) AS [Borrower],
                    [Actual Pull Date], [Actual Pull Time] into ' + @TempDB + '
                from
    			(SELECT 
                    --EN-00183
                    min(pullID) as [MinPullID], -- PullListID AS [ ], 
                    --EN-00183 to add hospital
                    (select top 1 DisplayCode from H_HospitalProfile where code = dbo.CL_PullList.HospitalID) as [Hospital],
    
    				Convert(varchar(10), PullDate, 111) AS [Transaction Date], 
    				PullListID AS [Pull Number], 
    				CONVERT (varchar(5), max(PullTime), 14) AS [Transaction Time], 
    		                      	(SELECT UserDescription FROM dbo.LoanLU_Location WHERE Code = dbo.CL_PullList.PullLocation) AS [Location], 
        			Convert(varchar(10), max(PullOutDate), 111) AS [Actual Pull Date], 
        			CONVERT (varchar(5), max(PullOutTime), 14) AS [Actual Pull Time]
    			FROM dbo.CL_PullList 
    			WHERE (PullDate >= ''' + LEFT(@SearchString, 8) + '01'' AND PullDate < DATEADD(M, 1, CONVERT(DATETIME, ''' + LEFT(@SearchString, 8) + '01'')))
--    			WHERE (PullDate >= CONVERT(DATETIME, LEFT(@SearchString, 8) + ''01'')  AND PullDate < DATEADD(M, 1, CONVERT(DATETIME, LEFT(@SearchString, 8) + ''01'')))
    			AND ISNULL(PullListStatus, 0) <> 1
              ' +  (case when @HospID > 0 then 'AND (ISNULL(HospitalID, 0) = 0 OR HospitalID = ' + cast(@HospID as varchar(10)) + ') ' else '' end) + '
                group by PullListID, PullDate, PullLocation, dbo.CL_PullList.HospitalID) P
    			ORDER BY [Transaction Date] Desc, [Pull Number] '
		END
	
		ELSE
		BEGIN
            --PR-01677
            if @PullFormat in (2, 4, 5)
    			set @sql = 'SELECT Top ' + cast(@TopX as varchar(10)) + ' 
                    --EN-00183
                    min(pullID) as [PID], -- PullListID AS [ ], 
                    --EN-00183 to add hospital
                    (select top 1 DisplayCode from H_HospitalProfile where code = dbo.CL_PullList.HospitalID) as [Hospital],
    
    				Convert(varchar(10), PullDate, 111) AS [Transaction Date], 
    				PullListID AS [Pull Number], 
    				CONVERT (varchar(5), max(PullTime), 14) AS [Transaction Time], 
                   	(SELECT UserDescription FROM dbo.LoanLU_Location WHERE Code = dbo.CL_PullList.PullLocation) AS [Location], 
    				(SELECT UserDescription FROM dbo.LoanLU_Borrower WHERE Code = Puller) AS [Borrower],
        			Convert(varchar(10), max(PullOutDate), 111) AS [Actual Pull Date], 
        			CONVERT (varchar(5), max(PullOutTime), 14) AS [Actual Pull Time] into ' + @TempDB + '
    			FROM dbo.CL_PullList 
    -- Ticket 11985
    --			WHERE (PullDate >= @SearchString) AND ISNULL(PullListStatus, 0) <> 1
    --			WHERE (PullDate = @SearchString or @SearchString = '''') AND ISNULL(PullListStatus, 0) <> 1
    			WHERE ' + (case when @SearchString = '' then '' else 'PullDate = ''' + @SearchString + ''' AND ' end) + ' ISNULL(PullListStatus, 0) <> 1
              ' +  (case when @HospID > 0 then 'AND (ISNULL(HospitalID, 0) = 0 OR HospitalID = ' + cast(@HospID as varchar(10)) + ') ' else '' end) + '
                group by PullListID, PullDate, PullLocation, Puller, dbo.CL_PullList.HospitalID
    			ORDER BY [Transaction Date] Desc, [Pull Number] '
            else
                set @sql = 'select Top ' + cast(@TopX as varchar(10)) + ' 
                    MinPullID as [PID], [Hospital], [Pull Number], [Transaction Date], [Transaction Time], [Location], 
        			(SELECT UserDescription FROM dbo.LoanLU_Borrower WHERE Code = (select top 1 Puller from CL_PullList where PullID = MinPullID)) AS [Borrower],
                    [Actual Pull Date], [Actual Pull Time] into ' + @TempDB + '
                from
    			(SELECT 
                    --EN-00183
                    min(pullID) as [MinPullID], -- PullListID AS [ ], 
                    --EN-00183 to add hospital
                    (select top 1 DisplayCode from H_HospitalProfile where code = dbo.CL_PullList.HospitalID) as [Hospital],
    
    				Convert(varchar(10), PullDate, 111) AS [Transaction Date], 
    				PullListID AS [Pull Number], 
    				CONVERT (varchar(5), max(PullTime), 14) AS [Transaction Time], 
                   	(SELECT UserDescription FROM dbo.LoanLU_Location WHERE Code = dbo.CL_PullList.PullLocation) AS [Location], 
        			Convert(varchar(10), max(PullOutDate), 111) AS [Actual Pull Date], 
        			CONVERT (varchar(5), max(PullOutTime), 14) AS [Actual Pull Time]
    			FROM dbo.CL_PullList 
    -- Ticket 11985
    --			WHERE (PullDate >= @SearchString) AND ISNULL(PullListStatus, 0) <> 1
    --			WHERE (PullDate = @SearchString or @SearchString = '''') AND ISNULL(PullListStatus, 0) <> 1
    			WHERE ' + (case when @SearchString = '' then '' else 'PullDate = ''' + @SearchString + ''' AND ' end) + ' ISNULL(PullListStatus, 0) <> 1
              ' +  (case when @HospID > 0 then 'AND (ISNULL(HospitalID, 0) = 0 OR HospitalID = ' + cast(@HospID as varchar(10)) + ') ' else '' end) + '
                group by PullListID, PullDate, PullLocation, dbo.CL_PullList.HospitalID) P
    			ORDER BY [Transaction Date] Desc, [Pull Number] '

		END
	END
	
	Else If @FieldName = 'PullTime'
	    begin 
	
	        set @SearchString = (case charindex(':', @SearchString)
	            when 1 then '00' + @SearchString
	            when 2 then '0' + @SearchString
	            else @SearchString
	        end)
	
	        set @SearchString = replace(@SearchString, ':', '')
	
	        set @SearchString = (case len(@SearchString) 
	            when 0 then '00:00'
	            when 1 then '00:0' + @SearchString 
	            when 2 then '00:' + @SearchString
	            when 3 then '0' + left(@SearchString, 1) + ':' + right(@SearchString, 2) 
	            when 4 then left(@SearchString, 2) + ':' + right(@SearchString, 2)
	            else left(@SearchString, 2) + ':' + substring(@SearchString, 2, 2)
	        end)
	
	        if (isdate(@SearchString) = 0) Set @SearchString = '23:59:59'
            --PR-01677
            if @PullFormat in (2, 4, 5)
        		set @sql = 'SELECT Top ' + cast(@TopX as varchar(10)) + ' 
                    --EN-00183
                    min(pullID) as [PID], -- PullListID AS [ ], 
                    --EN-00183 to add hospital
                    (select top 1 DisplayCode from H_HospitalProfile where code = dbo.CL_PullList.HospitalID) as [Hospital],
        
        			CONVERT (varchar(5), max(PullTime), 14) AS [Transaction Time], 
        			PullListID AS [Pull Number], 
        			Convert(varchar(10), PullDate, 111) AS [Transaction Date], 
        	        (SELECT UserDescription FROM dbo.LoanLU_Location WHERE Code = dbo.CL_PullList.PullLocation) AS [Location], 
        			(SELECT UserDescription FROM dbo.LoanLU_Borrower WHERE Code = Puller) AS [Borrower],
        			Convert(varchar(10), max(PullOutDate), 111) AS [Actual Pull Date], 
        			CONVERT (varchar(5), max(PullOutTime), 14) AS [Actual Pull Time] into ' + @TempDB + '
        		FROM dbo.CL_PullList 
--        		WHERE (PullTime >= ''1899-12-30 '' + @SearchString or @SearchString = '''') AND ISNULL(PullListStatus, 0) <> 1
        		WHERE ' + (case when @SearchString = '' then '' else 'PullTime >= ''1899-12-30 ' + @SearchString + ''' AND ' end) + 'ISNULL(PullListStatus, 0) <> 1
              ' +  (case when @HospID > 0 then 'AND (ISNULL(HospitalID, 0) = 0 OR HospitalID = ' + cast(@HospID as varchar(10)) + ') ' else '' end) + '
                group by PullListID, PullDate, PullLocation, Puller, dbo.CL_PullList.HospitalID
        		ORDER BY [Transaction Time], [Transaction Date] '
            else
                set @sql = 'select Top ' + cast(@TopX as varchar(10)) + ' 
                    MinPullID as [PID], [Hospital], [Pull Number], [Transaction Date], [Transaction Time], [Location], 
        			(SELECT UserDescription FROM dbo.LoanLU_Borrower WHERE Code = (select top 1 Puller from CL_PullList where PullID = MinPullID)) AS [Borrower],
                    [Actual Pull Date], [Actual Pull Time] into ' + @TempDB + '
                from
        		(SELECT 
                    --EN-00183
                    min(pullID) as [MinPullID], -- PullListID AS [ ], 
                    --EN-00183 to add hospital
                    (select top 1 DisplayCode from H_HospitalProfile where code = dbo.CL_PullList.HospitalID) as [Hospital],
        
        			CONVERT (varchar(5), max(PullTime), 14) AS [Transaction Time], 
        			PullListID AS [Pull Number], 
        			Convert(varchar(10), PullDate, 111) AS [Transaction Date], 
        	        (SELECT UserDescription FROM dbo.LoanLU_Location WHERE Code = dbo.CL_PullList.PullLocation) AS [Location], 
        			Convert(varchar(10), max(PullOutDate), 111) AS [Actual Pull Date], 
        			CONVERT (varchar(5), max(PullOutTime), 14) AS [Actual Pull Time]
        		FROM dbo.CL_PullList 
--        		WHERE (PullTime >= ''1899-12-30 '' + @SearchString or @SearchString = '''') AND ISNULL(PullListStatus, 0) <> 1
        		WHERE ' + (case when @SearchString = '' then '' else 'PullTime >= ''1899-12-30 ' + @SearchString + ''' AND ' end) + 'ISNULL(PullListStatus, 0) <> 1
              ' +  (case when @HospID > 0 then 'AND (ISNULL(HospitalID, 0) = 0 OR HospitalID = ' + cast(@HospID as varchar(10)) + ') ' else '' end) + '
                group by PullListID, PullDate, PullLocation, dbo.CL_PullList.HospitalID) P
        		ORDER BY [Transaction Time], [Transaction Date]'
	    end

	Else if @FieldName = 'PullOutDate'
	BEGIN
		--EN-00081
		if right(@SearchString, 5) = '00/00' 
		BEGIN
            --PR-01677
            if @PullFormat in (2, 4, 5)
    			set @sql = 'SELECT Top ' + cast(@TopX as varchar(10)) + ' 
                    --EN-00183
                    min(pullID) as [PID], -- PullListID AS [ ], 
                    --EN-00183 to add hospital
                    (select top 1 DisplayCode from H_HospitalProfile where code = dbo.CL_PullList.HospitalID) as [Hospital],
    
        			Convert(varchar(10), max(PullOutDate), 111) AS [Actual Pull Date], 
    				PullListID AS [Pull Number], 
    				Convert(varchar(10), PullDate, 111) AS [Transaction Date], 
    				CONVERT (varchar(5), max(PullTime), 14) AS [Transaction Time], 
    		        (SELECT UserDescription FROM dbo.LoanLU_Location WHERE Code = dbo.CL_PullList.PullLocation) AS [Location], 
    				(SELECT UserDescription FROM dbo.LoanLU_Borrower WHERE Code = Puller) AS [Borrower],
        			CONVERT (varchar(5), max(PullOutTime), 14) AS [Actual Pull Time] into ' + @TempDB + '
    			FROM dbo.CL_PullList 
--    			WHERE (PullOutDate >= CONVERT(DATETIME, LEFT(@SearchString, 5) + ''01/01'')  AND PullOutDate <= CONVERT(DATETIME, LEFT(@SearchString, 5) + ''12/31''))
    			WHERE (PullOutDate >= ''' + LEFT(@SearchString, 5) + '01/01'' AND PullOutDate <= ''' + LEFT(@SearchString, 5) + '12/31'') 
    			AND ISNULL(PullListStatus, 0) <> 1
              ' +  (case when @HospID > 0 then 'AND (ISNULL(HospitalID, 0) = 0 OR HospitalID = ' + cast(@HospID as varchar(10)) + ') ' else '' end) + '
                group by PullListID, PullDate, PullLocation, Puller, dbo.CL_PullList.HospitalID --, PullOutDate, PullOutTime
    			ORDER BY [Transaction Date] Desc, [Pull Number] '
            else
                set @sql = 'select Top ' + cast(@TopX as varchar(10)) + ' 
                    MinPullID as [PID], [Hospital], [Pull Number], [Transaction Date], [Transaction Time], [Location], 
        			(SELECT UserDescription FROM dbo.LoanLU_Borrower WHERE Code = (select top 1 Puller from CL_PullList where PullID = MinPullID)) AS [Borrower],
                    [Actual Pull Date], [Actual Pull Time] into ' + @TempDB + '
                from
    			(SELECT 
                    --EN-00183
                    min(pullID) as [MinPullID], -- PullListID AS [ ], 
                    --EN-00183 to add hospital
                    (select top 1 DisplayCode from H_HospitalProfile where code = dbo.CL_PullList.HospitalID) as [Hospital],
    
        			Convert(varchar(10), max(PullOutDate), 111) AS [Actual Pull Date], 
    				PullListID AS [Pull Number], 
    				Convert(varchar(10), PullDate, 111) AS [Transaction Date], 
    				CONVERT (varchar(5), max(PullTime), 14) AS [Transaction Time], 
    		        (SELECT UserDescription FROM dbo.LoanLU_Location WHERE Code = dbo.CL_PullList.PullLocation) AS [Location], 
        			CONVERT (varchar(5), max(PullOutTime), 14) AS [Actual Pull Time]
    			FROM dbo.CL_PullList 
--    			WHERE (PullOutDate >= CONVERT(DATETIME, LEFT(@SearchString, 5) + ''01/01'')  AND PullOutDate <= CONVERT(DATETIME, LEFT(@SearchString, 5) + ''12/31''))
    			WHERE (PullOutDate >= ''' + LEFT(@SearchString, 5) + '01/01'' AND PullOutDate <= ''' + LEFT(@SearchString, 5) + '12/31'')
    			AND ISNULL(PullListStatus, 0) <> 1
              ' +  (case when @HospID > 0 then 'AND (ISNULL(HospitalID, 0) = 0 OR HospitalID = ' + cast(@HospID as varchar(10)) + ') ' else '' end) + '
                group by PullListID, PullDate, PullLocation, dbo.CL_PullList.HospitalID) P --, PullOutDate, PullOutTime
    			ORDER BY [Transaction Date] Desc, [Pull Number] '
		END

		else IF RIGHT(@SearchString, 2) = '00'
		BEGIN
            --PR-01677
            if @PullFormat in (2, 4, 5)
    			set @sql = 'SELECT Top ' + cast(@TopX as varchar(10)) + ' 
                    --EN-00183
                    min(pullID) as [PID], -- PullListID AS [ ], 
                    --EN-00183 to add hospital
                    (select top 1 DisplayCode from H_HospitalProfile where code = dbo.CL_PullList.HospitalID) as [Hospital],
    
        			Convert(varchar(10), max(PullOutDate), 111) AS [Actual Pull Date], 
    				PullListID AS [Pull Number], 
    				Convert(varchar(10), PullDate, 111) AS [Transaction Date], 
    				CONVERT (varchar(5), max(PullTime), 14) AS [Transaction Time], 
    		        (SELECT UserDescription FROM dbo.LoanLU_Location WHERE Code = dbo.CL_PullList.PullLocation) AS [Location], 
    				(SELECT UserDescription FROM dbo.LoanLU_Borrower WHERE Code = Puller) AS [Borrower],
        			CONVERT (varchar(5), max(PullOutTime), 14) AS [Actual Pull Time] into ' + @TempDB + '
    			FROM dbo.CL_PullList 
--    			WHERE (PullOutDate >= CONVERT(DATETIME, LEFT(@SearchString, 8) + ''01'')  AND PullOutDate < DATEADD(M, 1, CONVERT(DATETIME, LEFT(@SearchString, 8) + ''01'')))
    			WHERE (PullOutDate >= ''' + LEFT(@SearchString, 8) + '01'' AND PullOutDate < DATEADD(M, 1, CONVERT(DATETIME, ''' + LEFT(@SearchString, 8) + '01'')))
    			AND ISNULL(PullListStatus, 0) <> 1
              ' +  (case when @HospID > 0 then 'AND (ISNULL(HospitalID, 0) = 0 OR HospitalID = ' + cast(@HospID as varchar(10)) + ') ' else '' end) + '
                group by PullListID, PullDate, PullLocation, Puller, dbo.CL_PullList.HospitalID --, PullOutDate, PullOutTime
    			ORDER BY [Transaction Date] Desc, [Pull Number] '
            else
                set @sql = 'select Top ' + cast(@TopX as varchar(10)) + ' 
                    MinPullID as [PID], [Hospital], [Pull Number], [Transaction Date], [Transaction Time], [Location], 
        			(SELECT UserDescription FROM dbo.LoanLU_Borrower WHERE Code = (select top 1 Puller from CL_PullList where PullID = MinPullID)) AS [Borrower],
                    [Actual Pull Date], [Actual Pull Time]  into ' + @TempDB + '
                from 
    			(SELECT 
                    --EN-00183
                    min(pullID) as [MinPullID], -- PullListID AS [ ], 
                    --EN-00183 to add hospital
                    (select top 1 DisplayCode from H_HospitalProfile where code = dbo.CL_PullList.HospitalID) as [Hospital],
    
        			Convert(varchar(10), max(PullOutDate), 111) AS [Actual Pull Date], 
    				PullListID AS [Pull Number], 
    				Convert(varchar(10), PullDate, 111) AS [Transaction Date], 
    				CONVERT (varchar(5), max(PullTime), 14) AS [Transaction Time], 
    		        (SELECT UserDescription FROM dbo.LoanLU_Location WHERE Code = dbo.CL_PullList.PullLocation) AS [Location], 
        			CONVERT (varchar(5), max(PullOutTime), 14) AS [Actual Pull Time]
    			FROM dbo.CL_PullList 
--    			WHERE (PullOutDate >= CONVERT(DATETIME, LEFT(@SearchString, 8) + ''01'')  AND PullOutDate < DATEADD(M, 1, CONVERT(DATETIME, LEFT(@SearchString, 8) + ''01'')))
    			WHERE (PullOutDate >= ''' + LEFT(@SearchString, 8) + '01'' AND PullOutDate < DATEADD(M, 1, CONVERT(DATETIME, ''' + LEFT(@SearchString, 8) + '01'')))
    			AND ISNULL(PullListStatus, 0) <> 1
              ' +  (case when @HospID > 0 then 'AND (ISNULL(HospitalID, 0) = 0 OR HospitalID = ' + cast(@HospID as varchar(10)) + ') ' else '' end) + '
                group by PullListID, PullDate, PullLocation, dbo.CL_PullList.HospitalID) P --, PullOutDate, PullOutTime
    			ORDER BY [Transaction Date] Desc, [Pull Number]'

		END
	
		ELSE
		BEGIN
            --PR-01677
            if @PullFormat in (2, 4, 5)
    			set @sql = 'SELECT  Top ' + cast(@TopX as varchar(10)) + ' 
                    --EN-00183
                    min(pullID) as [PID], -- PullListID AS [ ], 
                    --EN-00183 to add hospital
                    (select top 1 DisplayCode from H_HospitalProfile where code = dbo.CL_PullList.HospitalID) as [Hospital],
        
        			Convert(varchar(10), max(PullOutDate), 111) AS [Actual Pull Date], 
    				PullListID AS [Pull Number], 
    				Convert(varchar(10), PullDate, 111) AS [Transaction Date], 
    				CONVERT (varchar(5), max(PullTime), 14) AS [Transaction Time], 
    		        (SELECT UserDescription FROM dbo.LoanLU_Location WHERE Code = dbo.CL_PullList.PullLocation) AS [Location], 
    				(SELECT UserDescription FROM dbo.LoanLU_Borrower WHERE Code = Puller) AS [Borrower],
        			CONVERT (varchar(5), max(PullOutTime), 14) AS [Actual Pull Time] into ' + @TempDB + '
    			FROM dbo.CL_PullList 
    -- Ticket 11985
    --			WHERE (PullOutDate >= @SearchString) AND ISNULL(PullListStatus, 0) <> 1
    --			WHERE (PullOutDate = @SearchString or @SearchString = '''') AND ISNULL(PullListStatus, 0) <> 1
    			WHERE ' + (case when @SearchString = '' then '' else 'PullOutDate = ''' + @SearchString + ''' AND ' end) + 'ISNULL(PullListStatus, 0) <> 1
              ' +  (case when @HospID > 0 then 'AND (ISNULL(HospitalID, 0) = 0 OR HospitalID = ' + cast(@HospID as varchar(10)) + ') ' else '' end) + '
                group by PullListID, PullDate, PullLocation, Puller, dbo.CL_PullList.HospitalID
    			ORDER BY [Transaction Date] Desc, [Pull Number]'
            else
                set @sql = 'select Top ' + cast(@TopX as varchar(10)) + ' 
                    MinPullID as [PID], [Hospital], [Pull Number], [Transaction Date], [Transaction Time], [Location], 
        			(SELECT UserDescription FROM dbo.LoanLU_Borrower WHERE Code = (select top 1 Puller from CL_PullList where PullID = MinPullID)) AS [Borrower],
                    [Actual Pull Date], [Actual Pull Time] into ' + @TempDB + '
                from 
    			(SELECT  
                    --EN-00183
                    min(pullID) as [MinPullID], -- PullListID AS [ ], 
                    --EN-00183 to add hospital
                    (select top 1 DisplayCode from H_HospitalProfile where code = dbo.CL_PullList.HospitalID) as [Hospital],
        
        			Convert(varchar(10), max(PullOutDate), 111) AS [Actual Pull Date], 
    				PullListID AS [Pull Number], 
    				Convert(varchar(10), PullDate, 111) AS [Transaction Date], 
    				CONVERT (varchar(5), max(PullTime), 14) AS [Transaction Time], 
    		        (SELECT UserDescription FROM dbo.LoanLU_Location WHERE Code = dbo.CL_PullList.PullLocation) AS [Location], 
        			CONVERT (varchar(5), max(PullOutTime), 14) AS [Actual Pull Time]
    			FROM dbo.CL_PullList 
    -- Ticket 11985
    --			WHERE (PullOutDate >= @SearchString) AND ISNULL(PullListStatus, 0) <> 1
    --			WHERE (PullOutDate = @SearchString or @SearchString = '''') AND ISNULL(PullListStatus, 0) <> 1
    			WHERE ' + (case when @SearchString = '' then '' else 'PullOutDate = ''' + @SearchString + ''' AND ' end) + 'ISNULL(PullListStatus, 0) <> 1
              ' +  (case when @HospID > 0 then 'AND (ISNULL(HospitalID, 0) = 0 OR HospitalID = ' + cast(@HospID as varchar(10)) + ') ' else '' end) + '
                group by PullListID, PullDate, PullLocation, dbo.CL_PullList.HospitalID) P
    			ORDER BY [Transaction Date] Desc, [Pull Number] '
		END
	END
	
	Else If @FieldName = 'PullOutTime'
	    begin 
	
	        set @SearchString = (case charindex(':', @SearchString)
	            when 1 then '00' + @SearchString
	            when 2 then '0' + @SearchString
	            else @SearchString
	        end)
	
	        set @SearchString = replace(@SearchString, ':', '')
	
	        set @SearchString = (case len(@SearchString) 
	            when 0 then '00:00'
	            when 1 then '00:0' + @SearchString 
	            when 2 then '00:' + @SearchString
	            when 3 then '0' + left(@SearchString, 1) + ':' + right(@SearchString, 2) 
	            when 4 then left(@SearchString, 2) + ':' + right(@SearchString, 2)
	            else left(@SearchString, 2) + ':' + substring(@SearchString, 2, 2)
	        end)
	
	        if (isdate(@SearchString) = 0) Set @SearchString = '23:59:59'
            --PR-01677
            if @PullFormat in (2, 4, 5)
        		set @sql = 'SELECT Top ' + cast(@TopX as varchar(10)) + ' 
                    --EN-00183
                    min(pullID) as [PID], -- PullListID AS [ ], 
                    --EN-00183 to add hospital
                    (select top 1 DisplayCode from H_HospitalProfile where code = dbo.CL_PullList.HospitalID) as [Hospital],
        
        			CONVERT (varchar(5), max(PullOutTime), 14) AS [Actual Pull Time],
        			CONVERT (varchar(5), max(PullTime), 14) AS [Transaction Time], 
        			PullListID AS [Pull Number], 
        			Convert(varchar(10), PullDate, 111) AS [Transaction Date], 
        	        (SELECT UserDescription FROM dbo.LoanLU_Location WHERE Code = dbo.CL_PullList.PullLocation) AS [Location], 
        			(SELECT UserDescription FROM dbo.LoanLU_Borrower WHERE Code = Puller) AS [Borrower],
        			Convert(varchar(10), max(PullOutDate), 111) AS [Actual Pull Date] into ' + @TempDB + '
        		FROM dbo.CL_PullList 
--        		WHERE (PullOutTime >= ''1899-12-30 '' + @SearchString or @SearchString = '''') AND ISNULL(PullListStatus, 0) <> 1
        		WHERE ' + (case when @SearchString = '' then '' else 'PullOutTime >= ''1899-12-30 ' + @SearchString + ''' AND ' end) + 'ISNULL(PullListStatus, 0) <> 1
              ' +  (case when @HospID > 0 then 'AND (ISNULL(HospitalID, 0) = 0 OR HospitalID = ' + cast(@HospID as varchar(10)) + ') ' else '' end) + '
                group by PullListID, PullDate, PullLocation, Puller, dbo.CL_PullList.HospitalID --, PullOutDate, PullOutTime
        		ORDER BY [Transaction Time], [Transaction Date] '
            else
                set @sql = 'select Top ' + cast(@TopX as varchar(10)) + ' 
                    MinPullID as [PID], [Hospital], [Pull Number], [Transaction Date], [Transaction Time], [Location], 
        			(SELECT UserDescription FROM dbo.LoanLU_Borrower WHERE Code = (select top 1 Puller from CL_PullList where PullID = MinPullID)) AS [Borrower],
                    [Actual Pull Date], [Actual Pull Time]  into ' + @TempDB + '
                from 
        		(SELECT 
                    --EN-00183
                    min(pullID) as [MinPullID], -- PullListID AS [ ], 
                    --EN-00183 to add hospital
                    (select top 1 DisplayCode from H_HospitalProfile where code = dbo.CL_PullList.HospitalID) as [Hospital],
        
        			CONVERT (varchar(5), max(PullOutTime), 14) AS [Actual Pull Time],
        			CONVERT (varchar(5), max(PullTime), 14) AS [Transaction Time], 
        			PullListID AS [Pull Number], 
        			Convert(varchar(10), PullDate, 111) AS [Transaction Date], 
        	        (SELECT UserDescription FROM dbo.LoanLU_Location WHERE Code = dbo.CL_PullList.PullLocation) AS [Location], 
        			Convert(varchar(10), max(PullOutDate), 111) AS [Actual Pull Date]
        		FROM dbo.CL_PullList 
--        		WHERE (PullOutTime >= ''1899-12-30 '' + @SearchString or @SearchString = '''') AND ISNULL(PullListStatus, 0) <> 1
        		WHERE ' + (case when @SearchString = '' then '' else 'PullOutTime >= ''1899-12-30 ' + @SearchString + ''' AND ' end) + 'ISNULL(PullListStatus, 0) <> 1
              ' +  (case when @HospID > 0 then 'AND (ISNULL(HospitalID, 0) = 0 OR HospitalID = ' + cast(@HospID as varchar(10)) + ') ' else '' end) + '
                group by PullListID, PullDate, PullLocation, dbo.CL_PullList.HospitalID) P --, PullOutDate, PullOutTime
        		ORDER BY [Transaction Time], [Transaction Date]'
	    end
--print @sql
exec (@sql)

If @SearchAudit = 1
Begin
--	Declare @CurDTime as Datetime
--	Set @CurDTime = getdate()
    set @sql = 'insert into AU_SearchDetail select 11, [PID], ' + cast(isnull(@LogID, 0) as varchar(10)) + ', getdate() as Field2 from ' + @TempDB  

--	set @SQL = 'insert into AU_SearchDetail select 11, [ ], ''' + Cast(@LogID as varchar(10)) + ''', ''' + convert(varchar(30), @CurDTime, 120) + ''' as Field2 from ' + @TempDB + ''
--	exec(@SQL)
end
 
set @sql = 'select * from ' + @TempDB 
exec (@sql)


set nocount on

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [F_SearchPullList]
	@PullListID as VarChar(50),
--    @PullDate as datetime,
    @HospID as int,
	@PullListAll as VarChar(1),
    @AccessLockChart as int = 1
AS 
--EN-00183
-- 	SELECT Top 1 VolumeID, 
-- 		PullListID, 
-- 		Convert(varchar(10), PullDate, 111) AS [PullDate], 
-- 		CONVERT (varchar(5), PullTime, 14) AS [PullTime], 
-- 		PullLocation, 
-- 		Puller, 
-- 		PullNotes, 
--     		Convert(varchar(10), PullOutDate, 111) AS PullOutDate, 
--     		CONVERT (varchar(5), PullOutTime, 14) AS PullOutTime, CLRequestPriority
-- 	FROM dbo.CL_PullList
-- 	Where PullListID = @PullListID 
-- 	AND ISNULL(PullListStatus, 0) <> 1
--     	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	If @PullListAll = 'Y'
		SELECT top 999    
            v.VolumeID as [ ], 
            isnull(ch.DisplayCode, '') as [Chart Hospital Link],
            --PR - 06101
            c.ChartNumber,
    		--REPLACE(SPACE(10 - LEN(c.ChartNumber)) + c.ChartNumber, ' ', '0') AS ChartNumber, 
    		(select DisplayCode from LoanLU_VolumeType where Code = v.VolumeType) as [Volume Type], 
            vh.DisplayCode as [Volume Hospital Link],
    		v.VolumeNumber AS [Volume], 
    		ISNULL(c.LastName, '') + ', ' + ISNULL(c.FirstName, '') + ' ' + ISNULL(c.MiddleName, '') AS [Full Name], 
            isnull(D.DisplayCode, '') as [Expirted],
    		CONVERT(VarChar(10), c.BirthDate, 111) AS [Birth Date], 
    		cl.DisplayCode AS [Current Location],
            FL.DisplayCode AS [Previous Location], 
    		PL.DisplayCode AS [Permanent Location],
            v.CLBoxNumber as [Box Number],
    		CONVERT(VarChar(10), c.LastVisitDate, 111) AS [Last Visit Date], 
    		v.VolumeDateFrom AS [Date From],
    		v.VolumenDateTo AS [Date To],
            
            PullTime as [Require Time],
            --PullNotes as Notes,
            LoanNote  as Notes,
            PullID,
            PullListStatus,
            isnull(B.DisplayCode, '') as [Borrower],
            Puller,
            isnull(LoanReason, '') as [Reason for Loan],
            LoanReason,
            isnull(Digit.DisplayCode, '') as [Digital]  --TS-222
  		FROM  dbo.CL_PullList p inner join 
            CM_CPI_Volume v ON v.VolumeID = p.VolumeID inner join
            dbo.CM_CPI c ON v.PatientID = c.PatientID LEFT OUTER JOIN
            dbo.LoanLU_Location CL ON v.CLCurrentLocation = CL.Code LEFT OUTER JOIN
            dbo.LoanLU_Location PL ON v.PermLocation = PL.Code LEFT OUTER JOIN
            dbo.LoanLU_Location FL ON v.CLPreviousLocation = FL.Code LEFT OUTER JOIN
            H_HospitalProfile CH on c.HospitalID = CH.Code LEFT OUTER JOIN
            H_HospitalProfile VH on v.HospitalID = VH.Code left join
            LU_YesNoSystem D on c.DeathIndicator = D.Code left join
            LoanLU_Borrower B on p.Puller = B.Code left join
            dbo.LoanLU_DigitalIndicator Digit on v.DigitalIndicator = Digit.code
		Where PullListID = @PullListID --and PullDate = @PullDate
            	AND (ISNULL(p.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(p.HospitalID, 0) end)
            	AND (ISNULL(v.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(v.HospitalID, 0) end)
            	AND (ISNULL(c.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(c.HospitalID, 0) end)
                --PR-01006
	            and ((LastName not like '%merged%' and FirstName not like '%merged%') or @AccessLockChart = 1)

		ORDER BY ChartNumber, v.VolumenDateTo desc, VolumeNumber desc, PullTime
	Else
		SELECT top 999    
            v.VolumeID as [ ], 
            isnull(ch.DisplayCode, '') as [Chart Hospital Link],
            --PR - 06101
            c.ChartNumber,
    		--REPLACE(SPACE(10 - LEN(c.ChartNumber)) + c.ChartNumber, ' ', '0') AS ChartNumber, 
    		(select DisplayCode from LoanLU_VolumeType where Code = v.VolumeType) as [Volume Type], 
            vh.DisplayCode as [Volume Hospital Link],
    		v.VolumeNumber AS [Volume], 
    		ISNULL(c.LastName, '') + ', ' + ISNULL(c.FirstName, '') + ' ' + ISNULL(c.MiddleName, '') AS [Full Name], 
            isnull(D.DisplayCode, '') as [Expirted],
    		CONVERT(VarChar(10), c.BirthDate, 111) AS [Birth Date], 
    		cl.DisplayCode AS [Current Location],
            FL.DisplayCode AS [Previous Location], 
    		PL.DisplayCode AS [Permanent Location],
            v.CLBoxNumber as [Box Number],
    		CONVERT(VarChar(10), c.LastVisitDate, 111) AS [Last Visit Date], 
    		v.VolumeDateFrom AS [Date From],
    		v.VolumenDateTo AS [Date To],

            PullTime as [Require Time],
            --PullNotes as Notes,
            LoanNote  as Notes,
            PullID,
            PullListStatus,
            isnull(B.DisplayCode, '') as [Borrower],
            Puller,
            isnull(LoanReason, '') as [Reason for Loan],
            LoanReason
  		FROM  dbo.CL_PullList p inner join 
            CM_CPI_Volume v ON v.VolumeID = p.VolumeID inner join
            dbo.CM_CPI c ON v.PatientID = c.PatientID LEFT OUTER JOIN
            dbo.LoanLU_Location CL ON v.CLCurrentLocation = CL.Code LEFT OUTER JOIN
            dbo.LoanLU_Location PL ON v.PermLocation = PL.Code LEFT OUTER JOIN
            dbo.LoanLU_Location FL ON v.CLPreviousLocation = FL.Code LEFT OUTER JOIN
            H_HospitalProfile CH on c.HospitalID = CH.Code LEFT OUTER JOIN
            H_HospitalProfile VH on v.HospitalID = VH.Code left join
            LU_YesNoSystem D on c.DeathIndicator = D.Code left join
            LoanLU_Borrower B on p.Puller = B.Code 
		Where PullListID = @PullListID and isnull(PullListStatus, '0') <> 1 --and PullDate = @PullDate
            	AND (ISNULL(p.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(p.HospitalID, 0) end)
            	AND (ISNULL(v.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(v.HospitalID, 0) end)
            	AND (ISNULL(c.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(c.HospitalID, 0) end)
                --PR-01006
	            and ((LastName not like '%merged%' and FirstName not like '%merged%') or @AccessLockChart = 1)
		ORDER BY ChartNumber, v.VolumenDateTo desc, VolumeNumber desc, PullTime
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--F_SearchRehab_Chart '6688779', ' 006688779', 4, 4, 0, '0'

-- Called by the New Rehab Record Form (Locates Chart to user in new record).
CREATE PROCEDURE [F_SearchRehab_Chart]
	@SearchString as VarChar(50), 
	@SearchString2 as VarChar(50),
	@SearchType as Int,
	@UserID as int = 1,
	@Exact as int = 0,
	@HospID as varchar(100) = '0'
AS 
Set Nocount on
	Declare @Select as NVarchar(3000)   --PR-03542
	Declare @SQL as NVarchar(4000)   --PR-03542

--Chart Audits, Prefixs, VIP and Top X parameters
	Declare @SearchPrefix as NVarChar(500)
	Declare @ShowVip as NVarChar(1)
	Declare @TopX as NVarChar(3)
	Declare @SearchAudit as int
	Declare @SQLTopX as NVarChar(30)

--13507: Stops ' from screwing it up
Set @SearchString = replace(@SearchString, '''', '''''')
Set @SearchString2 = replace(@SearchString2, '''', '''''')

	Select @SearchPrefix = isnull(searchchartprefix, ''), @ShowVip = isnull(showvip, 0) from u_users where code = @UserID
	If @SearchPrefix <> ''
		Set @SearchPrefix = ' and dbo.CM_CPI.Chartnumber like ''' + @SearchPrefix + '%'' '   --PR-03542
	If @HospID = '0'
		Select top 1 @TopX = isnull(TopSearch, '999'), @SearchAudit = EnableSearchAudit  FROM H_HospitalProfile 
	else	
		Select top 1 @TopX = isnull(TopSearch, '999'), @SearchAudit = EnableSearchAudit  FROM H_HospitalProfile where isnull(Code, 0) = @HospID
	Set @SQLTopX = 'Select distinct top ' + @TopX + ' ' 
	Declare @TempTable as NVarChar(100)
	set @TempTable = '##SearchTmp' + replace(convert(nvarchar(100), getdate(), 114), ':', '')

	insert into AU_Search Values (2500, @SearchString, @UserID, GetDate(), 'Chart Number') --PR - 06295

IF @SearchType = 1
BEGIN
	--ADMIT - Can Show All Charts.
	Set @SQL = @SQLTopX + ' PatientID as [ ], PatientID AS [_],
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CM_CPI.HospitalID, 0)) as [Hosp ID],
		case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
		replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')  as [ChartNumber],
		IsNull(LastName, '''') + '', '' + IsNull(FirstName, '''')  + '' '' + IsNull(MiddleName, '''') As [Full Name],
		Convert(VarChar(10), BirthDate, 111) as [Birth Date]
		--, '' '' as [Date Stay Began]
	into ' + @TempTable + ' FROM dbo.CM_CPI 
	WHERE (ChartNumber LIKE ''' + @SearchString + '%''  OR ChartNumber LIKE ''' + @SearchString2 +'%'')
	AND IsDeleted = 2 ' + @SearchPrefix + '
	AND (ISNULL(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(HospitalID, 0) end) 
	ORDER BY [Hosp ID], ChartNumber'
END

ELSE IF @SearchType = 2 or @SearchType = 4
BEGIN
	--INTERIM & DISCH - Can Only Show Charts Already Admited
	Set @SQL = @SQLTopX + ' PatientID as [ ], dbo.RH_ClientInfo.AbstractID AS [_], 
				(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(RH_ClientInfo.HospitalID, 0)) as [Hosp ID],
				case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
				replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'')  as [ChartNumber],
				IsNull(dbo.CM_CPI.LastName, '''') + '', '' + IsNull(dbo.CM_CPI.FirstName, '''')  + '' '' + IsNull(dbo.CM_CPI.MiddleName, '''') As [Full Name],
				Convert(VarChar(10), dbo.CM_CPI.BirthDate, 111) AS [Birth Date],
				Convert(VarChar(10), dbo.RH_ClientInfo.AdmitDate, 111) AS [Date Stay Began]
	into ' + @TempTable + ' FROM dbo.CM_CPI INNER JOIN dbo.RH_ClientInfo ON dbo.CM_CPI.ChartNumber = dbo.RH_ClientInfo.ChartNumber
	WHERE dbo.RH_ClientInfo.AssessmentType = 134
	AND (ISNULL(RH_ClientInfo.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(RH_ClientInfo.HospitalID, 0) end) 
	AND dbo.RH_ClientInfo.AbstractID NOT IN (SELECT LinkID FROM dbo.RH_ClientInfo WHERE dbo.RH_ClientInfo.AssessmentType = 135 and LinkID is not null)
	AND dbo.RH_ClientInfo.AbstractID NOT IN (SELECT AbstractID FROM dbo.RH_Administrative WHERE ISNULL(dbo.RH_Administrative.AdmitClass, 0) = 21)
	AND (dbo.CM_CPI.ChartNumber LIKE ''' + @SearchString + '%'' OR dbo.CM_CPI.ChartNumber LIKE ''' + @SearchString2 + '%'')
	AND dbo.RH_ClientInfo.IsDeleted = 2 ' + @SearchPrefix
END

ELSE IF @SearchType = 3 --PR - 05011 or @SearchType = 5
BEGIN
	--POST DISCHARGE(EN-00549) & FOLLOW UP - Can Only Show Charts Already Discharged
	Set @SQL = @SQLTopX + ' PatientID as [ ], dbo.RH_ClientInfo.LinkID AS [_],
				(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(RH_ClientInfo.HospitalID, 0)) as [Hosp ID],
				case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
				replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'')  as [ChartNumber],
				IsNull(dbo.CM_CPI.LastName, '''') + '', '' + IsNull(dbo.CM_CPI.FirstName, '''')  + '' '' + IsNull(dbo.CM_CPI.MiddleName, '''') As [Full Name],
				Convert(VarChar(10), dbo.CM_CPI.BirthDate, 111) AS [Birth Date],
				Convert(VarChar(10), dbo.RH_ClientInfo.AdmitDate, 111) AS [Date Stay Began]
	into ' + @TempTable + ' FROM dbo.CM_CPI INNER JOIN dbo.RH_ClientInfo ON dbo.CM_CPI.ChartNumber = dbo.RH_ClientInfo.ChartNumber
	WHERE dbo.RH_ClientInfo.AssessmentType = 135
	AND (ISNULL(RH_ClientInfo.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(RH_ClientInfo.HospitalID, 0) end) 
	AND dbo.RH_ClientInfo.LinkID NOT IN (SELECT LinkID FROM dbo.RH_ClientInfo WHERE dbo.RH_ClientInfo.AssessmentType = 136 and LinkID is not null)
	AND dbo.RH_ClientInfo.AbstractID NOT IN (SELECT AbstractID FROM dbo.RH_Administrative WHERE ISNULL(dbo.RH_Administrative.DischReason, 0) = 50)
	AND (dbo.CM_CPI.ChartNumber LIKE ''' + @SearchString + '%'' OR dbo.CM_CPI.ChartNumber LIKE ''' + @SearchString2 + '%'')
	AND dbo.RH_ClientInfo.IsDeleted = 2 ' + @SearchPrefix
END
ELSE IF @SearchType = 5 --PR - 05011 to allow post discharge after followup
BEGIN
	--POST DISCHARGE(EN-00549) & FOLLOW UP - Can Only Show Charts Already Discharged
	Set @SQL = @SQLTopX + ' PatientID as [ ], dbo.RH_ClientInfo.LinkID AS [_],
				(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(RH_ClientInfo.HospitalID, 0)) as [Hosp ID],
				case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
				replace(space(10-len(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, '' '', ''0'')  as [ChartNumber],
				IsNull(dbo.CM_CPI.LastName, '''') + '', '' + IsNull(dbo.CM_CPI.FirstName, '''')  + '' '' + IsNull(dbo.CM_CPI.MiddleName, '''') As [Full Name],
				Convert(VarChar(10), dbo.CM_CPI.BirthDate, 111) AS [Birth Date],
				Convert(VarChar(10), dbo.RH_ClientInfo.AdmitDate, 111) AS [Date Stay Began]
	into ' + @TempTable + ' FROM dbo.CM_CPI INNER JOIN dbo.RH_ClientInfo ON dbo.CM_CPI.ChartNumber = dbo.RH_ClientInfo.ChartNumber
	WHERE dbo.RH_ClientInfo.AssessmentType = 135
	AND (ISNULL(RH_ClientInfo.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(RH_ClientInfo.HospitalID, 0) end) 
	AND dbo.RH_ClientInfo.AbstractID NOT IN (SELECT AbstractID FROM dbo.RH_Administrative WHERE ISNULL(dbo.RH_Administrative.DischReason, 0) = 50)
	AND (dbo.CM_CPI.ChartNumber LIKE ''' + @SearchString + '%'' OR dbo.CM_CPI.ChartNumber LIKE ''' + @SearchString2 + '%'')
	AND dbo.RH_ClientInfo.IsDeleted = 2 ' + @SearchPrefix
END
	--print @sql
	exec sp_executesql @sql

	If @ShowVip = '2'
	Begin
		set @SQL = 'delete ' + @TempTable + ' where [ChartNumber] in (select replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') 
			from CM_CPI where isnull(secret, 0) = 1 and replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')
			in (select [ChartNumber] from ' + @TempTable + '))'
		Exec(@SQL)
	End
	Set nocount off
		set @SQL = 'select * From ' + @TempTable
		exec(@SQL)
		set @SQL = 'drop table ' + @TempTable
		exec(@SQL)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



--F_SearchROI  4654, '', '', 4, 0, '', 0


-- Called by the CPI Search Form 
CREATE PROCEDURE [F_SearchROI]
	@FKey as int,
	@SearchString as VarChar(50),
	@SearchString2 as VarChar(50),
	@UserID as int = 1,
	@Exact as int = 0,
	@ExtraSearch 	[varchar](1000) = '',
    @HospID as varchar(10) = '0',
    @Confidential as int = 0	--EN - 00494
AS 

DECLARE @SQL nVarChar(2500)
DECLARE @select NVarChar(2500) --PR-02232
DECLARE @from   NVarChar(500) --PR-02232
DECLARE @where  NVarChar(500) --PR-02232
DECLARE @order  NVarChar(500) --PR-02232

DECLARE @DataType int
DECLARE @FieldName as VarChar(500)
DECLARE @FieldDesc as VarChar(500)
Declare @FieldDT     NVarChar(500) --PR-02232
DECLARE @NameSplit   int

DECLARE @DBTableName as VarChar(500) --PR-02232
declare @TempDB varchar(100)

--13507: Moved to top	
Set @SearchString = replace(@SearchString, '''', '''''')
Set @SearchString2 = replace(@SearchString2, '''', '''''')

--PR-03175: BEGIN
declare @SearchPrefix as nvarchar(50)
declare @SearchPrefix_Org as NVarChar(100) --PR - 05450
declare @ShowVip as nvarchar(1)
declare @TopX as nvarchar(3)
declare @SQLTopX as nvarchar(20)
declare @Confidential_Where as nvarchar(100)

set nocount on

select @SearchPrefix = isnull(SearchChartPrefix, ''), @ShowVip = isnull(ShowVIP, 0) from U_Users where Code = @UserID

set @SearchPrefix_Org = @SearchPrefix   --PR - 05450
if @SearchPrefix <> ''
	set @SearchPrefix = ' and ROI_Main.Chartnumber like ''' + @SearchPrefix + '%'' '
--EN - 00494
if @Confidential = 1 
	set @Confidential_Where = ''
else
	set @Confidential_Where = ' and isnull(ROI_Main.Confidential, 0) = 0 '
	
if @HospID = '0'
	select top 1 @TopX = isnull(TopSearch, '999') from H_HospitalProfile 
else	
	select top 1 @TopX = isnull(TopSearch, '999') from H_HospitalProfile where isnull(Code, 0) = @HospID
set @SQLTopX = 'select top ' + @TopX + ' ' 
--PR-03175: END

SELECT @DataType = (SELECT DataType FROM U_UsersFields  WHERE AppID = 30 AND FieldID = @FKey and UserID = @UserID)
SELECT @FieldName = (SELECT SystemName FROM U_Fields  WHERE FieldID = @FKey)
SELECT @FieldDesc = (SELECT isnull(Header_User, @FieldName) FROM U_UsersFields  WHERE AppID = 30 AND FieldID = @FKey and UserID = @UserID)
SET @NameSplit = CHARINDEX(',', @SearchString) 

select top 1 @DBTableName = Table_Name from information_schema.columns Where Column_Name = @FieldName and Table_Name like 'ROI_%' order by Table_Name
set @TempDB = '##SearchROI' + replace(replace(replace(replace(convert(varchar(50), getdate(), 121), '-', ''), ':', ''), ' ', ''), '.', '') + 
            cast(isnull(@HospID, 0) as varchar(10)) + cast(isnull(@UserID, 0) as varchar(10))

	insert into AU_Search Values (30, @SearchString, @UserID, GetDate(), @FieldDesc) --PR - 06295


--PR-01257 - Changed the First / Last Name to use the ROI fields (which it probably should have been doing anyway)
--EN-00043
if @FKey = 45006 -- TERMINAL DIGIT SORT
    begin
--	declare @order as varchar(400) --PR-02232
-- 	declare @OrdT as varchar(400)
-- 
-- 	declare @TDigit as varchar(10)
-- 	declare @TDigitR as varchar(10)
-- 	declare @TDigitH as varchar(10)
-- 
-- 	select @TDigitR = TerminalDigit from H_RegionProfile
-- 	if @HospID = '0' 
-- 		select top 1 @TDigitH = TerminalDigit from H_HospitalProfile 
-- 	else
-- 		select top 1 @TDigitH = TerminalDigit from H_HospitalProfile where HospitalID = @HospID
-- 	
-- 	set @TDigit = @TDigitR
-- 	if len(@TDigitH) <> 0 and isnull(@TDigitH, '0') <> '0' set @TDigit = @TDigitH
-- 	--set @TDigit = '926315'
-- 	
-- 	declare @Pos1 as varchar(1)
-- 	declare @Len1 as varchar(1)
-- 	declare @Pos2 as varchar(1)
-- 	declare @Len2 as varchar(1)
-- 	declare @Pos3 as varchar(1)
-- 	declare @Len3 as varchar(1)
-- 	declare @Pos4 as varchar(1)
-- 	declare @Len4 as varchar(1)
-- 	declare @Pos5 as varchar(1)
-- 	declare @Len5 as varchar(1)
-- 
-- 	if isnumeric(substring(@TDigit, 1, 1)) = 1 
-- 		set @Pos1 = substring(@TDigit, 1, 1)
-- 	if isnumeric(substring(@TDigit, 2, 1)) = 1 
-- 		set @Len1 = substring(@TDigit, 2, 1)
-- 	if isnumeric(substring(@TDigit, 3, 1)) = 1 
-- 		set @Pos2 = substring(@TDigit, 3, 1)
-- 	if isnumeric(substring(@TDigit, 4, 1)) = 1 
-- 		set @Len2 = substring(@TDigit, 4, 1)
-- 	if isnumeric(substring(@TDigit, 5, 1)) = 1 
-- 		set @Pos3 = substring(@TDigit, 5, 1)
-- 	if isnumeric(substring(@TDigit, 6, 1)) = 1 
-- 		set @Len3 = substring(@TDigit, 6, 1)
-- 	if isnumeric(substring(@TDigit, 7, 1)) = 1 
-- 		set @Pos4 = substring(@TDigit, 7, 1)
-- 	if isnumeric(substring(@TDigit, 8, 1)) = 1 
-- 		set @Len4 = substring(@TDigit, 8, 1)
-- 	if isnumeric(substring(@TDigit, 9, 1)) = 1 
-- 		set @Pos5 = substring(@TDigit, 9, 1)
-- 	if isnumeric(substring(@TDigit, 10, 1)) = 1 
-- 		set @Len5 = substring(@TDigit, 10, 1)
-- 
-- 	if len(@Pos1) <> 0 and len(@Len1) <> 0
-- 		set @OrdT = ' substring(replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0''), ' + @Pos1 + ', ' + @Len1 + '), '
-- 		
-- 	if len(@Pos2) <> 0 and len(@Len2) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0''), ' + @Pos2 + ', ' + @Len2 + '), '
-- 
-- 	if len(@Pos3) <> 0 and len(@Len3) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0''), ' + @Pos3 + ', ' + @Len3 + '), '
-- 
-- 	if len(@Pos4) <> 0 and len(@Len4) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0''), ' + @Pos4 + ', ' + @Len4 + '), '
-- 
-- 	if len(@Pos5) <> 0 and len(@Len5) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0''), ' + @Pos5 + ', ' + @Len5 + '), '
-- 
-- 	if len(@OrdT) <> 0 
-- 		set @OrdT = left(@OrdT, len(@OrdT) - 1)
-- 
-- 	SELECT @SQL = 'SELECT TOP 100 PERCENT ROIID as [ ], 
--			(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(ROI_Main.HospitalID, 0)) as [Hosp ID],
-- 			(select (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = ROI_Main.ChartNumber) as [Deceased],
-- 			REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #],
-- 			(SELECT TOP 1 ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''') + '' '' + ISNULL(MiddleName, '''') FROM CM_CPI WHERE CM_CPI.ChartNumber = ROI_Main.ChartNumber) AS [Patient Name],
-- 			RequestNumber AS [Request Number],
-- 			RequestDate AS [Request Date],
-- 			(SELECT DisplayCode FROM LU_ROI_Requesters WHERE Code = RequesterID) AS [Requester],
-- 			(SELECT DisplayCode FROM LU_ROI_RequestTypes WHERE Code = RequestType) AS [Request Type],
-- 			(SELECT DisplayCode FROM LU_ROI_Status WHERE Code = ROIStatus) AS [Status]
-- 		FROM dbo.ROI_Main 			
-- 		WHERE (ChartNumber LIKE ''' + @SearchString + '%'' OR ChartNumber LIKE ''' + @SearchString2 +'%'')
-- 		AND ISNULL(IsDeleted, 2) <> 1 
--     		and ChartNumber in (select ChartNumber from CM_CPI where (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end)) ' 
-- 		+ @ExtraSearch 
-- 
-- 	set @order = ''
-- 	if len(@OrdT) <> 0 
-- 	        set @order = ' order by ' + @OrdT
    --PR - 04434 put the search item in the first column
	--SELECT @SQL = 'SELECT TOP 100 PERCENT ROIID as [ ], --PR-03175
		set @SQL  = @SQLTopX + ' ROIID as [ ], 
			(select TerminalChart from CM_Terminal where PatientID = (select PatientID from CM_CPI where ChartNumber = ROI_Main.ChartNumber)) as [Terminal #], 
			(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(ROI_Main.HospitalID, 0)) as [Hosp ID],
			(select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = ROI_Main.ChartNumber) as [Deceased],
			REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #],
			--(SELECT TOP 1 ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''') + '' '' + ISNULL(MiddleName, '''') FROM CM_CPI WHERE CM_CPI.ChartNumber = ROI_Main.ChartNumber) AS [Patient Name],
			(ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''')) AS [Patient Name],
			RequestNumber AS [Request Number],
			convert(NVarChar(10), RequestDate, 111) as [Request Dated], 
			convert(NVarChar(10), RequestReceived, 111) as [Receive Date], 
			(SELECT top 1 DisplayCode FROM LU_ROI_Requesters WHERE Code = RequesterID) AS [Requester ID],
			(SELECT top 1 UserDescription FROM LU_ROI_Requesters WHERE Code = RequesterID) AS [Requester ID Desc],
			(SELECT top 1 DisplayCode FROM LU_ROI_RequestTypes WHERE Code = RequestType) AS [Request Type],
			(SELECT top 1 DisplayCode FROM LU_ROI_Status WHERE Code = ROIStatus) AS [Status] into ' + @TempDB + '
		FROM dbo.ROI_Main 	
		where ChartNumber in (select CM_CPI.ChartNumber from CM_CPI where PatientID in (select PatientID from CM_Terminal where TerminalChart Like ''' + @SearchString + '%'' or MaskTerminal Like ''' + @SearchString + '%''))	' 
		+ @SearchPrefix --PR-03175
		+ @Confidential_Where	--EN - 00494
		+ ' AND ISNULL(IsDeleted, 2) <> 1 
			and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '             		
		+ @ExtraSearch 
		--and ChartNumber in (select ChartNumber from CM_CPI where (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end)) ' 

	set @order = ' order by [Hosp ID], (select TerminalChart from CM_Terminal where PatientID = (select PatientID from CM_CPI where ChartNumber = ROI_Main.ChartNumber)) '
	set @sql = @sql + @order
	--print @sql
        exec sp_executesql @sql 
    end

else IF @FieldName = 'ChartNumber' 
BEGIN
    --PR - 05450
    if len(@SearchPrefix_Org) > 0 and len(isnull(@SearchString, '')) > 0
    begin
        if charindex(@SearchPrefix_Org, @SearchString) <> 1
        begin
            set @SearchString = @SearchPrefix_Org + @SearchString
        end
    end

	IF @Exact = 0 
		--SELECT @SQL = 'SELECT TOP 100 PERCENT ROIID as [ ], --PR-03175
		set @SQL = @SQLTopX + ' ROIID as [ ], 
			ChartNumber AS [' + @FieldDesc + '],
			(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(ROI_Main.HospitalID, 0)) as [Hosp ID],
			(select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = ROI_Main.ChartNumber) as [Deceased],
			REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #],
			--(SELECT TOP 1 ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''') + '' '' + ISNULL(MiddleName, '''') FROM CM_CPI WHERE CM_CPI.ChartNumber = ROI_Main.ChartNumber) AS [Patient Name],
			(ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''')) AS [Patient Name],
			RequestNumber AS [Request Number],
			convert(NVarChar(10), RequestDate, 111) as [Request Dated], 
			convert(NVarChar(10), RequestReceived, 111) as [Receive Date], 
			(SELECT top 1 DisplayCode FROM LU_ROI_Requesters WHERE Code = RequesterID) AS [Requester ID],
			(SELECT top 1 UserDescription FROM LU_ROI_Requesters WHERE Code = RequesterID) AS [Requester ID Desc],
			(SELECT top 1 DisplayCode FROM LU_ROI_RequestTypes WHERE Code = RequestType) AS [Request Type],
			(SELECT top 1 DisplayCode FROM LU_ROI_Status WHERE Code = ROIStatus) AS [Status] into ' + @TempDB + '
			FROM dbo.ROI_Main 			
			WHERE (ChartNumber LIKE ''' + @SearchString + '%'' OR ChartNumber LIKE ''' + @SearchString2 +'%'') ' + 
			+ @SearchPrefix --PR-03175
			+ @Confidential_Where --EN - 00494
			+ ' AND ISNULL(IsDeleted, 2) <> 1 
			and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '             		
			+ @ExtraSearch + '
			ORDER BY [Hosp ID], [Chart #] DESC'
			--and ChartNumber in (select ChartNumber from CM_CPI where (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end)) ' 
	ELSE
		--SELECT @SQL = 'SELECT TOP 100 PERCENT ROIID as [ ], --PR-03175
		set @SQL = @SQLTopX + ' ROIID as [ ], 
			ChartNumber AS [' + @FieldDesc + '],
			(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(ROI_Main.HospitalID, 0)) as [Hosp ID],
			(select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = ROI_Main.ChartNumber) as [Deceased],
			REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #],
			--(SELECT TOP 1 ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''') + '' '' + ISNULL(MiddleName, '''') FROM CM_CPI WHERE CM_CPI.ChartNumber = ROI_Main.ChartNumber) AS [Patient Name],
			(ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''')) AS [Patient Name],
			RequestNumber AS [Request Number],
			convert(NVarChar(10), RequestDate, 111) as [Request Dated], 
			convert(NVarChar(10), RequestReceived, 111) as [Receive Date], 
			(SELECT top 1 DisplayCode FROM LU_ROI_Requesters WHERE Code = RequesterID) AS [Requester ID],
			(SELECT top 1 UserDescription FROM LU_ROI_Requesters WHERE Code = RequesterID) AS [Requester ID Desc],
			(SELECT top 1 DisplayCode FROM LU_ROI_RequestTypes WHERE Code = RequestType) AS [Request Type],
			(SELECT top 1 DisplayCode FROM LU_ROI_Status WHERE Code = ROIStatus) AS [Status] into ' + @TempDB + '
			FROM dbo.ROI_Main 			
			WHERE (ChartNumber = ''' + @SearchString + ''' OR ChartNumber = ''' + @SearchString2 +''') ' 
			+ @SearchPrefix --PR-03175
			+ @Confidential_Where --EN - 00494
			+ ' AND ISNULL(IsDeleted, 2) <> 1 
			and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '             		
			+ @ExtraSearch + '
			ORDER BY [Hosp ID], [Chart #] DESC'
			--and ChartNumber in (select ChartNumber from CM_CPI where (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end)) ' 
	--print @sql
	EXECUTE(@SQL)
	--RETURN 0
END

ELSE IF @FieldName = 'RequestNumber' 
BEGIN
	--SELECT @SQL = 'SELECT TOP 100 PERCENT ROIID as [ ], --PR-03175
	set @SQL = @SQLTopX + ' ROIID as [ ], 
		RequestNumber AS [ ' + @FieldDesc + '],			
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(ROI_Main.HospitalID, 0)) as [Hosp ID],
		(select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = ROI_Main.ChartNumber) as [Deceased],
		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #],
		--(SELECT TOP 1 ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''') + '' '' + ISNULL(MiddleName, '''') FROM CM_CPI WHERE CM_CPI.ChartNumber = ROI_Main.ChartNumber) AS [Patient Name],
		(ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''')) AS [Patient Name], 
		RequestNumber AS [Request Number],			
		convert(NVarChar(10), RequestDate, 111) as [Request Dated], 
			convert(NVarChar(10), RequestReceived, 111) as [Receive Date], 
		(SELECT top 1 DisplayCode FROM LU_ROI_Requesters WHERE Code = RequesterID) AS [Requester ID],
		(SELECT top 1 UserDescription FROM LU_ROI_Requesters WHERE Code = RequesterID) AS [Requester ID Desc],
		(SELECT top 1 DisplayCode FROM LU_ROI_RequestTypes WHERE Code = RequestType) AS [Request Type],
		(SELECT top 1 DisplayCode FROM LU_ROI_Status WHERE Code = ROIStatus) AS [Status] into ' + @TempDB + '
		FROM dbo.ROI_Main 			
		WHERE RequestNumber LIKE ''' + @SearchString + '%'' ' 
		+ @SearchPrefix --PR-03175
		+ @Confidential_Where --EN - 00494
		+ ' AND ISNULL(IsDeleted, 2) <> 1 
		and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '      
		+ @ExtraSearch + '
		ORDER BY [Hosp ID], [Request Number] DESC'
	EXECUTE(@SQL)
	--RETURN 0
END

ELSE IF @FieldName = 'LastName' AND @NameSplit = 0
BEGIN
	--13507: Moved to top	
	--SET @SearchString = replace(@SearchString, '''', '''''')
	--SET @SQL = 'SELECT TOP 100 PERCENT ROIID as [ ], --PR-03175
	set @SQL = @SQLTopX + ' ROIID as [ ], 
		LastName AS [' + @FieldDesc + '],			
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(ROI_Main.HospitalID, 0)) as [Hosp ID],
		(select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = ROI_Main.ChartNumber) as [Deceased],
		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #],
		--(SELECT TOP 1 ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''') + '' '' + ISNULL(MiddleName, '''') FROM CM_CPI WHERE CM_CPI.ChartNumber = ROI_Main.ChartNumber) AS [Patient Name],
		(ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''')) AS [Patient Name],
		RequestNumber AS [Request Number],			
		convert(NVarChar(10), RequestDate, 111) as [Request Dated], 
		convert(NVarChar(10), RequestReceived, 111) as [Receive Date], 
		(SELECT top 1 DisplayCode FROM LU_ROI_Requesters WHERE Code = RequesterID) AS [Requester ID],
		(SELECT top 1 UserDescription FROM LU_ROI_Requesters WHERE Code = RequesterID) AS [Requester ID Desc],
		(SELECT top 1 DisplayCode FROM LU_ROI_RequestTypes WHERE Code = RequestType) AS [Request Type],
		(SELECT top 1 DisplayCode FROM LU_ROI_Status WHERE Code = ROIStatus) AS [Status] into ' + @TempDB + '
		FROM dbo.ROI_Main 	
		WHERE LastName Like ''' + @SearchString + '%'' '
		+ @SearchPrefix --PR-03175
		+ @Confidential_Where --EN - 00494
		+ ' AND ISNULL(IsDeleted, 2) <> 1 
        	and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '             		
		+ @ExtraSearch + '
		ORDER BY [Hosp ID], [Patient Name] DESC'
	EXECUTE(@SQL)
	--RETURN 0
END

ELSE IF @FieldName = 'LastName' AND @NameSplit > 0
BEGIN
	--13507: Moved to top	
	--SET @SearchString = replace(@SearchString, '''', '''''')
	--SET @SQL = 'SELECT TOP 100 PERCENT ROIID as [ ], --PR-03175
	set @SQL = @SQLTopX + ' ROIID as [ ], 
		LastName AS [' + @FieldDesc + ' ],			
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(ROI_Main.HospitalID, 0)) as [Hosp ID],
		(select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = ROI_Main.ChartNumber) as [Deceased],
		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #],
		--(SELECT TOP 1 ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''') + '' '' + ISNULL(MiddleName, '''') FROM CM_CPI WHERE CM_CPI.ChartNumber = ROI_Main.ChartNumber) AS [Patient Name],
		(ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''')) AS [Patient Name],
 		RequestNumber AS [Request Number],			
		convert(NVarChar(10), RequestDate, 111) as [Request Dated], 
    	convert(NVarChar(10), RequestReceived, 111) as [Receive Date], 
		(SELECT top 1 DisplayCode FROM LU_ROI_Requesters WHERE Code = RequesterID) AS [Requester ID],
		(SELECT top 1 UserDescription FROM LU_ROI_Requesters WHERE Code = RequesterID) AS [Requester ID Desc],
		(SELECT top 1 DisplayCode FROM LU_ROI_RequestTypes WHERE Code = RequestType) AS [Request Type],
		(SELECT top 1 DisplayCode FROM LU_ROI_Status WHERE Code = ROIStatus) AS [Status] into ' + @TempDB + '
		FROM dbo.ROI_Main 	
		WHERE LastName Like ''' + rtrim(ltrim(Left(@SearchString, @NameSplit-1))) + '%'' 
		AND FirstName Like ''' + rtrim(ltrim(Stuff(@SearchString, 1, @NameSplit, ''))) + '%'' '
		+ @SearchPrefix --PR-03175
		+ @Confidential_Where --EN - 00494
		+ ' AND ISNULL(IsDeleted, 2) <> 1 
        	and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '             		
		+ @ExtraSearch + '
		ORDER BY [Hosp ID], [Patient Name] DESC'
	EXECUTE(@SQL)
END

-- ELSE IF @DataType in (11, 12, 13) --PR-01739
-- BEGIN
-- 	SELECT @SQL = 'SELECT TOP 100 PERCENT ROIID as [ ], 
-- 		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(ROI_Main.HospitalID, 0)) as [Hosp ID],
-- 		(select (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = ROI_Main.ChartNumber) as [Deceased],
-- 		RequestNumber AS [Request Number],			
-- 		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #],
-- 		--(SELECT TOP 1 ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''') + '' '' + ISNULL(MiddleName, '''') FROM CM_CPI WHERE CM_CPI.ChartNumber = ROI_Main.ChartNumber) AS [Patient Name],
-- 		(ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''')) AS [Patient Name],
-- 		convert(NVarChar(10), RequestDate, 111) as [Request Date], 
-- 		(SELECT DisplayCode FROM LU_ROI_Requesters WHERE Code = RequesterID) AS [Requester],
-- 		(SELECT DisplayCode FROM LU_ROI_RequestTypes WHERE Code = RequestType) AS [Request Type],
-- 		(SELECT DisplayCode FROM LU_ROI_Status WHERE Code = ROIStatus) AS [Status]
-- 		FROM dbo.ROI_Main 			
-- 		WHERE ' + @FieldName + ' >= CONVERT(DATETIME, ''' + @SearchString + ''') 
-- 		AND ISNULL(IsDeleted, 2) <> 1 
--         	and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
-- 		+ @ExtraSearch + '
-- 		ORDER BY [Hosp ID], ' + @FieldName 
-- 	EXECUTE(@SQL)
-- 	RETURN 0
-- END-- 
-- ELSE IF @DataType = 15
-- BEGIN
--     set @SearchString = (case charindex(':', @SearchString)
--         when 1 then '00' + @SearchString
--         when 2 then '0' + @SearchString
--         else @SearchString
--     end)
-- 
--     set @SearchString = replace(@SearchString, ':', '')
-- 
--     set @SearchString = (case len(@SearchString) 
--         when 0 then '00:00'
--         when 1 then '00:0' + @SearchString 
--         when 2 then '00:' + @SearchString
--         when 3 then '0' + left(@SearchString, 1) + ':' + right(@SearchString, 2) 
--         when 4 then left(@SearchString, 2) + ':' + right(@SearchString, 2)
--         else left(@SearchString, 2) + ':' + substring(@SearchString, 2, 2)
--     end)
-- 
--     if (isdate(@SearchString) = 0) Set @SearchString = '23:59:59'
--     set @SearchString = '1899-12-30 ' + @SearchString 
-- 
-- 	SELECT @SQL = 'SELECT TOP 100 PERCENT ROIID as [ ], 
-- 		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(ROI_Main.HospitalID, 0)) as [Hosp ID],
-- 		(select (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = ROI_Main.ChartNumber) as [Deceased],
-- 		RequestNumber AS [Request Number],			
-- 		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #],
-- 		--(SELECT TOP 1 ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''') + '' '' + ISNULL(MiddleName, '''') FROM CM_CPI WHERE CM_CPI.ChartNumber = ROI_Main.ChartNumber) AS [Patient Name],
-- 		(ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''')) AS [Patient Name],
-- 		convert(NVarChar(10), RequestDate, 111) as [Request Date], 
-- 		(SELECT DisplayCode FROM LU_ROI_Requesters WHERE Code = RequesterID) AS [Requester],
-- 		(SELECT DisplayCode FROM LU_ROI_RequestTypes WHERE Code = RequestType) AS [Request Type],
-- 		(SELECT DisplayCode FROM LU_ROI_Status WHERE Code = ROIStatus) AS [Status]
-- 		FROM dbo.ROI_Main 			
-- 		WHERE ' + @FieldName + ' >= CONVERT(DATETIME, ''' + @SearchString + ''') 
-- 		AND ISNULL(IsDeleted, 2) <> 1 
--         	and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
-- 		+ @ExtraSearch + '
-- 		ORDER BY [Hosp ID], ' + @FieldName 
-- 	EXECUTE(@SQL)
-- 	RETURN 0
-- END
-- 
-- ELSE
-- BEGIN
-- 	SELECT @SQL = 'SELECT TOP 100 PERCENT ROIID as [ ], 
-- 		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(ROI_Main.HospitalID, 0)) as [Hosp ID],
-- 		(select (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = ROI_Main.ChartNumber) as [Deceased],
-- 		RequestNumber AS [Request Number],			
-- 		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #],
-- 		--(SELECT TOP 1 ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''') + '' '' + ISNULL(MiddleName, '''') FROM CM_CPI WHERE CM_CPI.ChartNumber = ROI_Main.ChartNumber) AS [Patient Name],
-- 		(ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''')) AS [Patient Name],
-- 		convert(NVarChar(10), RequestDate, 111) as [Request Date], 
-- 		(SELECT DisplayCode FROM LU_ROI_Requesters WHERE Code = RequesterID) AS [Requester],
-- 		(SELECT DisplayCode FROM LU_ROI_RequestTypes WHERE Code = RequestType) AS [Request Type],
-- 		(SELECT DisplayCode FROM LU_ROI_Status WHERE Code = ROIStatus) AS [Status]
-- 		FROM dbo.ROI_Main 			
-- 		WHERE ' + @FieldName + ' LIKE ''%' + @SearchString + '%''  
-- 		AND ISNULL(IsDeleted, 2) <> 1 
--         	and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
-- 		+ @ExtraSearch + '
-- 		ORDER BY [Hosp ID], ' + @FieldName 
-- 	EXECUTE(@SQL)
-- 	RETURN 0
-- END
-- 

ELSE 
BEGIN
    declare @TempFieldDesc as Varchar(100)
            
    set @TempFieldDesc = '[ ' + @FieldDesc + ']'
    --PR - 07060
    --set @FieldDesc = '[ ' + @FieldDesc + '] = ' + (case @DataType
    --    when 11 then 'Convert(NVarChar(10), ' + @FieldName + ', 111), '
    --    when 12 then 'Convert(NVarChar(10), ' + @FieldName + ', 111), ' --PR-01739
    --    when 13 then 'Convert(NVarChar(10), ' + @FieldName + ', 111), ' --PR-01739
    --    when 15 then 'Convert(NVarChar(5), ' + @FieldName + ', 14), ' 
    --    else         '' + @FieldName + ', '
    --    end)
    set @FieldDesc =  (case @DataType
        when 11 then 'Convert(NVarChar(10), ' + @FieldName + ', 111) '
        when 12 then 'Convert(NVarChar(10), ' + @FieldName + ', 111) ' --PR-01739
        when 13 then 'Convert(NVarChar(10), ' + @FieldName + ', 111) ' --PR-01739
        when 15 then 'Convert(NVarChar(5), ' + @FieldName + ', 14) ' 
        else         '' + @FieldName + ''
        end) + ' as [ ' + @FieldDesc + '], '

	--set @select = 'select top 100 percent ROI_Main.ROIID as [ ], ' + --PR-03175
	set @select = @SQLTopX + ' ROI_Main.ROIID as [ ], ' + 		
        @FieldDesc +
		' (select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(ROI_Main.HospitalID, 0)) as [Hosp ID], ' +
		' (select top 1 (case when DeathIndicator = 1 then ''Y'' else ''N'' end) from CM_CPI where ChartNumber = ROI_Main.ChartNumber) as [Deceased], ' +
		' REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'') AS [Chart #], ' + 
		' (ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''')) AS [Patient Name], ' + 
		' RequestNumber AS [Request Number], ' +
		' convert(NVarChar(10), RequestDate, 111) as [Request Dated], ' + 
		' convert(NVarChar(10), RequestReceived, 111) as [Receive Date], ' + 
		' (SELECT top 1 DisplayCode FROM LU_ROI_Requesters WHERE Code = RequesterID) AS [Requester ID], ' + 
		' (SELECT top 1 UserDescription FROM LU_ROI_Requesters WHERE Code = RequesterID) AS [Requester ID Desc], ' +
		' (SELECT top 1 DisplayCode FROM LU_ROI_RequestTypes WHERE Code = RequestType) AS [Request Type], ' + 
		' (SELECT top 1 DisplayCode FROM LU_ROI_Status WHERE Code = ROIStatus) AS [Status]  into ' + @TempDB + ' '

	set @from = 'from dbo.ROI_Main ' + (case @DBTableName when 'ROI_Main' then '' else 'join dbo.' + @DBTableName + ' r2 on ROI_Main.ROIID = r2.ROIID ' end)
	
	if (@DataType in (11, 12, 13))     -- if it is a date PR-01739
	begin 
		--EN-00081
		if right(@SearchString, 5) = '00/00' 
			set @where = '(' + @FieldName + ' >= Convert(DateTime, ''' + left(@SearchString, 5) + '01/01'') and ' + @FieldName + ' <= convert(DateTime, ''' + left(@SearchString, 5) + '12/31'')) '
	
		else if right(@SearchString, 2) = '00' 
	        	set @where = '(' + @FieldName + ' >= Convert(DateTime, ''' + left(@SearchString, 8) + '01'') and ' + @FieldName + ' < dateadd(M, 1, Convert(DateTime, ''' + left(@SearchString, 8) + '01''))) '
	
	        Else if (isdate(@SearchString) = 0) 
			set @SearchString = '1950/01/01'
	
		If isnull(@where, '') = ''	            set @where =  ' convert(nvarchar(10), ' + @FieldName + ', 111) = ''' + @SearchString + ''''
	            --12626
		        --set @where = @FieldName + ' = Convert(DateTime, ''' + @SearchString + ''') '
	end 

    if (@DataType = 15) -- if it is a time
    begin 

        set @SearchString = (case charindex(':', @SearchString)
            when 1 then '00' + @SearchString
            when 2 then '0' + @SearchString
            else @SearchString
        end)

        set @SearchString = replace(@SearchString, ':', '')

        set @SearchString = (case len(@SearchString) 
            when 0 then '00:00'
            when 1 then '00:0' + @SearchString 
            when 2 then '00:' + @SearchString
            when 3 then '0' + left(@SearchString, 1) + ':' + right(@SearchString, 2) 
            when 4 then left(@SearchString, 2) + ':' + right(@SearchString, 2)
            else left(@SearchString, 2) + ':' + substring(@SearchString, 2, 2)
        end)

        --if (isdate(@SearchString) = 0) Set @SearchString = '23:59:59' --PR-03191
        --set @where = @FieldName + ' >= ''1899-12-30 ' + @SearchString + ''' ' --PR-03191
	if (isdate(@SearchString) = 0) Set @SearchString = '23:59' --PR-03191
	set @where = 'convert(NVarChar(5), ' + @FieldName + ', 14) >= ''' + @SearchString + ''' ' --PR-03191
    end

    --PR-02625
    else if (@DataType = 3) -- if it is currency
    begin 
        if (isnumeric(@SearchString) = 0) Set @SearchString = '0'
        set @where = @FieldName + ' >= ' + @SearchString 
    end

    else if isnull(@where, '') = ''-- all other cases
    begin
	select @FieldDT = Data_Type from information_schema.columns Where Column_Name = @FieldName and Table_Name like 'AB_%'
	If (@FieldDT = 'int') 
        begin
	    --if (@SearchString = '') Set @SearchString = '0'
            if (isnumeric(@SearchString) <> 1) Set @SearchString = '0'
            set @where = @FieldName + ' >= ' + @SearchString + ' '
        end
        else set @where = @FieldName + ' like ''%' + @SearchString + '%'' '
    end 

    set @where = 
        'where isnull(IsDeleted, 0) = 2 and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) ' +
        'and ' + @where + @SearchPrefix 			
        + @Confidential_Where --EN - 00494
		+ @ExtraSearch

    set @order = ' ORDER BY [Hosp ID], ' + @TempFieldDesc 

    select @sql = @select + @from + @where + @order
    --print @sql
    exec sp_executesql @sql
END

If @ShowVip <> '1'
Begin
	set @SQL = 'delete ' + @TempDB + ' where [Chart #] in (select replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') 
		from CM_CPI where isnull(secret, 0) = 1 and replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')
		in (select [Chart #] from ' + @TempDB + '))'
	--print @SQL	
	Exec(@SQL)
End

set @sql = 'select * from  ' + @TempDB 
exec (@sql)
set nocount off
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO






-- Called by the Scheduler Search Form
CREATE     PROCEDURE [F_SearchSchedule]
	@FKey as int,
	@SearchString as VarChar(50),
	@UserID as int = 1,
	@Exact as int = 0,
	@ExtraSearch 	[varchar](1000) = ''
AS 

--SH_Appointments


DECLARE @SQL nVarChar(1500)
DECLARE @DataType int
DECLARE @FieldName as VarChar(50)
DECLARE @FieldDescription as VarChar(50)
DECLARE @NameSplit   int

	SELECT @DataType = (SELECT DataType FROM U_UsersFields  WHERE AppID = 500 AND FieldID = @FKey and UserID = @UserID)
	SELECT @FieldName = (SELECT SystemName FROM U_Fields  WHERE FieldID = @FKey)
	SELECT @FieldDescription = (SELECT ISNULL(Header_User, @FieldName) FROM U_UsersFields  WHERE AppID = 500 AND FieldID = @FKey and UserID = @UserID)
	SET @NameSplit = CHARINDEX(',', @SearchString) 


IF @FieldName = 'PatientID' 
BEGIN	
	IF @Exact = 0 
		SELECT dbo.SH_Appointments.AppointmentID AS [ ], 
			(SELECT DisplayCode FROM LU_Provider WHERE Code = ProviderNumber) AS [Provider #], 
			REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, ' ', '0')  AS [Chart #], 
	    		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [Full Name], 
	    		CONVERT(VARCHAR(10), AppointmentDate, 111) AS [Appnt Date], 
	    		CONVERT(VARCHAR(5), AppointmentTime, 14) AS [Appnt Time],
			(SELECT DisplayCode FROM LU_CodeFile WHERE Code = Location) AS [Location], 
	                      	(SELECT DisplayCode FROM LU_CodeFile WHERE Code = Room) AS [Room]
		FROM dbo.SH_Appointments INNER JOIN dbo.CM_CPI ON dbo.SH_Appointments.Patientid = dbo.CM_CPI.PatientID
		WHERE ChartNumber LIKE @SearchString + '%' AND IsDeleted = 2 AND ISNULL(Status, 0) = 0
		ORDER BY ChartNumber, AppointmentDate
	ELSE
		SELECT dbo.SH_Appointments.AppointmentID AS [ ], 
			(SELECT DisplayCode FROM LU_Provider WHERE Code = ProviderNumber) AS [Provider #], 
			REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, ' ', '0')  AS [Chart #], 
	    		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [Full Name], 
	    		CONVERT(VARCHAR(10), AppointmentDate, 111) AS [Appnt Date], 
    			CONVERT(VARCHAR(5), AppointmentTime, 14) AS [Appnt Time],
			(SELECT DisplayCode FROM LU_CodeFile WHERE Code = Location) AS [Location], 
	                      	(SELECT DisplayCode FROM LU_CodeFile WHERE Code = Room) AS [Room]
		FROM dbo.SH_Appointments INNER JOIN dbo.CM_CPI ON dbo.SH_Appointments.Patientid = dbo.CM_CPI.PatientID
		WHERE ChartNumber = @SearchString AND IsDeleted = 2 AND ISNULL(Status, 0) = 0
		ORDER BY ChartNumber, AppointmentDate

	RETURN 0
END

ELSE IF @FieldName = 'LastName' AND @NameSplit = 0
BEGIN
	SET @SearchString = REPLACE(@SearchString, '''', '''''')
	SELECT dbo.SH_Appointments.AppointmentID AS [ ], 
		(SELECT DisplayCode FROM LU_Provider WHERE Code = ProviderNumber) AS [Provider #], 
		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, ' ', '0')  AS [Chart #], 
    		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [Full Name], 
    		CONVERT(VARCHAR(10), AppointmentDate, 111) AS [Appnt Date], 
    		CONVERT(VARCHAR(5), AppointmentTime, 14) AS [Appnt Time],
		(SELECT DisplayCode FROM LU_CodeFile WHERE Code = Location) AS [Location], 
                      	(SELECT DisplayCode FROM LU_CodeFile WHERE Code = Room) AS [Room]
	FROM dbo.SH_Appointments INNER JOIN dbo.CM_CPI ON dbo.SH_Appointments.Patientid = dbo.CM_CPI.PatientID
	WHERE LastName LIKE @SearchString + '%' AND IsDeleted = 2 AND ISNULL(Status, 0) = 0
	ORDER BY LastName DESC, FirstName, AppointmentDate DESC
	RETURN 0
END
	
ELSE IF @FieldName = 'LastName' AND @NameSplit > 0
BEGIN
	SET @SearchString = REPLACE(@SearchString, '''', '''''')
	SELECT dbo.SH_Appointments.AppointmentID AS [ ], 
		(SELECT DisplayCode FROM LU_Provider WHERE Code = ProviderNumber) AS [Provider #], 
		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, ' ', '0')  AS [Chart #], 
    		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [Full Name], 
    		CONVERT(VARCHAR(10), AppointmentDate, 111) AS [Appnt Date], 
    		CONVERT(VARCHAR(5), AppointmentTime, 14) AS [Appnt Time],
		(SELECT DisplayCode FROM LU_CodeFile WHERE Code = Location) AS [Location], 
                      	(SELECT DisplayCode FROM LU_CodeFile WHERE Code = Room) AS [Room]
	FROM dbo.SH_Appointments INNER JOIN dbo.CM_CPI ON dbo.SH_Appointments.Patientid = dbo.CM_CPI.PatientID
	WHERE LastName LIKE RTRIM(LTRIM(LEFT(@SearchString, @NameSplit-1))) + '%'
	AND FirstName LIKE RTRIM(LTRIM(STUFF(@SearchString, 1, @NameSplit, ''))) + '%'  AND IsDeleted = 2 AND ISNULL(Status, 0) = 0
	ORDER BY LastName DESC, FirstName, AppointmentDate DESC
	RETURN 0
END

ELSE IF  @DataType in (11, 12, 13) --PR-01739
BEGIN
		SELECT @SQL = 'SELECT 
		dbo.SH_Appointments.AppointmentID AS [ ], 
		(SELECT DisplayCode FROM LU_Provider WHERE Code = ProviderNumber) AS [Provider #], 
		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'')  AS [Chart #], 
			ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''') + '' '' + ISNULL(MiddleName, '''') AS [Full Name], 
    		CONVERT(VARCHAR(10), AppointmentDate, 111) AS [Appnt Date], 
			CONVERT(VARCHAR(5), AppointmentTime, 14) AS [Appnt Time],
		(SELECT DisplayCode FROM LU_CodeFile WHERE Code = Location) AS [Location], 
                      	(SELECT DisplayCode FROM LU_CodeFile WHERE Code = Room) AS [Room]
	FROM dbo.SH_Appointments INNER JOIN dbo.CM_CPI ON dbo.SH_Appointments.Patientid = dbo.CM_CPI.PatientID
	WHERE ' + @FieldName + ' >= CONVERT(DATETIME, ''' + @SearchString + ''') AND ISNULL(Status, 0) = 0
	ORDER BY ' + @FieldName 	EXECUTE(@SQL)
	RETURN 0
END


ELSE IF  @DataType = 15
BEGIN	
	SET @SearchString = (CASE CHARINDEX(':', @SearchString) WHEN 1 THEN '00' + @SearchString WHEN 2 THEN '0' + @SearchString ELSE @SearchString END)
	SET @SearchString = REPLACE(@SearchString, ':', '')	
	SET @SearchString = (CASE LEN(@SearchString) WHEN 0 THEN '00:00' WHEN 1 THEN '00:0' + @SearchString WHEN 2 THEN '00:' + @SearchString WHEN 3 THEN '0' + LEFT(@SearchString, 1) + ':' + RIGHT(@SearchString, 2) WHEN 4 THEN LEFT(@SearchString, 2) + ':' + RIGHT(@SearchString, 2) ELSE LEFT(@SearchString, 2) + ':' + SUBSTRING(@SearchString, 2, 2) END)

	--IF (ISDATE(@SearchString) = 0) SET @SearchString = '23:59:59'  --PR-03191
	--SET @SearchString = @FieldName + ' >= ''1899-12-30 ' + @SearchString + ''' '  --PR-03191
	if (isdate(@SearchString) = 0) Set @SearchString = '23:59' --PR-03191
	set @SearchString = 'convert(NVarChar(5), ' + @FieldName + ', 14) >= ''' + @SearchString + ''' ' --PR-03191

	SELECT @SQL = 'SELECT 
		dbo.SH_Appointments.AppointmentID AS [ ], 
		(SELECT DisplayCode FROM LU_Provider WHERE Code = ProviderNumber) AS [Provider #], 
		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'')  AS [Chart #], 
			ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''') + '' '' + ISNULL(MiddleName, '''') AS [Full Name], 
    		CONVERT(VARCHAR(10), AppointmentDate, 111) AS [Appnt Date], 
			CONVERT(VARCHAR(5), AppointmentTime, 14) AS [Appnt Time],
		(SELECT DisplayCode FROM LU_CodeFile WHERE Code = Location) AS [Location], 
                      	(SELECT DisplayCode FROM LU_CodeFile WHERE Code = Room) AS [Room]
	FROM dbo.SH_Appointments INNER JOIN dbo.CM_CPI ON dbo.SH_Appointments.Patientid = dbo.CM_CPI.PatientID
	WHERE ' + @SearchString + ' AND ISNULL(Status, 0) = 0
	ORDER BY ' + @FieldName 	EXECUTE(@SQL)
	RETURN 0
END

ELSE
BEGIN
	SELECT @SQL = 'SELECT 
		dbo.SH_Appointments.AppointmentID AS [ ], 
		(SELECT DisplayCode FROM LU_Provider WHERE Code = ProviderNumber) AS [Provider #], 
		REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, '' '', ''0'')  AS [Chart #], 
			ISNULL(LastName, '''') + '', '' + ISNULL(FirstName, '''') + '' '' + ISNULL(MiddleName, '''') AS [Full Name], 
    		CONVERT(VARCHAR(10), AppointmentDate, 111) AS [Appnt Date], 
			CONVERT(VARCHAR(5), AppointmentTime, 14) AS [Appnt Time],
		(SELECT DisplayCode FROM LU_CodeFile WHERE Code = Location) AS [Location], 
                      	(SELECT DisplayCode FROM LU_CodeFile WHERE Code = Room) AS [Room]
	FROM dbo.SH_Appointments INNER JOIN dbo.CM_CPI ON dbo.SH_Appointments.Patientid = dbo.CM_CPI.PatientID
	WHERE ' + @FieldName + ' LIKE ''%' + @SearchString + '%'' AND ISNULL(Status, 0) = 0
	ORDER BY ' + @FieldName 
	EXECUTE(@SQL)
	RETURN 0
END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- Called by the Transcription Search Form 
CREATE             PROCEDURE [F_SearchTransAdd]
	@FKey 		[int],
	@SearchString 	[varchar](50) = '',
	@SearchString2 [varchar](50) = '',
	@UserID 	[int] = 1,
	@Exact 	[int] = 0,
	@HospID [varchar](100) = '0',
	@ExtraSearch 	[varchar](1000) = ''
AS 

DECLARE @SQL    varchar(2500)
DECLARE @FieldName   varchar(50)
DECLARE @NameSplit   int
DECLARE @Top 	int

SELECT @Top = ISNULL(TopSearch, 999) FROM H_HospitalProfile
SET ROWCOUNT @TOP

SELECT @FieldName   = SystemName FROM U_Fields  WHERE FieldID = @FKey

-- --13507: Moved to top	
-- Set @SearchString = replace(@SearchString, '''', '''''')
-- Set @SearchString2 = replace(@SearchString2, '''', '''''')

SET @NameSplit = CHARINDEX(',', @SearchString) 
IF @FieldName = 'ChartNumber' 
BEGIN		
/*
		SET @SQL = 
			'SELECT dbo.CM_CPI.PatientID AS [ ],  dbo.AB_Abstract.AbstractID AS [ ], 
			case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased],
			REPLACE(SPACE(10-LEN(dbo.AB_Abstract.ChartNumber)) + dbo.AB_Abstract.ChartNumber, '' '', ''0'')  AS [Chart #],
			dbo.AB_Abstract.EncounterNumber AS [Encounter #], 
			ISNULL(dbo.AB_Abstract.LastName, '''') + '', '' + ISNULL(dbo.AB_Abstract.FirstName, '''') + '' '' + ISNULL(dbo.AB_Abstract.MiddleName, '''') AS [Full Name], 
			CONVERT(VARCHAR(10), dbo.AB_Abstract.DischargeDate, 111) AS [Disch Date],  
			CONVERT(VARCHAR(5), dbo.AB_Abstract.DischargeTime, 14) AS [Disch Time],
			CONVERT(VARCHAR(10), dbo.AB_Abstract.AdmitDate, 111) AS [Admit Date], 
			CONVERT(VARCHAR(5), dbo.AB_Abstract.AdmitTime, 14) AS [Admit Time] 
			FROM dbo.CM_CPI INNER JOIN dbo.AB_Abstract ON dbo.CM_CPI.ChartNumber = dbo.AB_Abstract.ChartNumber
			WHERE (dbo.AB_Abstract.ChartNumber Like ''' + @SearchString + '%'' OR dbo.AB_Abstract.ChartNumber LIKE ''' + @SearchString2 +'%'')
			AND dbo.AB_Abstract.IsDeleted = 2
			AND (ISNULL(AB_Abstract.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(AB_Abstract.HospitalID, 0) end) '
			+ @ExtraSearch + '
			ORDER BY [Chart #] Desc, DischargeDate DESC'			
*/

	IF @Exact = 0
		select isnull(UniversalID, 0) as [u], isnull(PatientID, 0) as [p], isnull(AbstractID, 0) as [a], isnull(AppType, 0) as [c],
		case when DeathIndicator = 1 then 'Y' else 'N' end as [Deceased],
		(select UserDescription from LU_CareType where Code = AppType) as [Visit Type],
		replace(space(10-len(ChartNumber)) + ChartNumber, ' ', '0')  as [Chart #],
		EncounterNumber as [Encounter #], 
		isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') as [Full Name], 
		convert(varchar(10), DischargeDate, 111) as [Disch Date],  
		convert(varchar(5), DischargeTime, 14) as [Disch Time],
		convert(varchar(10), AdmitDate, 111) as [Admit Date], 
		convert(varchar(5), AdmitTime, 14) as [Admit Time] 
		from AB_Main
		where (ChartNumber like @SearchString + '%' or ChartNumber like @SearchString2 + '%')
		and IsDeleted = 2
		and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by [Chart #] desc, DischargeDate desc
	ELSE
		select isnull(UniversalID, 0) as [u], isnull(PatientID, 0) as [p], isnull(AbstractID, 0) as [a], isnull(AppType, 0) as [c],
		case when DeathIndicator = 1 then 'Y' else 'N' end as [Deceased],
		(select UserDescription from LU_CareType where Code = AppType) as [Visit Type],
		replace(space(10-len(ChartNumber)) + ChartNumber, ' ', '0')  as [Chart #],
		EncounterNumber as [Encounter #], 
		isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') as [Full Name], 
		convert(varchar(10), DischargeDate, 111) as [Disch Date],  
		convert(varchar(5), DischargeTime, 14) as [Disch Time],
		convert(varchar(10), AdmitDate, 111) as [Admit Date], 
		convert(varchar(5), AdmitTime, 14) as [Admit Time] 
		from AB_Main
		where (ChartNumber = @SearchString or ChartNumber = @SearchString2)
		and IsDeleted = 2
		and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by [Chart #] desc, DischargeDate desc

--	EXECUTE(@SQL)
	SET ROWCOUNT 0
	RETURN 0
END

ELSE IF @FieldName = 'EncounterNumber'     	
BEGIN
	select isnull(UniversalID, 0) as [u], isnull(PatientID, 0) as [p], isnull(AbstractID, 0) as [a], isnull(AppType, 0) as [c],
	case when DeathIndicator = 1 then 'Y' else 'N' end as [Deceased],
	(select UserDescription from LU_CareType where Code = AppType) as [Visit Type],
	EncounterNumber as [Encounter #], 
	replace(space(10-len(ChartNumber)) + ChartNumber, ' ', '0')  as [Chart #],
	isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') as [Full Name], 
	convert(varchar(10), DischargeDate, 111) as [Disch Date],  
	convert(varchar(5), DischargeTime, 14) as [Disch Time],
	convert(varchar(10), AdmitDate, 111) as [Admit Date], 
	convert(varchar(5), AdmitTime, 14) as [Admit Time] 
	from AB_Main
	where (EncounterNumber like + @SearchString + '%' )
	and IsDeleted = 2
	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	order by [Encounter #] desc, DischargeDate desc

	SET ROWCOUNT 0
	RETURN 0
END

ELSE IF @FieldName = 'DischargeDate' 
BEGIN

	IF RIGHT(@SearchString, 5) = '00/00' 
		select isnull(UniversalID, 0) as [u], isnull(PatientID, 0) as [p], isnull(AbstractID, 0) as [a], isnull(AppType, 0) as [c],
		case when DeathIndicator = 1 then 'Y' else 'N' end as [Deceased],
		(select UserDescription from LU_CareType where Code = AppType) as [Visit Type],
		convert(varchar(10), DischargeDate, 111) as [Disch Date],  
		replace(space(10-len(ChartNumber)) + ChartNumber, ' ', '0')  as [Chart #],
		EncounterNumber as [Encounter #], 
		isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') as [Full Name], 
		convert(varchar(5), DischargeTime, 14) as [Disch Time],
		convert(varchar(10), AdmitDate, 111) as [Admit Date], 
		convert(varchar(5), AdmitTime, 14) as [Admit Time] 
		from AB_Main
		where (DischargeDate >= convert(datetime, left(@SearchString, 5) + '01/01') and DischargeDate <= convert(DateTime, left(@SearchString, 5) + '12/31')) 
		and IsDeleted = 2
		and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by DischargeDate desc

	else IF RIGHT(@SearchString, 2) = '00' 
		select isnull(UniversalID, 0) as [u], isnull(PatientID, 0) as [p], isnull(AbstractID, 0) as [a], isnull(AppType, 0) as [c],
		case when DeathIndicator = 1 then 'Y' else 'N' end as [Deceased],
		(select UserDescription from LU_CareType where Code = AppType) as [Visit Type],
		convert(varchar(10), DischargeDate, 111) as [Disch Date],  
		replace(space(10-len(ChartNumber)) + ChartNumber, ' ', '0')  as [Chart #],
		EncounterNumber as [Encounter #], 
		isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') as [Full Name], 
		convert(varchar(5), DischargeTime, 14) as [Disch Time],
		convert(varchar(10), AdmitDate, 111) as [Admit Date], 
		convert(varchar(5), AdmitTime, 14) as [Admit Time] 
		from AB_Main
		where (DischargeDate >= convert(datetime, left(@SearchString, 8) + '01') and DischargeDate < dateadd(M, 1, Convert(DateTime, left(@SearchString, 8) + '01'))) 
		and IsDeleted = 2
		and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by DischargeDate desc
	ELSE
		select isnull(UniversalID, 0) as [u], isnull(PatientID, 0) as [p], isnull(AbstractID, 0) as [a], isnull(AppType, 0) as [c],
		case when DeathIndicator = 1 then 'Y' else 'N' end as [Deceased],
		(select UserDescription from LU_CareType where Code = AppType) as [Visit Type],
		convert(varchar(10), DischargeDate, 111) as [Disch Date],  
		replace(space(10-len(ChartNumber)) + ChartNumber, ' ', '0')  as [Chart #],
		EncounterNumber as [Encounter #], 
		isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') as [Full Name], 
		convert(varchar(5), DischargeTime, 14) as [Disch Time],
		convert(varchar(10), AdmitDate, 111) as [Admit Date], 
		convert(varchar(5), AdmitTime, 14) as [Admit Time] 
		from AB_Main
		where (DischargeDate >= convert(datetime, @SearchString)) 
		and IsDeleted = 2
		and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by DischargeDate desc

	SET ROWCOUNT 0
	RETURN 0
END

ELSE IF @FieldName = 'AdmitDate' 
BEGIN
	IF RIGHT(@SearchString, 2) = '00/00' 
		select isnull(UniversalID, 0) as [u], isnull(PatientID, 0) as [p], isnull(AbstractID, 0) as [a], isnull(AppType, 0) as [c],
		case when DeathIndicator = 1 then 'Y' else 'N' end as [Deceased],
		(select UserDescription from LU_CareType where Code = AppType) as [Visit Type],
		convert(varchar(10), AdmitDate, 111) as [Admit Date], 
		replace(space(10-len(ChartNumber)) + ChartNumber, ' ', '0')  as [Chart #],
		EncounterNumber as [Encounter #], 
		isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') as [Full Name], 
		convert(varchar(10), DischargeDate, 111) as [Disch Date],  
		convert(varchar(5), DischargeTime, 14) as [Disch Time],
		convert(varchar(5), AdmitTime, 14) as [Admit Time] 
		from AB_Main
		where (AdmitDate >= convert(datetime, left(@SearchString, 5) + '01/01') and AdmitDate <= convert(DateTime, left(@SearchString, 5) + '12/31')) 
		and IsDeleted = 2
		and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by AdmitDate desc

	else IF RIGHT(@SearchString, 2) = '00' 
		select isnull(UniversalID, 0) as [u], isnull(PatientID, 0) as [p], isnull(AbstractID, 0) as [a], isnull(AppType, 0) as [c],
		case when DeathIndicator = 1 then 'Y' else 'N' end as [Deceased],
		(select UserDescription from LU_CareType where Code = AppType) as [Visit Type],
		convert(varchar(10), AdmitDate, 111) as [Admit Date], 
		replace(space(10-len(ChartNumber)) + ChartNumber, ' ', '0')  as [Chart #],
		EncounterNumber as [Encounter #], 
		isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') as [Full Name], 
		convert(varchar(10), DischargeDate, 111) as [Disch Date],  
		convert(varchar(5), DischargeTime, 14) as [Disch Time],
		convert(varchar(5), AdmitTime, 14) as [Admit Time] 
		from AB_Main
		where (AdmitDate >= convert(datetime, left(@SearchString, 8) + '01') and AdmitDate < dateadd(M, 1, Convert(DateTime, left(@SearchString, 8) + '01'))) 
		and IsDeleted = 2
		and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by AdmitDate desc

        ELSE
		select isnull(UniversalID, 0) as [u], isnull(PatientID, 0) as [p], isnull(AbstractID, 0) as [a], isnull(AppType, 0) as [c],
		case when DeathIndicator = 1 then 'Y' else 'N' end as [Deceased],		
		(select UserDescription from LU_CareType where Code = AppType) as [Visit Type],
		convert(varchar(10), AdmitDate, 111) as [Admit Date], 
		replace(space(10-len(ChartNumber)) + ChartNumber, ' ', '0')  as [Chart #],
		EncounterNumber as [Encounter #], 
		isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') as [Full Name], 
		convert(varchar(10), DischargeDate, 111) as [Disch Date],  
		convert(varchar(5), DischargeTime, 14) as [Disch Time],		
		convert(varchar(5), AdmitTime, 14) as [Admit Time] 
		from AB_Main
		where (AdmitDate >= convert(datetime, @SearchString)) 
		and IsDeleted = 2
		and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by AdmitDate desc

	EXECUTE(@SQL)
	SET ROWCOUNT 0
	RETURN 0
END
	
ELSE IF @FieldName = 'LastName' AND @NameSplit = 0
BEGIN
	--set @SearchString = replace(@SearchString, '''', '''''')

	select isnull(UniversalID, 0) as [u], isnull(PatientID, 0) as [p], isnull(AbstractID, 0) as [a], isnull(AppType, 0) as [c],
	case when DeathIndicator = 1 then 'Y' else 'N' end as [Deceased],
	(select UserDescription from LU_CareType where Code = AppType) as [Visit Type],
	isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') as [Full Name], 
	replace(space(10-len(ChartNumber)) + ChartNumber, ' ', '0')  as [Chart #],
	EncounterNumber as [Encounter #], 
	convert(varchar(10), DischargeDate, 111) as [Disch Date],  
	convert(varchar(5), DischargeTime, 14) as [Disch Time],
	convert(varchar(10), AdmitDate, 111) as [Admit Date], 
	convert(varchar(5), AdmitTime, 14) as [Admit Time] 
	from AB_Main
	where LastName like @SearchString + '%'
	and IsDeleted = 2
	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	order by  LastName desc, FirstName, AdmitDate desc

	SET ROWCOUNT 0	
	RETURN 0
END
	
ELSE IF @FieldName = 'LastName' AND @NameSplit > 0
BEGIN
	--set @SearchString = replace(@SearchString, '''', '''''')

	select isnull(UniversalID, 0) as [u], isnull(PatientID, 0) as [p], isnull(AbstractID, 0) as [a], isnull(AppType, 0) as [c],
	case when DeathIndicator = 1 then 'Y' else 'N' end as [Deceased],
	(select UserDescription from LU_CareType where Code = AppType) as [Visit Type],
	isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') as [Full Name], 
	replace(space(10-len(ChartNumber)) + ChartNumber, ' ', '0')  as [Chart #],
	EncounterNumber as [Encounter #], 
	convert(varchar(10), DischargeDate, 111) as [Disch Date],  
	convert(varchar(5), DischargeTime, 14) as [Disch Time],
	convert(varchar(10), AdmitDate, 111) as [Admit Date], 
	convert(varchar(5), AdmitTime, 14) as [Admit Time] 
	from AB_Main
	where LastName like rtrim(ltrim(left(@SearchString, @NameSplit-1))) + '%' 
	and FirstName like rtrim(ltrim(stuff(@SearchString, 1, @NameSplit, ''))) + '%' 
	and IsDeleted = 2
	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	order by  LastName desc, FirstName, AdmitDate desc

	SET ROWCOUNT 0
	RETURN 0
END




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

-- Called by the Transcription Search Form 
CREATE PROCEDURE [F_SearchTransEdit]
	@FKey 		[int],
	@SearchString 	[varchar](50) = '',
	@SearchString2 [varchar](50) = '',
	@UserID 	[int] = 1,
	@Exact 	[int] = 0,
	@HospID	[varchar](100) = '0',
	@ExtraSearch 	[varchar](1000) = ''
AS 

DECLARE @SQL    varchar(3500)
	DECLARE @select varchar(1500)
	DECLARE @where  varchar(500)
	DECLARE @order  varchar(100)

DECLARE @DataType    int
DECLARE @LookupTable varchar(50)
DECLARE @FieldName   varchar(50)
DECLARE @NameSplit   int
DECLARE @FieldDesc   varchar(150)
DECLARE @Temp        datetime
DECLARE @DBTableName varchar(50)
Declare @FieldDT     varchar(20)
DECLARE @Top 	int


--13507: Moved to top	
Set @SearchString = replace(@SearchString, '''', '''''')
Set @SearchString2 = replace(@SearchString2, '''', '''''')

SELECT @DataType    = DataType FROM U_UsersFields  WHERE AppID = 20 AND FieldID = @FKey AND UserID = @UserID
SELECT @LookupTable = LookUpTable FROM U_UsersFields  WHERE AppID = 20 AND FieldID = @FKey AND UserID = @UserID
SELECT @FieldName   = SystemName FROM U_Fields  WHERE FieldID = @FKey
SELECT @FieldDesc    = Header_User FROM U_UsersFields  WHERE AppID = 20 AND FieldID = @FKey AND UserID = @UserID
SELECT @DBTableName = Table_Name FROM information_schema.columns WHERE Column_Name = @FieldName and (Table_Name like 'TR[_]%' or table_name = 'AB_Abstract')

SELECT @Top = ISNULL(TopSearch, 999) FROM H_HospitalProfile
SET ROWCOUNT @Top

if (@DataType in (11, 12, 13))     -- if it is a date --PR-01739
begin 
	if right(@SearchString, 5) = '00/00' 
		set @where = '(' + @DBTableName + '.' + @FieldName + ' >= Convert(DateTime, ''' + left(@SearchString, 5) + '01/01'') and ' + @DBTableName + '.' + @FieldName + ' <= convert(DateTime, ''' + left(@SearchString, 5) + '12/31'')) '

	else if right(@SearchString, 2) = '00' 
		set @where = '(' + @DBTableName + '.' + @FieldName + ' >= Convert(DateTime, ''' + left(@SearchString, 8) + '01'') and ' + @DBTableName + '.' + @FieldName + ' < dateadd(M, 1, Convert(DateTime, ''' + left(@SearchString, 8) + '01''))) '

	Else if (isdate(@SearchString) = 0) 
		set @SearchString = '1950/01/01'

	If isnull(@where, '') = ''
	        set @where = @DBTableName + '.' + @FieldName + ' = Convert(DateTime, ''' + @SearchString + ''') '
end 

SET @NameSplit = CHARINDEX(',', @SearchString) 
IF @FieldName in ('ChartNumber', 'DischargeDate', 'LastName')
BEGIN
	IF @FieldName = 'ChartNumber' 
	BEGIN		
		IF @Exact = 0
			SET @SQL = 
				'SELECT dbo.TR_Main.TranscriptionID AS [ ], 
				(select UserDescription from LU_CareType where Code = TR_Main.CareType) as [Visit Type],
			    	REPLACE(SPACE(10-LEN(dbo.AB_Abstract.ChartNumber)) + dbo.AB_Abstract.ChartNumber, '' '', ''0'')  AS [Chart #],
				ISNULL(dbo.AB_Abstract.LastName, '''') + '', '' + ISNULL(dbo.AB_Abstract.FirstName, '''') + '' '' + ISNULL(dbo.AB_Abstract.MiddleName, '''') AS [Full Name], 
			    	CONVERT(VARCHAR(10), dbo.AB_Abstract.DischargeDate, 111) AS [Disch Date],  
				(SELECT DisplayCode FROM LU_TranscriptDocument WHERE Code = dbo.TR_Main.DocumentType) AS [Doc Type], 
			             dbo.TR_Main.DocumentName AS [Doc Name]
				FROM dbo.AB_Abstract INNER JOIN dbo.TR_Main ON dbo.AB_Abstract.AbstractID = dbo.TR_Main.AbstractID INNER JOIN dbo.CM_CPI ON dbo.TR_Main.PatientID = dbo.CM_CPI.PatientID AND dbo.AB_Abstract.ChartNumber = dbo.CM_CPI.ChartNumber
				WHERE (dbo.AB_Abstract.ChartNumber Like ''' + @SearchString + '%'' OR dbo.AB_Abstract.ChartNumber LIKE ''' + @SearchString2 +'%'')
				AND dbo.AB_Abstract.IsDeleted = 2
				AND dbo.TR_Main.IsDeleted = 2
				AND (ISNULL(AB_Abstract.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(AB_Abstract.HospitalID, 0) end) '
				+ @ExtraSearch + '
				ORDER BY [Chart #] Desc, DischargeDate DESC'	
		ELSE
			SET @SQL = 
				'SELECT dbo.TR_Main.TranscriptionID AS [ ], 
				(select UserDescription from LU_CareType where Code = TR_Main.CareType) as [Visit Type],
			    	REPLACE(SPACE(10-LEN(dbo.AB_Abstract.ChartNumber)) + dbo.AB_Abstract.ChartNumber, '' '', ''0'')  AS [Chart #],
				ISNULL(dbo.AB_Abstract.LastName, '''') + '', '' + ISNULL(dbo.AB_Abstract.FirstName, '''') + '' '' + ISNULL(dbo.AB_Abstract.MiddleName, '''') AS [Full Name], 
			    	CONVERT(VARCHAR(10), dbo.AB_Abstract.DischargeDate, 111) AS [Disch Date],  
				(SELECT DisplayCode FROM LU_TranscriptDocument WHERE Code = dbo.TR_Main.DocumentType) AS [Doc Type], 
			             dbo.TR_Main.DocumentName AS [Doc Name]
				FROM dbo.AB_Abstract INNER JOIN dbo.TR_Main ON dbo.AB_Abstract.AbstractID = dbo.TR_Main.AbstractID INNER JOIN dbo.CM_CPI ON dbo.TR_Main.PatientID = dbo.CM_CPI.PatientID AND dbo.AB_Abstract.ChartNumber = dbo.CM_CPI.ChartNumber
				WHERE (dbo.AB_Abstract.ChartNumber = ''' + @SearchString + ''' OR dbo.AB_Abstract.ChartNumber = ''' + @SearchString2 +''')
				AND dbo.AB_Abstract.IsDeleted = 2
				AND dbo.TR_Main.IsDeleted = 2
				AND (ISNULL(AB_Abstract.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(AB_Abstract.HospitalID, 0) end) '
				+ @ExtraSearch + '
				ORDER BY [Chart #] Desc, DischargeDate DESC'	

		EXECUTE(@SQL)
		SET ROWCOUNT 0
		RETURN 0
	END
		
	ELSE IF @FieldName = 'DischargeDate' 
	BEGIN	
		SET @SQL = 
			'SELECT dbo.TR_Main.TranscriptionID AS [ ],
			(select UserDescription from LU_CareType where Code = TR_Main.CareType) as [Visit Type],
			CONVERT(VARCHAR(10), dbo.AB_Abstract.DischargeDate, 111) AS [Disch Date],   
			REPLACE(SPACE(10-LEN(dbo.AB_Abstract.ChartNumber)) + dbo.AB_Abstract.ChartNumber, '' '', ''0'')  AS [Chart #],
			ISNULL(dbo.AB_Abstract.LastName, '''') + '', '' + ISNULL(dbo.AB_Abstract.FirstName, '''') + '' '' + ISNULL(dbo.AB_Abstract.MiddleName, '''') AS [Full Name], 
			(SELECT DisplayCode FROM LU_TranscriptDocument WHERE Code = dbo.TR_Main.DocumentType) AS [Doc Type], 
			dbo.TR_Main.DocumentName AS [Doc Name]
			FROM dbo.AB_Abstract INNER JOIN dbo.TR_Main ON dbo.AB_Abstract.AbstractID = dbo.TR_Main.AbstractID INNER JOIN dbo.CM_CPI ON dbo.TR_Main.PatientID = dbo.CM_CPI.PatientID AND dbo.AB_Abstract.ChartNumber = dbo.CM_CPI.ChartNumber
			WHERE  ' + @Where + ' 
			AND dbo.AB_Abstract.IsDeleted = 2
			AND dbo.TR_Main.IsDeleted = 2
			AND (ISNULL(AB_Abstract.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(AB_Abstract.HospitalID, 0) end) '
			+ @ExtraSearch + '
			ORDER BY DischargeDate'
		EXECUTE(@SQL)
		SET ROWCOUNT 0
		RETURN 0
	END
	
	ELSE IF @FieldName = 'LastName' AND @NameSplit = 0
	BEGIN
		SET @SearchString = REPLACE(@SearchString, '''', '''''')
		SET @SQL = 
			'SELECT dbo.TR_Main.TranscriptionID AS [ ], 
			(select UserDescription from LU_CareType where Code = TR_Main.CareType) as [Visit Type],
			ISNULL(dbo.AB_Abstract.LastName, '''') + '', '' + ISNULL(dbo.AB_Abstract.FirstName, '''') + '' '' + ISNULL(dbo.AB_Abstract.MiddleName, '''') AS [Full Name], 
		    	REPLACE(SPACE(10-LEN(dbo.AB_Abstract.ChartNumber)) + dbo.AB_Abstract.ChartNumber, '' '', ''0'')  AS [Chart #],
		    	CONVERT(VARCHAR(10), dbo.AB_Abstract.DischargeDate, 111) AS [Disch Date],  
			(SELECT DisplayCode FROM LU_TranscriptDocument WHERE Code = dbo.TR_Main.DocumentType) AS [Doc Type], 
		             dbo.TR_Main.DocumentName AS [Doc Name]
			FROM dbo.AB_Abstract INNER JOIN dbo.TR_Main ON dbo.AB_Abstract.AbstractID = dbo.TR_Main.AbstractID INNER JOIN dbo.CM_CPI ON dbo.TR_Main.PatientID = dbo.CM_CPI.PatientID AND dbo.AB_Abstract.ChartNumber = dbo.CM_CPI.ChartNumber
			WHERE dbo.AB_Abstract.LastName Like ''' + @SearchString + '%'' 
			AND dbo.AB_Abstract.IsDeleted = 2
			AND dbo.TR_Main.IsDeleted = 2
			AND (ISNULL(AB_Abstract.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(AB_Abstract.HospitalID, 0) end) '
			+ @ExtraSearch + '
			ORDER BY dbo.AB_Abstract.LastName DESC, dbo.AB_Abstract.FirstName, AdmitDate DESC'
		EXECUTE(@SQL)
		SET ROWCOUNT 0	
		RETURN 0
	END
	
	ELSE IF @FieldName = 'LastName' AND @NameSplit > 0
	BEGIN
		SET @SearchString = REPLACE(@SearchString, '''', '''''')
		SET @SQL = 
			'SELECT dbo.TR_Main.TranscriptionID AS [ ], 
			(select UserDescription from LU_CareType where Code = TR_Main.CareType) as [Visit Type],
			ISNULL(dbo.AB_Abstract.LastName, '''') + '', '' + ISNULL(dbo.AB_Abstract.FirstName, '''') + '' '' + ISNULL(dbo.AB_Abstract.MiddleName, '''') AS [Full Name], 
		    	REPLACE(SPACE(10-LEN(dbo.AB_Abstract.ChartNumber)) + dbo.AB_Abstract.ChartNumber, '' '', ''0'')  AS [Chart #],
		    	CONVERT(VARCHAR(10), dbo.AB_Abstract.DischargeDate, 111) AS [Disch Date],  
			(SELECT DisplayCode FROM LU_TranscriptDocument WHERE Code = dbo.TR_Main.DocumentType) AS [Doc Type], 
		             dbo.TR_Main.DocumentName AS [Doc Name]
			FROM dbo.AB_Abstract INNER JOIN dbo.TR_Main ON dbo.AB_Abstract.AbstractID = dbo.TR_Main.AbstractID INNER JOIN dbo.CM_CPI ON dbo.TR_Main.PatientID = dbo.CM_CPI.PatientID AND dbo.AB_Abstract.ChartNumber = dbo.CM_CPI.ChartNumber
			WHERE dbo.AB_Abstract.LastName Like ''' + RTRIM(LTRIM(LEFT(@SearchString, @NameSplit-1))) + '%'' 
			AND dbo.AB_Abstract.FirstName Like ''' + RTRIM(LTRIM(STUFF(@SearchString, 1, @NameSplit, ''))) + '%'' 
			AND dbo.AB_Abstract.IsDeleted = 2
			AND dbo.TR_Main.IsDeleted = 2
			AND (ISNULL(AB_Abstract.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(AB_Abstract.HospitalID, 0) end) '
			+ @ExtraSearch + '
			ORDER BY dbo.AB_Abstract.LastName DESC, dbo.AB_Abstract.FirstName, AdmitDate DESC'
		EXECUTE(@SQL)
		SET ROWCOUNT 0
		RETURN 0
	END
END

ELSE 
BEGIN
	Set @FieldName = @DBTableName + '.' + @FieldName
	SET @FieldDesc = (CASE @DataType 
			WHEN 11 THEN 'CONVERT(VARCHAR(10), ' + @FieldName + ', 111), ' 
			WHEN 12 THEN 'CONVERT(VARCHAR(10), ' + @FieldName + ', 111), ' --PR-01739
			WHEN 13 THEN 'CONVERT(VARCHAR(10), ' + @FieldName + ', 111), ' --PR-01739
			WHEN 15 THEN 'CONVERT(VARCHAR(5), ' + @FieldName + ', 14), '  
			ELSE '' + @FieldName +  ' AS [' + @FieldDesc + '] , '  END)
	SET @select = 
		'SELECT dbo.TR_Main.TranscriptionID AS [ ], 
		(select UserDescription from LU_CareType where Code = TR_Main.CareType) as [Visit Type], ' +
		@FieldDesc + 				
		'REPLACE(SPACE(10-LEN(dbo.AB_Abstract.ChartNumber)) + dbo.AB_Abstract.ChartNumber, '' '', ''0'')  AS [Chart #],
		ISNULL(dbo.AB_Abstract.LastName, '''') + '', '' + ISNULL(dbo.AB_Abstract.FirstName, '''') + '' '' + ISNULL(dbo.AB_Abstract.MiddleName, '''') AS [Full Name], 
		CONVERT(VARCHAR(10), dbo.AB_Abstract.DischargeDate, 111) AS [Disch Date],  
		(SELECT DisplayCode FROM LU_TranscriptDocument WHERE Code = dbo.TR_Main.DocumentType) AS [Doc Type], 
		dbo.TR_Main.DocumentName AS [Doc Name]
		FROM dbo.AB_Abstract INNER JOIN dbo.TR_Main ON dbo.AB_Abstract.AbstractID = dbo.TR_Main.AbstractID INNER JOIN dbo.CM_CPI ON dbo.TR_Main.PatientID = dbo.CM_CPI.PatientID AND dbo.AB_Abstract.ChartNumber = dbo.CM_CPI.ChartNumber '

	-- determine the Where Clause base on datatype
	IF (@DataType = 15) -- if it is a time
	BEGIN
		SET @SearchString = (CASE CHARINDEX(':', @SearchString) WHEN 1 THEN '00' + @SearchString WHEN 2 THEN '0' + @SearchString ELSE @SearchString END)
		SET @SearchString = REPLACE(@SearchString, ':', '')
		SET @SearchString = (CASE LEN(@SearchString)  WHEN 0 THEN '00:00' WHEN 1 THEN '00:0' + @SearchString WHEN 2 THEN '00:' + @SearchString WHEN 3 THEN '0' + LEFT(@SearchString, 1) + ':' + RIGHT(@SearchString, 2)  WHEN 4 THEN LEFT(@SearchString, 2) + ':' + RIGHT(@SearchString, 2) ELSE LEFT(@SearchString, 2) + ':' + SUBSTRING(@SearchString, 2, 2) END)
	        --if (isdate(@SearchString) = 0) Set @SearchString = '23:59:59' --PR-03191
	        --set @where = @FieldName + ' >= ''1899-12-30 ' + @SearchString + ''' ' --PR-03191
		if (isdate(@SearchString) = 0) Set @SearchString = '23:59' --PR-03191
		set @where = 'convert(NVarChar(5), ' + @FieldName + ', 14) >= ''' + @SearchString + ''' ' --PR-03191
	END
	ELSE if isnull(@where, '') = ''-- all other cases
	BEGIN
		SELECT @FieldDT = Data_Type FROM information_schema.columns WHERE Column_Name = @FieldName and Table_Name like 'TR_%'
		IF(@FieldDT = 'int') 
		BEGIN
			IF (@SearchString = '') SET @SearchString = '0'
				SET @where = @FieldName + ' >= ' + @SearchString + ' '
		END
		ELSE SET @where = @FieldName + ' LIKE ''%' + @SearchString + '%'' '
	END

	SET @where =  'WHERE dbo.AB_Abstract.IsDeleted = 2 AND dbo.TR_Main.IsDeleted = 2 AND (ISNULL(AB_Abstract.HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else ISNULL(AB_Abstract.HospitalID, 0) end) AND ' + @where + @ExtraSearch
	SET @order = 'ORDER BY ' + @FieldName + ', dbo.AB_Abstract.DischargeDate DESC'
		
	SELECT @sql = @select + @where + @order
	EXECUTE(@SQL)
	SET ROWCOUNT 0
	RETURN 0
END





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Called by the User Profile Search Form w/ Param to load User
-- And the User Prof/Ctrl File Mods w/out Param to load entire list.
CREATE       PROCEDURE [F_SearchUser]
	@SearchString as VarChar(50),
	@FilterRole as INT,
	@SearchDate as datetime,
	@HospID as int = 0
AS 

--NP-00025 - 				(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(U.HospitalID, 0)) as [Hosp ID],
--NP-00025 -				(select R.DisplayCode from U_Users R where R.Code = U.RoleID) as [Role ID], 
IF @FilterRole = 0 
	BEGIN
	IF @SearchString = '' 
		BEGIN
		SELECT Code As [ ], 
				(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(U.HospitalID, 0)) as [Hosp ID],
				(select R.DisplayCode from U_Users R where R.Code = U.RoleID) as [Role ID],
				DisplayCode as [Coder #], 
				UserName As [User Name], 
				ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [Full Name]
		FROM dbo.U_Users U
		WHERE Code > 2 and code not in (66666, 77777, 88888, 99999) --PR - 03603
		AND ValidTo >= @SearchDate
		AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end) 
		ORDER BY [Hosp ID], [Role ID], [User Name]
		END
	ELSE
		BEGIN
		SELECT Code As [ ], 
				(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(U.HospitalID, 0)) as [Hosp ID],
				(select R.DisplayCode from U_Users R where R.Code = U.RoleID) as [Role ID],
				DisplayCode as [Coder Number], 
				UserName As [User Name], 
				ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [Full Name]
		FROM dbo.U_Users U
		WHERE Code > 2 AND [UserName] like @SearchString + '%' and code not in (66666, 77777, 88888, 99999) --PR - 03603		
		AND ValidTo >= @SearchDate 
		AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end) 
		ORDER BY [Hosp ID], [Role ID], [UserName]
		END
	END
ELSE
	BEGIN
	IF @SearchString = '' 
		BEGIN
		SELECT Code As [ ], 
				(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(U.HospitalID, 0)) as [Hosp ID],
				(select R.DisplayCode from U_Users R where R.Code = U.RoleID) as [Role ID],
				DisplayCode as [Coder #], 
				UserName As [User Name], 
				ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [Full Name]
		FROM dbo.U_Users U
		WHERE Code > 2 AND ISNULL(RoleID, 0) <= 0 and code not in (66666, 77777, 88888, 99999) --PR - 03603
		AND ValidTo >= @SearchDate
		AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end) 
		ORDER BY [Hosp ID], [Role ID], [User Name]
		END
	ELSE
		BEGIN
		SELECT Code As [ ], 
				(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(U.HospitalID, 0)) as [Hosp ID],
				(select R.DisplayCode from U_Users R where R.Code = U.RoleID) as [Role ID],
				DisplayCode as [Coder Number], 
				UserName As [User Name], 
				ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [Full Name]
		FROM dbo.U_Users U
		WHERE Code > 2 AND ISNULL(RoleID, 0) <= 0 AND [UserName] like @SearchString + '%' and code not in (66666, 77777, 88888, 99999) --PR - 03603
		AND ValidTo >= @SearchDate
		AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end) 
		ORDER BY [Hosp ID], [Role ID], [UserName]
		END
	END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Called by the User Profile New Form w/ Param to load User List that will base the Ctrl File on.
CREATE       PROCEDURE [F_SearchUserCtrl]
	@SearchString as VarChar(50),
	@HospID as int = 0
AS 

--NP-00025 - 				(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(U_Users.HospitalID, 0)) as [Hosp ID],

IF @SearchString = '' 
	BEGIN
		SELECT Code As [ ], 
				(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(U_Users.HospitalID, 0)) as [Hosp ID],
				DisplayCode as [Coder #], 
				UserName As [User Name], 
				ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [Full Name]
		FROM dbo.U_Users 
		WHERE ISNULL(RoleID, 0) <= 0 and code not in (66666, 77777, 88888, 99999) --PR - 03603
		AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end) 
		ORDER BY [User Name]
	END
ELSE
	BEGIN
		SELECT Code As [ ], 
				(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(U_Users.HospitalID, 0)) as [Hosp ID],
				DisplayCode as [Coder Number], 
				UserName As [User Name], 
				ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [Full Name]
		FROM dbo.U_Users 
		WHERE ISNULL(RoleID, 0) <= 0 AND [UserName] like @SearchString + '%'
		AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end) 
        and code not in (66666, 77777, 88888, 99999) --PR - 03603
		ORDER BY [UserName]
	END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Called by the Abstract Search Form
CREATE PROCEDURE [F_SearchVisit]
	@FKey int,
	@SearchString varchar(50) = '',
	@SearchString2 varchar(50) = '',
	@UserID int = 1,  -- This is actually the RoleID
	@Exact int = 0,
	@LogID int = 0,	--This is the UserID that Logged In
	@HospID	varchar(100) = '0',
	@ExtraSearch 	[varchar](1000) = ''
AS 
set nocount on

declare @AppID int
declare @sql nvarchar(2500)
declare @select nvarchar(1500)
declare @from nvarchar(1000)
declare @where nvarchar(1000)
declare @order nvarchar(100)

declare @DataType int
declare @LookupTable nvarchar(50)
declare @SearchField nvarchar(50)
declare @NameSplit int
declare @FieldDesc nvarchar(150)
declare @Temp datetime
declare @DBTableName nvarchar(50)
declare @FieldDT nvarchar(20)

--Chart Audits, Prefixs, VIP and Top X parameters
declare @SearchPrefix as nvarchar(50)
declare @SearchPrefix_Org as NVarChar(100) --PR - 05450
declare @ShowVip as nvarchar(1)
declare @TopX as nvarchar(3)
declare @SearchAudit as int
declare @sqlTopX as nvarchar(20)
declare @results as nvarchar(100)

--13507: Moved to top	
Set @SearchString = replace(@SearchString, '''', '''''')
Set @SearchString2 = replace(@SearchString2, '''', '''''')

set @AppID = 3

select 
    @DataType = DataType, 
    @LookupTable = LookUpTable, 
    @FieldDesc = Header_User 
from U_UsersFields 
where AppID = @AppID 
and FieldID = @FKey 
and UserID = @UserID

select @SearchField = SystemName 
from U_Fields 
where FieldID = @FKey

set @FieldDesc = replace(@FieldDesc, '[', '')
set @FieldDesc = replace(@FieldDesc, ']', '')

select top 1 @DBTableName = table_name 
from information_schema.columns 
where Column_Name = @SearchField 
and Table_Name like 'AB_%' 
order by Table_Name

--Audit values searched on
insert into AU_Search Values (@AppID, @SearchString, @LogID, GetDate(), @FieldDesc)

select @SearchPrefix = isnull(SearchChartPrefix, ''), @ShowVip = isnull(ShowVip, 0) 
from U_Users 
where Code = @UserID
set @SearchPrefix_Org = @SearchPrefix   --PR - 05450
if @SearchPrefix <> ''
	set @SearchPrefix = ' and Chartnumber like ''' + @SearchPrefix + '%'' '

if @HospID = '0'
	select top 1 @TopX = isnull(TopSearch, '999'), @SearchAudit = EnableSearchAudit  from H_HospitalProfile 
else	
	select top 1 @TopX = isnull(TopSearch, '999'), @SearchAudit = EnableSearchAudit  from H_HospitalProfile where isnull(Code, 0) = @HospID

set @sqlTopX = 'select top ' + @TopX + ' ' 
set @NameSplit = charindex(',', @SearchString) 


set @results = '##SearchResults' + replace(convert(nvarchar(100), getdate(), 114), ':', '')
-- determine the where Clause base on datatype

-- if it is a date
if (@DataType in (11, 12, 13)) begin  --PR-01739
	if right(@SearchString, 5) = '00/00' 
        	set @where = '(' + @SearchField + ' >= convert(DateTime, ''' + left(@SearchString, 5) + '01/01'') and ' + @SearchField + ' <= convert(DateTime, ''' + left(@SearchString, 5) + '12/31'')) '

	else if right(@SearchString, 2) = '00' 
        	set @where = '(' + @SearchField + ' >= convert(DateTime, ''' + left(@SearchString, 8) + '01'') and ' + @SearchField + ' < dateadd(M, 1, convert(DateTime, ''' + left(@SearchString, 8) + '01''))) '

    else if (isdate(@SearchString) = 0) 
		set @SearchString = '1950/01/01'

	if isnull(@where, '') = ''
        set @where = @SearchField + ' = convert(DateTime, ''' + @SearchString + ''') '
end 

--EN-00043
--9031
declare @OrdT as varchar(400)
set @OrdT = ''

if @FKey = 45006 -- TERMINAL DIGIT SORT
    begin
-- 	declare @TDigit as varchar(10)
-- 	declare @TDigitR as varchar(10)
-- 	declare @TDigitH as varchar(10)
-- 
-- 	select @TDigitR = TerminalDigit from H_RegionProfile
-- 	if @HospID = '0' 
-- 		select top 1 @TDigitH = TerminalDigit from H_HospitalProfile 
-- 	else
-- 		select top 1 @TDigitH = TerminalDigit from H_HospitalProfile where HospitalID = @HospID
-- 	
-- 	set @TDigit = @TDigitR
-- 	if len(@TDigitH) <> 0 and isnull(@TDigitH, '0') <> '0' set @TDigit = @TDigitH
-- 	--set @TDigit = '926315'
-- 	
-- 	declare @Pos1 as varchar(1)
-- 	declare @Len1 as varchar(1)
-- 	declare @Pos2 as varchar(1)
-- 	declare @Len2 as varchar(1)
-- 	declare @Pos3 as varchar(1)
-- 	declare @Len3 as varchar(1)
-- 	declare @Pos4 as varchar(1)
-- 	declare @Len4 as varchar(1)
-- 	declare @Pos5 as varchar(1)
-- 	declare @Len5 as varchar(1)
-- 
-- 	if isnumeric(substring(@TDigit, 1, 1)) = 1 
-- 		set @Pos1 = substring(@TDigit, 1, 1)
-- 	if isnumeric(substring(@TDigit, 2, 1)) = 1 
-- 		set @Len1 = substring(@TDigit, 2, 1)
-- 	if isnumeric(substring(@TDigit, 3, 1)) = 1 
-- 		set @Pos2 = substring(@TDigit, 3, 1)
-- 	if isnumeric(substring(@TDigit, 4, 1)) = 1 
-- 		set @Len2 = substring(@TDigit, 4, 1)
-- 	if isnumeric(substring(@TDigit, 5, 1)) = 1 
-- 		set @Pos3 = substring(@TDigit, 5, 1)
-- 	if isnumeric(substring(@TDigit, 6, 1)) = 1 
-- 		set @Len3 = substring(@TDigit, 6, 1)
-- 	if isnumeric(substring(@TDigit, 7, 1)) = 1 
-- 		set @Pos4 = substring(@TDigit, 7, 1)
-- 	if isnumeric(substring(@TDigit, 8, 1)) = 1 
-- 		set @Len4 = substring(@TDigit, 8, 1)
-- 	if isnumeric(substring(@TDigit, 9, 1)) = 1 
-- 		set @Pos5 = substring(@TDigit, 9, 1)
-- 	if isnumeric(substring(@TDigit, 10, 1)) = 1 
-- 		set @Len5 = substring(@TDigit, 10, 1)
-- 
-- 	if len(@Pos1) <> 0 and len(@Len1) <> 0
-- 		set @OrdT = ' substring(replace(space(10-len([Chart #])) + [Chart #], '' '', ''0''), ' + @Pos1 + ', ' + @Len1 + '), '
-- 		
-- 	if len(@Pos2) <> 0 and len(@Len2) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len([Chart #])) + [Chart #], '' '', ''0''), ' + @Pos2 + ', ' + @Len2 + '), '
-- 
-- 	if len(@Pos3) <> 0 and len(@Len3) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len([Chart #])) + [Chart #], '' '', ''0''), ' + @Pos3 + ', ' + @Len3 + '), '
-- 
-- 	if len(@Pos4) <> 0 and len(@Len4) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len([Chart #])) + [Chart #], '' '', ''0''), ' + @Pos4 + ', ' + @Len4 + '), '
-- 
-- 	if len(@Pos5) <> 0 and len(@Len5) <> 0
-- 		set @OrdT = @OrdT + ' substring(replace(space(10-len([Chart #])) + [Chart #], '' '', ''0''), ' + @Pos5 + ', ' + @Len5 + '), '
-- 
-- 	if len(@OrdT) <> 0 
-- 		set @OrdT = left(@OrdT, len(@OrdT) - 1)
-- 	
-- 	set @sql = N'' + 
--     		@sqlTopX + ' [ ] = UniversalID, ' + 
--         		'[Chart #]     = right(''0000000000'' + ChartNumber, 10), ' + 
-- 		        '[Encounter #] = EncounterNumber, ' + 
-- 		        '[Full Name]   = isnull(LastName, '''') + '', '' + isnull(FirstName, '''') + '' '' + isnull(MiddleName, ''''), ' + 
-- 		        '[Admit Date]  = convert(varchar(10), AdmitDate, 111), ' + 
-- 		        '[Admit Time]  = convert(varchar(5), AdmitTime, 14),  ' + 
-- 		        'case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased], ' +
--			'dbo.LU_AppIDs.UserDescription as Module ' + 
--     		'into ' + @results + ' ' + 
--     		'from dbo.AB_Main LEFT OUTER JOIN dbo.LU_AppIDs ON dbo.AB_Main.AppID = dbo.LU_AppIDs.Code LEFT OUTER JOIN
--      		dbo.LU_YesBlank ON dbo.AB_Main.DeathIndicator = dbo.LU_YesBlank.Code ' + 
--     		'where (ChartNumber like ''' + @SearchString + '%'' or ChartNumber like ''' + @SearchString2 +'%'') ' + 
--     		'and IsDeleted = 2' + @SearchPrefix + ' ' + 
--     		'and (isnull(AB_Main.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(AB_Main.HospitalID, 0) end) ' 
-- 	+  @ExtraSearch 
-- 
-- 	if len(@OrdT) <> 0 
-- 		set @OrdT = ' order by ' + @OrdT


	set @sql = N'' + 
    		@sqlTopX + ' [ ] = UniversalID, ' + 			
    			'[SearchItem#]  = (select TerminalChart from CM_Terminal where PatientID = AB_Main.PatientID), ' +
	    		'[Hosp ID] = (select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Main.HospitalID, 0)), ' + 			
        		'[Chart #]     = right(''0000000000'' + ChartNumber, 10), ' + 
		        '[Encounter #] = EncounterNumber, ' + 
		        '[Full Name]   = isnull(LastName, '''') + '', '' + isnull(FirstName, '''') + '' '' + isnull(MiddleName, ''''), ' + 
		        '[Admit Date]  = convert(varchar(10), AdmitDate, 111), ' + 
		        '[Admit Time]  = convert(varchar(5), AdmitTime, 14),  ' + 
		        'case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased], ' +
			'dbo.LU_AppIDs.UserDescription as Module ' + 
    		'into ' + @results + ' ' + 
    		'from dbo.AB_Main LEFT OUTER JOIN dbo.LU_AppIDs ON dbo.AB_Main.AppID = dbo.LU_AppIDs.Code LEFT OUTER JOIN
     		dbo.LU_YesBlank ON dbo.AB_Main.DeathIndicator = dbo.LU_YesBlank.Code ' + 
		'where AB_Main.PatientID in (select PatientID from CM_Terminal where TerminalChart Like ''' + @SearchString + '%'' or MaskTerminal Like ''' + @SearchString + '%'') ' + 
    		'and IsDeleted = 2' + @SearchPrefix + ' ' + 
    		'and (isnull(AB_Main.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(AB_Main.HospitalID, 0) end) ' 
	+  @ExtraSearch 
	
	set @OrdT = ' order by [Hosp ID], [Terminal #] ' -- (select TerminalChart from CM_Terminal where PatientID = AB_Main.PatientID) '
	--set @sql = @sql + @order
	--print @sql 
        --exec sp_executesql @sql 
        set @FieldDesc = 'Terminal #'
    end

else if @SearchField = 'EncounterNumber' begin
    set @sql = N'' + 
        @sqlTopX + ' [ ] = UniversalID, ' +
            '[SearchItem#] = EncounterNumber, ' +
	        '[Hosp ID] = (select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Main.HospitalID, 0)), ' + 			
            '[Chart #]     = right(''0000000000'' + ChartNumber,  10), ' +
            '[Encounter #] = EncounterNumber, ' +
            '[Full Name]   = isnull(LastName, '''') + '', '' + isnull(FirstName, '''') + '' '' + isnull(MiddleName, ''''), ' +
            '[Admit Date]  = convert(varchar(10), AdmitDate, 111), ' +
            '[Admit Time]  = convert(varchar(5), AdmitTime, 14),  ' + 
            'case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased], ' + 
	        'dbo.LU_AppIDs.UserDescription as Module ' + 
            'into ' + @results + ' ' + 
            'from dbo.AB_Main LEFT OUTER JOIN dbo.LU_AppIDs ON dbo.AB_Main.AppID = dbo.LU_AppIDs.Code LEFT OUTER JOIN
             dbo.LU_YesBlank ON dbo.AB_Main.DeathIndicator = dbo.LU_YesBlank.Code ' + 
        'where EncounterNumber like ''' + @SearchString + '%'' ' +
        'and IsDeleted = 2' + @SearchPrefix + ' ' + 
        'and (isnull(AB_Main.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(AB_Main.HospitalID, 0) end) ' + 
        @ExtraSearch + 
        'order by [Hosp ID], EncounterNumber desc ' 
end

else if @SearchField = 'ChartNumber' begin
    --PR - 05450
    if len(@SearchPrefix_Org) > 0 and len(isnull(@SearchString, '')) > 0
    begin
        if charindex(@SearchPrefix_Org, @SearchString) <> 1
        begin
            set @SearchString = @SearchPrefix_Org + @SearchString
        end
    end
	if @Exact = 0 
		set @sql = N'' + 
            @sqlTopX + ' [ ] = UniversalID, ' + 
                '[SearchItem#] = ChartNumber, ' + 
    		    '[Hosp ID] = (select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Main.HospitalID, 0)), ' + 			
                '[Chart #]     = right(''0000000000'' + ChartNumber, 10), ' + 
                '[Encounter #] = EncounterNumber, ' + 
                '[Full Name]   = isnull(LastName, '''') + '', '' + isnull(FirstName, '''') + '' '' + isnull(MiddleName, ''''), ' + 
                '[Admit Date]  = convert(varchar(10), AdmitDate, 111), ' + 
                '[Admit Time]  = convert(varchar(5), AdmitTime, 14),  ' + 
                'case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased], ' +
		        'dbo.LU_AppIDs.UserDescription as Module ' + 
            'into ' + @results + ' ' + 
            'from dbo.AB_Main LEFT OUTER JOIN dbo.LU_AppIDs ON dbo.AB_Main.AppID = dbo.LU_AppIDs.Code LEFT OUTER JOIN
             dbo.LU_YesBlank ON dbo.AB_Main.DeathIndicator = dbo.LU_YesBlank.Code ' + 
            'where (ChartNumber like ''' + @SearchString + '%'' or ChartNumber like ''' + @SearchString2 +'%'') ' + 
            'and IsDeleted = 2' + @SearchPrefix + ' ' + 
            'and (isnull(AB_Main.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(AB_Main.HospitalID, 0) end) ' + 
           @ExtraSearch + 
            'order by [Hosp ID], [Chart #] desc, AdmitDate desc'
	else
		set @sql = 
            @sqlTopX + ' [ ] = UniversalID, ' +
                '[SearchItem#] = ChartNumber, ' + 
        		'[Hosp ID] = (select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Main.HospitalID, 0)), ' + 			
                '[Chart #]     = right(''0000000000'' + ChartNumber, 10), ' + 
                '[Encounter #] = EncounterNumber, ' +
                '[Full Name]   = isnull(LastName, '''') + '', '' + isnull(FirstName, '''') + '' '' + isnull(MiddleName, ''''), ' +
                '[Admit Date]  = convert(varchar(10), AdmitDate, 111), ' +
                '[Admit Time]  = convert(varchar(5), AdmitTime, 14), ' +
                'case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased], ' +
	        	'dbo.LU_AppIDs.UserDescription as Module ' + 
            'into ' + @results + ' ' + 
            'from dbo.AB_Main LEFT OUTER JOIN dbo.LU_AppIDs ON dbo.AB_Main.AppID = dbo.LU_AppIDs.Code LEFT OUTER JOIN
             dbo.LU_YesBlank ON dbo.AB_Main.DeathIndicator = dbo.LU_YesBlank.Code ' + 
            'where (ChartNumber = ''' + @SearchString + ''' or ChartNumber = ''' + @SearchString2 + ''') ' +
            'and IsDeleted = 2' + @SearchPrefix + ' ' +
            'and (isnull(AB_Main.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(AB_Main.HospitalID, 0) end) ' +
           @ExtraSearch + 
            'order by [Hosp ID], [Chart #] desc, AdmitDate desc'
end
else if @SearchField = 'AdmitDate' begin
    set @sql = N'' + 
        @sqlTopX + ' [ ] = UniversalID, ' + 
            '[SearchItem#]  = convert(varchar(10), AdmitDate, 111), ' +
    	    '[Hosp ID] = (select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Main.HospitalID, 0)), ' + 			
            '[Chart #]     = right(''0000000000'' + ChartNumber, 10), ' + 
            '[Encounter #] = EncounterNumber, ' +
            '[Full Name]   = isnull(LastName, '''') + '', '' + isnull(FirstName, '''') + '' '' + isnull(MiddleName, ''''), ' +
            '[Admit Date]  = convert(varchar(10), AdmitDate, 111), ' +
            '[Admit Time]  = convert(varchar(5), AdmitTime, 14), ' +
            'case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased], ' +
    		'dbo.LU_AppIDs.UserDescription as Module ' + 
            'into ' + @results + ' ' + 
            'from dbo.AB_Main LEFT OUTER JOIN dbo.LU_AppIDs ON dbo.AB_Main.AppID = dbo.LU_AppIDs.Code LEFT OUTER JOIN
             dbo.LU_YesBlank ON dbo.AB_Main.DeathIndicator = dbo.LU_YesBlank.Code ' + 
        'where ' + @where + ' ' +
        'and IsDeleted = 2' + @SearchPrefix + ' ' +
        'and (isnull(AB_Main.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(AB_Main.HospitalID, 0) end) ' +
        @ExtraSearch + 
        'order by [Hosp ID], AdmitDate'
end
else if @SearchField = 'LastName' and @NameSplit = 0 begin
	--13507: Moved to top	
	--set @SearchString = replace(@SearchString, '''', '''''')
    set @sql = N'' + 
        @sqlTopX + ' [ ] = UniversalID, ' + 
            '[SearchItem#] = LastName, ' +
    	    '[Hosp ID] = (select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Main.HospitalID, 0)), ' + 			
            '[Chart #]     = right(''0000000000'' + ChartNumber, 10), ' + 
            '[Encounter #] = EncounterNumber, ' + 
            '[Full Name]   = isnull(LastName, '''') + '', '' + isnull(FirstName, '''') + '' '' + isnull(MiddleName, ''''), ' + 
            '[Admit Date]  = convert(varchar(10), AdmitDate, 111), ' + 
            '[Admit Time]  = convert(varchar(5), AdmitTime, 14), ' +
            'case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased], ' +
	        'dbo.LU_AppIDs.UserDescription as Module ' + 
            'into ' + @results + ' ' + 
            'from dbo.AB_Main LEFT OUTER JOIN dbo.LU_AppIDs ON dbo.AB_Main.AppID = dbo.LU_AppIDs.Code LEFT OUTER JOIN
             dbo.LU_YesBlank ON dbo.AB_Main.DeathIndicator = dbo.LU_YesBlank.Code ' + 
        'where LastName like ''' + @SearchString + '%'' ' + 
        'and IsDeleted = 2' + @SearchPrefix + ' ' + 
        'and (isnull(AB_Main.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(AB_Main.HospitalID, 0) end) ' + 
        @ExtraSearch + 
        'order by [Hosp ID], LastName desc, FirstName, AdmitDate desc'
end
else if @SearchField = 'LastName' and @NameSplit > 0 begin
	--13507: Moved to top	
	--set @SearchString = replace(@SearchString, '''', '''''')
    set @sql = N'' + 
        @sqlTopX + ' [ ] = UniversalID, ' + 
            '[SearchItem#] = LastName, ' +
	        '[Hosp ID] = (select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Main.HospitalID, 0)), ' + 			
            '[Chart #]     = right(''0000000000'' + ChartNumber, 10), ' + 
            '[Encounter #] = EncounterNumber, ' +
            '[Full Name]   = isnull(LastName, '''') + '', '' + isnull(FirstName, '''') + '' '' + isnull(MiddleName, ''''), ' +
            '[Admit Date]  = convert(varchar(10), AdmitDate, 111), ' +
            '[Admit Time]  = convert(varchar(5), AdmitTime, 14), ' +
            'case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased], ' +
    		'dbo.LU_AppIDs.UserDescription as Module ' + 
            'into ' + @results + ' ' + 
            'from dbo.AB_Main LEFT OUTER JOIN dbo.LU_AppIDs ON dbo.AB_Main.AppID = dbo.LU_AppIDs.Code LEFT OUTER JOIN
             dbo.LU_YesBlank ON dbo.AB_Main.DeathIndicator = dbo.LU_YesBlank.Code ' + 
         'where LastName like ''' + rtrim(ltrim(Left(@SearchString, @NameSplit-1))) + '%'' ' +
        'and FirstName like ''' + rtrim(ltrim(Stuff(@SearchString, 1, @NameSplit, ''))) + '%'' ' +
        'and IsDeleted = 2' + @SearchPrefix + ' ' +
        'and (isnull(AB_Main.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(AB_Main.HospitalID, 0) end) ' +
        @ExtraSearch + 
        'order by [Hosp ID], LastName desc, FirstName, AdmitDate desc'
end
else begin
    Declare @SearchItem varchar(100) --PR - 04434

    set @SearchItem = '[SearchItem#] = ' + (case @DataType
        when 11 then 'convert(varchar(10), ' + @SearchField + ', 111), '
        when 12 then 'convert(varchar(10), ' + @SearchField + ', 111), ' --PR-01739
        when 13 then 'convert(varchar(10), ' + @SearchField + ', 111), ' --PR-01739
        when 15 then 'convert(varchar(5), ' + @SearchField + ', 14), ' 
        else         '' + @SearchField + ', '
        end)

    set @select = N'' + 
        @sqlTopX + ' [ ] = UniversalID, ' + 
            @SearchItem +
	        '[Hosp ID] = (select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Main.HospitalID, 0)), ' + 			
        --PR - 04434
        --PR - 04420
        --(case when @SearchField = 'AdmitTime' then '' else @FieldDesc end) +
            '[Chart #]     = replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0''), ' +
            '[Encounter #] = EncounterNumber, ' +
            '[Full Name]   = isnull(LastName, '''') + '', '' + isnull(FirstName, '''') + '' '' + isnull(MiddleName, ''''), ' +
            '[Admit Date]  = convert(varchar(10), AdmitDate, 111), ' +
            '[Admit Time]  = convert(varchar(5), AdmitTime, 14), ' +
             'case when DeathIndicator = 1 then ''Y'' else ''N'' end as [Deceased], ' +
		    'dbo.LU_AppIDs.UserDescription as Module ' 

    set @from = N'' + 
        'into ' + @results + ' ' + 
            'from dbo.AB_Main LEFT OUTER JOIN dbo.LU_AppIDs ON dbo.AB_Main.AppID = dbo.LU_AppIDs.Code LEFT OUTER JOIN
             dbo.LU_YesBlank ON dbo.AB_Main.DeathIndicator = dbo.LU_YesBlank.Code '

     -- if it is a time
    if (@DataType = 15) begin 

        set @SearchString = (case charindex(':', @SearchString)
            when 1 then '00' + @SearchString
            when 2 then '0' + @SearchString
            else @SearchString
        end)

        set @SearchString = replace(@SearchString, ':', '')

        set @SearchString = (case len(@SearchString) 
            when 0 then '00:00'
            when 1 then '00:0' + @SearchString 
            when 2 then '00:' + @SearchString
            when 3 then '0' + left(@SearchString, 1) + ':' + right(@SearchString, 2) 
            when 4 then left(@SearchString, 2) + ':' + right(@SearchString, 2)
            else left(@SearchString, 2) + ':' + substring(@SearchString, 2, 2)
        end)

        --if (isdate(@SearchString) = 0) set @SearchString = '23:59:59' --PR-03191
        --set @where = @SearchField + ' >= ''1899-12-30 ' + @SearchString + ''' ' --PR-03191
	if (isdate(@SearchString) = 0) Set @SearchString = '23:59' --PR-03191
	set @where = 'convert(NVarChar(5), ' + @SearchField + ', 14) >= ''' + @SearchString + ''' ' --PR-03191
    end

    -- all other cases
    else if isnull(@where, '') = '' begin
		select @FieldDT = Data_Type from information_schema.columns where Column_Name = @SearchField and Table_Name like 'AB_%'
		if (@FieldDT = 'int') begin            --if (@SearchString = '') set @SearchString = '0'
            if (isnumeric(@SearchString) <> 1) set @SearchString = '0'
            set @where = @SearchField + ' >= ' + @SearchString + ' '
        end
        else 
            set @where = @SearchField + ' like ''%' + @SearchString + '%'' '
    end 

    set @where = 
        'where IsDeleted = 2 ' + @SearchPrefix + 
		'and (isnull(AB_Main.HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(AB_Main.HospitalID, 0) end) ' +
        'and ' + @where  +  @ExtraSearch  

    set @order = 'order by [Hosp ID], ' + @SearchField + ', AdmitDate desc'

    select @sql = @select + @from + @where + @order
end

exec sp_executesql @sql

if @ShowVip = '2'
begin
	set @sql = 'delete ' + @results + ' where [Chart #] in (select replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'') 
		from CM_CPI where isnull(secret, 0) = 1 and replace(space(10-len(ChartNumber)) + ChartNumber, '' '', ''0'')
		in (select [Chart #] from ' + @results + '))'
	exec(@sql)
end
if @SearchAudit = 1
begin
	declare @CurDTime as Datetime
	set @CurDTime = getdate()
	set @sql = 'insert into AU_SearchDetail select ' + cast(@Appid as varchar(10)) + ', [ ], ''' + Cast(@LogID as varchar(10)) + ''', ''' + convert(varchar(30), @CurDTime, 120) + ''' as Field2 from ' + @results
	exec(@sql)
end

set nocount off
    set @sql = 'select [ ], [' + @FieldDesc + '] = [SearchItem#], [Hosp ID], [Chart #], [Encounter #], [Full Name], [Admit Date], [Admit Time], [Deceased], [Module] from ' + @results + ' order by [Hosp ID], [SearchItem#] desc'
	--set @sql = 'select * from ' + @results + @OrdT
	exec(@sql)
	set @sql = 'drop table ' + @results
	exec(@sql)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE  Procedure [GetLookUpUpdateHistory] (
	@TableName         varchar(250) = null, 
	@InstitutionNumber varchar(12) = null,
    @RecordID          int = null, 
	@DateFrom          datetime = null, 
	@DateTo            datetime = null,
    @Coder             varchar(12) = null
) 
as

declare @LookUp    varchar(100)
declare @Sql       varchar(2000)
declare @LookUpID  int
declare @TempTable varchar(100)
declare @CoderNumber int
set nocount on

if isnull(@TableName, '') = '' set @TableName = ''
if isnull(@DateFrom, '1900/01/01') < '1950/04/01' set @DateFrom = '1950/04/01'
if isnull(@DateTo, '2001/03/31') < '2002/03/31' set @DateTo = '2020/03/31'
if @RecordID is null set @RecordID = 0
if isnull(@InstitutionNumber, '') = '' set @InstitutionNumber = ''
set @CoderNumber = isnull((select top 1 code from U_Users where displaycode = @Coder), 1)

set @LookUp = (select top 1 lookuptable from u_usersfields  
                where appid = @CoderNumber and appid = 1100 AND header_user = @TableName)

if @LookUp is null
    set @LookUp = (select top 1 lookuptable from u_usersfields UF 
                where appid = @CoderNumber and appid = 201 AND header_user = @TableName)

if @LookUp is null and @TableName like 'Report%'
begin
    set @LookUp = 'LU_Reports'
end
set @TempTable = 'zz#LLU_UpdateHistory' + 
    cast(datepart(year, getdate()) as varchar(10)) +
    cast(datepart(month, getdate()) as varchar(10)) +
    cast(datepart(day, getdate()) as varchar(10)) +
    cast(datepart(hour, getdate()) as varchar(10)) +
    cast(datepart(minute, getdate()) as varchar(10)) +
    cast(datepart(second, getdate()) as varchar(10)) 

set @sql = 'if exists (select * from dbo.sysobjects where id = object_id(N''[' + @TempTable + ']'') and OBJECTPROPERTY(id, N''IsUserTable'') = 1)
    drop table [' + @TempTable + ']'

exec (@sql)

set @sql = 'create table ' + @TempTable + '(
    TableName varchar(50),
    DisplayCode varchar(50),
    UserDescription varchar(255),
    UpdateCoder varchar(50), 
    UpdateCoderDesc varchar(255),
    UpdateTime datetime
)'
exec (@sql)

--select @TableName ,	@InstitutionNumber,    @RecordID, 	@DateFrom, 	@DateTo , @LookUp

if isnull(@LookUp, '') <> ''
begin
    if @LookUp = 'ICD10_Diag' set @LookUp = 'ICD_DiagFile10'
    else if @LookUp = 'ICD10_Interv' set @LookUp = 'ICD_ProcFile10'

    set @sql = '
    insert ' + @TempTable + '
    select TableName = ''' + @TableName + ''', ' +
        (case when @LookUp = 'LU_Reports' then 'DisplayCode = ''''' else 'L.DisplayCode' end) +
        ', L.UserDescription,
        UpdateCoder = U.DisplayCode, 
        UpdateCoderDesc = U.UserDescription,
        UpdateTime = H.Updated
    from LLU_UpdateHistory H
        inner join U_Users U on H.Coder = U.Code
        inner join ' + (case when isnumeric(@LookUp) = 0 then @LookUp
          else 'LU_CodeFile' end) + ' L on H.RecordID = L.Code
    where TableName = ''' + @LookUp + ''' ' +
    (case when @RecordID > 0 then 'and L.Code = ' + cast(@RecordID as varchar(10)) 
          else (case when @InstitutionNumber = '' then ''
                     else ' and L.HospitalID in (0, (select top 1 HospitalID
                                    from H_InstitutionProfile where DisplayCode = ''' + @InstitutionNumber + ''')) '
                end)
     end) + ' and H.Updated between ''' + cast(@DateFrom as varchar(50)) + 
        ''' and ''' +  cast(@DateTo as varchar(50)) + ''' '
    --print @sql
    exec (@sql)
end
else
begin
    declare @cur_lookup cursor
    SET @cur_lookup = CURSOR SCROLL KEYSET FOR
        SELECT distinct TableName FROM LLU_UpdateHistory
    open @cur_lookup
    fetch next from @cur_lookup into @lookup
    while(@@fetch_status = 0)
    begin

        set @TableName = (select top 1 header_user from u_usersfields 
                where userid = @CoderNumber and appid = 1100 AND lookuptable = @lookup)
        if @TableName is null
            set @TableName = (select top 1 header_user from u_usersfields 
                where userid = @CoderNumber and appid = 201 AND lookuptable = @lookup)

        if @TableName is null and @LookUp like 'LU_ROI%'
            set @TableName = (select top 1 header_user from u_usersfields 
                where userid = @CoderNumber and appid = 1120 AND lookuptable = @lookup)

        if @TableName is null set @TableName = ''

        if @TableName = '' and @LookUp = 'LU_Reports' set @TableName = 'Reports'
        
        if exists (select * from information_schema.tables where table_name = @LookUp and table_type = 'base table')
            and @LookUp not like 'llu[_]Provider%'
            and @LookUp not like 'NU[_]%'
        begin
            set @sql = '
            insert ' + @TempTable + '
            select TableName = ''' + (case when @LookUp = 'LU_Reports' then 'Report Table' else @TableName end) + ''', ' +
                (case when @LookUp = 'LU_Reports' then 'DisplayCode = ''''' else 'L.DisplayCode' end) +
                ', L.UserDescription,
                UpdateCoder = U.DisplayCode, 
                UpdateCoderDesc = U.UserDescription,
                UpdateTime = H.Updated
            from LLU_UpdateHistory H
                inner join U_Users U on H.Coder = U.Code
                inner join ' + (case when isnumeric(@LookUp) = 0 then @LookUp
                  else 'LU_CodeFile' end) + ' L on H.RecordID = L.Code
            where TableName = ''' + @LookUp + ''' ' +
            (case when @InstitutionNumber = '' then ''
                  else ' and L.HospitalID in (0, (select top 1 HospitalID
                          from H_InstitutionProfile where DisplayCode = ''' + @InstitutionNumber + ''')) '
             end) + 'and H.Updated between ''' + cast(@DateFrom as varchar(50)) + 
                ''' and ''' +  cast(@DateTo as varchar(50)) + ''' '
            print @sql
            
            exec (@sql)
        end
        fetch next from @cur_lookup into @lookup
    end
end
set @sql = 'select TableName, DisplayCode, UserDescription, 
    UpdateCoder, UpdateCoderDesc, UpdateTime 
from ' + @TempTable + ' order by TableName, DisplayCode '
exec (@sql)

set @sql = 'drop table ' + @TempTable 
exec (@sql)

set nocount off


            
    






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This generates a random password, defaulting to 10 characters
create procedure [GetPass]
 @passlen int = 10, @charset int = 2 -- 2 is alphanumeric + special characters,
 -- 1 is alphanumeric, 0 is alphabetical only
as
set nocount on
if (@passlen > 8000 or @passlen < 1) -- Let's not go crazy here
 select @passlen = 10

declare @password varchar(8000), @string varchar(256), @numbers varchar(10), @extra varchar(50),
 @stringlen int, @index int

-- no 1, l, I, 0, O which can cause confusion
select @string = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' -- same as @charset = 0
select @numbers = '23456789'
select @extra = '">_!@#$%&=?<>' -- add more special characters if you want


if @charset = 2
 select @string = @string + @numbers + @extra
else if @charset = 1
 select @string = @string + @numbers
-- else assume @extra is 0 and @string is just letters. Feel free to modify these criteria as you see fit

select @stringlen = len(@string)

select @password = ''

while (@passlen > 0)
begin
 -- For the random part here, use rand() or newid()
 select @index = (abs(checksum(newid())) % @stringlen) + 1
 select @password = @password + substring(@string, @index, 1)
 select @passlen = @passlen - 1
end
select @password
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_AB_Abstract]
   (@IsMultiContact             [int],
    @ICDType                    [char](1),
    @CareType                   [int],
    @HospitalID			[int],
    @AbstractID                 [int],
    @IsCorrected                [int],
    @IsSubmitted                [int],
    @IsValidated                [int],
    @IsCompleted                [int],
    @IsDeleted                  [int],
    @CIHIDateSent          	[datetime],
    @BatchYear                  [varchar](10),
    @BatchPeriod                [int],
    @BatchNumber                [varchar](10),
    @AbstractNumber             [varchar](10),
    @ProvinceNumber             [int],
    @InstitutionNumber          [int],
    @SiteNumber                 [int],
    @EncounterNumber            [varchar](20),
    @EncounterSequence          [int],
    @ChartNumber                [varchar](10),
    @CoderNumber           	[int],
    @MaidenName            	[varchar](35),
    @LastName                   [varchar](40),
    @MiddleName                 [varchar](15),
    @FirstName                  [varchar](35),
    @Gender                     [int],
    @BirthDate                  [datetime],
    @BirthDateEstimated         [int],
    @MaritalStatus              [int],
    @LanguageCode          	[int],
    @PostalCode                 [varchar](6),
    @ResidenceCode              [int],
    @ResponsiblePayment         [int],
    @EducationLevel             [int],
    @Occupation                 [int],
    @LivingArrangement         	[int],
    @ResidenceType             	[int],
    @HCNProvince           	[int],
    @HealthCareNumber           [varchar](12),
    @HCNVersion                 [varchar](2),
    @AdmitDate                  [datetime],
    @AdmitTime                  [datetime],
    @ArrivalMode                [int],
    @ArrivalDate                [datetime],
    @ArrivalTime                [datetime],
    @RegisterNumber             [varchar](8),
    @SecondChartRegNumber  	[varchar](10),
    @AgeCode                    [int],
    @AgeNumber                  [varchar](10),
    @EntryCode                  [int],
    @DecisionAdmitDate          [datetime],
    @DecisionAdmitTime          [datetime],
    @DecisionAdmitDifference    [varchar](10),
    @TransferOverloadDate       [datetime],
    @TransferOverloadTime  	[datetime],
    @TransferOverloadDifference [varchar](10),
    @NextSchedVisitDate         [datetime],
    @NextSchedVisitTime         [datetime],
    @WaitTimeER                 [varchar](10),
    @Weight                     [varchar](10),
    @AdmitCategory         	[int],
    @AdmitAmbulance             [int],
    @AmbulanceReportNumber      [varchar](11),
    @Institutionfrom            [int],
    @Program                    [int],
    @MISCode                    [int],
    @ContactMode                [int],
    @Referredfrom               [int],
    @VisitType                  [int],
    @ReAdmitCode                [int],
    @UnplanReAdmit         	[int],
    @AttendingPhysician         [int],
    @AdmittingDiagnosis         [int],
    @ChiefComplaint             [varchar](250),
    @Injury                     [int],
    @InjuryLocation             [int],
    @InjuryActivity             [int],
    @InjuryActivityDescription  [varchar](250),
    @TriageLevel                [int],
    @TriageDate                 [datetime],
    @TriageTime                 [datetime],
    @ArrivalTriageDifference    [varchar](10),
    @AssessmentDate             [datetime],
    @AssessmentTime             [datetime],
    @WaitAssessmentDifference   [varchar](10),
    @AdmittingNurseArea         [int],
    @PreAdmitWorkUp             [int],
    @DischargeDate         	[datetime],
    @DischargeTime         	[datetime],
    @EstimatedDischargeDate     [datetime],
    @DischargeNurseArea         [int],
    @LOSDays                    [varchar](10),
    @LOSTime                    [varchar](10),
    @LOSMinutes                 [varchar](10),
    @LOSTotal                   [varchar](10),
    @PhysicianEstimatedLOS      [varchar](10),
    @DischargeAge          	[varchar](10),
    @ExitCode                   [int],
    @DispositionCode            [int],
    @ReferredTo                 [int],
    @DischargePlanning          [int],
    @DateReadyDischarge         [datetime],
    @DateLeftER                 [datetime],
    @TimeLeftER                 [datetime],
    @InstitutionTo              [int],
    @SocialService              [int],
    @NewbornChart          	[varchar](10),
    @NewbornDischargeDate  	[datetime],
    @AcuteLOS                   [varchar](10),
    @ALCLOS                     [varchar](10),
    @GlasgowComaScale           [int],
    @Complication               [int],
    @SurgicalCase               [int],
    @PreOpDays                  [varchar](10),
    @PostOpDays                 [varchar](10),
    @InterfaceDate              [datetime],
    @InterfaceTime              [datetime],
    @InterfaceCoder             [int],
    @InputDate                  [datetime],
    @InputTime                  [datetime],
    @DataEntryCoder             [int],
    @FinishDate                 [datetime],
    @FinishTime                 [datetime],
    @Secret                     [int],
    @AbstractOverflow           [int],
    @TSIDate                    [datetime],
    @TSITime                    [datetime],
    @TSICoder                   [int],
    @InjuryDate                 [datetime],
    @FamilyPhysician            [int],
    @VisitStatus                [int],   
    @NurseAssessDate            [datetime],
    @NurseAssessTime            [datetime],
    @NurseAssessDiff            [varchar](10),
    @UniqiueLifetimeID          [varchar](20),
    @DecisionAdmitTimeUnknown   [int], 
    @AssessmentTimeUnknown      [int],
    @PCTASIndicator             [int], 
    @SchedEDVisit               [int],
    @SeatbeltIndicator          [int],
    @HelmetIndicator 	        [int], 
    @ReferralDate 		[datetime], 
    @CompleteRecord 		[int],
    @AgeGroup 			[int], 
    @StakeHolder 		[int],
    @TimeLeftERUnknown 		[int], 
    @DischargeAgeCode 		[int],
    @DischargeTimeUnknown 	[int],
    @ReasonForVisit 		[int],
    @RefPhysician 		[int],
    @TriageTimeUnknown 	[int],
    @AmbulanceArrDate 		[datetime], 
    @AmbulanceArrTime 		[datetime], 
    @AmbulanceTranDate 	[datetime], 
    @AmbulanceTranTime 	[datetime],
    @CDUArrivalDate 	[datetime], 
    @CDUArrivalTime 	[datetime],
    @IsReciprocalBilling int,
    @CDUFlag             int = 0,
    @CDUInTimeUnknown    int = 0,
    @CDUOutDate          datetime = null,
    @CDUOutTime          datetime = null,
    @CDUOutTimeUnknown   int = 0,
    @AccessCareCode      int = 0,
    @SubmissionLevel     int = 0,
    @AmbulanceArrTimeUnknown int = 0,
    @AmbulanceTranTimeUnknown int = 0,
    @IsSubmitLevel1 	int, 
    @IsCorrectLevel1 	int,
    @IsValidLevel1	int,
    @CIHIDateSentLevel1 datetime, 
    @IsCompleteLevel1 	int,
    @AdmitTimeUnknown  int,
    @ArrivalTimeUnknown int,
    @RegionalPatientID varchar(50),
    @FixedChartNumber varchar(50),
	@IsCustomValidated int,
    @WaitTimeERHour int,
    @Height varchar(10),
    @WeightKilo varchar(10),
	@InstitutionFromType int,
	@InstitutionToType int,
	@UniversalEpisodeIdentifier varchar(50),
    @IsLiteSubmission int,
    @HospitalAccountRecord varchar(50),
	@IndigenousIdentity int,
	@RacializedGroups int
)
AS 
set @LastName = replace(@LastName, '''''', '''')
select @AbstractID = (select isnull(max(AbstractID), 0) from AB_Abstract) + 1
-- If it's a Multi Contact then Increment the Encounter Sequence.
if @IsMultiContact = 1 
select @EncounterSequence = (select isnull(max([EncounterSequence]), 1) from AB_Abstract where [EncounterNumber] = @EncounterNumber) + 1

If isnull(@IsDeleted, 0) = 0   set @IsDeleted = 2   -- PR - 03723
If isnull(@IsCorrected, 0) = 0 set @IsCorrected = 1 -- PR - 03723
If isnull(@IsSubmitted, 0) = 0 set @IsSubmitted = 2  -- PR - 03723
If isnull(@IsSubmitLevel1, 0) = 0 set @IsSubmitLevel1 = 2  --NP-00125
If isnull(@IsCorrectLevel1, 0) = 0 set @IsCorrectLevel1 = 1 --NP-00125
If isnull(@IsCompleteLevel1, 0) = 0 set @IsCompleteLevel1 = 1 --ED-02065

if @AgeNumber < 0 set @AgeNumber = 0    --PR - 05653

insert into [AB_Abstract] 
    ([LinkID],
    [AbstractID],
    [HospitalID],
    [VolumeID],
    [IsCorrected],
    [CIHIReturnStatus],
    [IsSubmited],
    [IsValidated],
    [IsCompleted],
    [IsDeleted],
    [IsReciprocalBilling],
    [ICDType],
    [CareType],
    [CIHIDateSent],
    [BatchYear],
    [BatchPeriod],
    [BatchNumber],
    [AbstractNumber],
    [ProvinceNumber],
    [InstitutionNumber],
    [SiteNumber],
    [EncounterNumber],
    [EncounterSequence],
    [ChartNumber],
    [UniqiueLifetimeID],
    [CoderNumber],
    [MaidenName],
    [LastName],
    [MiddleName],
    [FirstName],
    [Gender],
    [BirthDate],
    [BirthDateEstimated],
    [MaritalStatus],
    [LanguageCode],
    [PostalCode],
    [ResidenceCode],
    [ResponsiblePayment],
    [FamilyPhysician],
    [EducationLevel],
    [Occupation],
    [LivingArrangement],
    [ResidenceType],
    [HCNProvince],
    [HealthCareNumber],
    [HCNVersion],
    [AdmitDate],
    [AdmitTime],
    [ArrivalMode],
    [ArrivalDate],
    [ArrivalTime],
    [RegisterNumber],
    [SecondChartRegNumber],
    [AgeCode],
    [AgeNumber],
    [AgeGroup],
    [EntryCode],
    [DecisionAdmitDate],
    [DecisionAdmitTime],
    [DecisionAdmitDifference],
    [DecisionAdmitTimeUnknown], 
    [TransferOverloadDate],
    [TransferOverloadTime],
    [TransferOverloadDifference],
    [NextSchedVisitDate],
    [NextSchedVisitTime],
    [WaitTimeER],
    [Weight],
    [AdmitCategory],
    [AdmitAmbulance],
    [AmbulanceReportNumber],
    [Institutionfrom],
    [Program],
    [MISCode],
    [ContactMode],
    [Referredfrom],
    [VisitType],
    [VisitStatus],
    [ReasonForVisit],
    [ReAdmitCode],
    [UnplanReAdmit],
    [AttendingPhysician],
    [AdmittingDiagnosis],
    [ChiefComplaint],
    [Injury],
    [InjuryDate],
    [InjuryLocation],
    [InjuryActivity],
    [InjuryActivityDescription],
    [TriageLevel],
    [TriageDate],
    [TriageTime],
    [TriageTimeUnknown],
    [ArrivalTriageDifference],
    [AssessmentDate],
    [AssessmentTime],
    [WaitAssessmentDifference],
    [AssessmentTimeUnknown], 
    [NurseAssessDate], 
    [NurseAssessTime], 
    [NurseAssessDiff],
    [AdmittingNurseArea],
    [PreAdmitWorkUp],
    [DischargeDate],
    [DischargeTime],
    [DischargeTimeUnknown], 
    [EstimatedDischargeDate],
    [DischargeNurseArea],
    [LOSDays],
    [LOSTime],
    [LOSMinutes],
    [LOSTotal],
    [PhysicianEstimatedLOS],
    [DischargeAge],
    [DischargeAgeCode],
    [ExitCode],
    [DispositionCode],
    [ReferredTo],
    [DischargePlanning],
    [DateReadyDischarge],
    [DateLeftER],
    [TimeLeftER],
    [InstitutionTo],
    [SocialService],
    [NewbornChart],
    [NewbornDischargeDate],
    [AcuteLOS],
    [ALCLOS],
    [GlasgowComaScale],
    [Complication],
    [SurgicalCase],
    [PreOpDays],
    [PostOpDays],
    [InterfaceDate],
    [InterfaceTime],
    [InterfaceCoder],
    [InputDate],
    [InputTime],
    [DataEntryCoder],
    [FinishDate],
    [FinishTime],
    [Secret],
    [AbstractOverflow],
    [TSIDate],
    [TSITime],
    [TSICoder],
    [PCTASIndicator], 
    [SchedEDVisit],
    [SeatbeltIndicator],
    [HelmetIndicator], 
    [ReferralDate], 
    [CompleteRecord],
    [StakeHolder],
    [TimeLeftERUnknown],
    [RefPhysician],
    [AmbulanceArrDate],
    [AmbulanceArrTime],
    [AmbulanceTranDate],
    [AmbulanceTranTime],
    [CDUArrivalDate], 
    [CDUArrivalTime],
    CDUFlag,
    CDUInTimeUnknown,
    CDUOutDate,
    CDUOutTime,
    CDUOutTimeUnknown,
    AccessCareCode,
    SubmissionLevel,
    AmbulanceArrTimeUnknown,
    AmbulanceTranTimeUnknown,
    [IsSubmitLevel1], 
    [IsCorrectLevel1],
    [IsValidLevel1],
    [CIHIDateSentLevel1],
    [IsCompleteLevel1],
    [AdmitTimeUnknown],
    [ArrivalTimeUnknown],
    [RegionalPatientID],
    [FixedChartNumber],
	[IsCustomValidated],
    [WaitTimeERHour],
    [Height],
    [WeightKilo],
	[InstitutionFromType],
	[InstitutionToType],
	[UniversalEpisodeIdentifier],
    [IsLiteSubmission],
    [HospitalAccountRecord],
	[IndigenousIdentity],
	[RacializedGroups]
) 
values 
   (null, 
    @AbstractID,
    @HospitalID,
    1,      
    1,
    1,
    2,
    @IsValidated,
    @IsCompleted,
    2,
    2,
    @ICDType,
    @CareType,
    @CIHIDateSent,
    @BatchYear,
    @BatchPeriod,
    @BatchNumber,
    @AbstractNumber,
    @ProvinceNumber,
    @InstitutionNumber,
    @SiteNumber,
    @EncounterNumber,
    @EncounterSequence,
    @ChartNumber,
    @UniqiueLifetimeID,
    @CoderNumber,
    @MaidenName,
    @LastName,
    @MiddleName,
    @FirstName,
    @Gender,
    @BirthDate,
    @BirthDateEstimated,
    @MaritalStatus,
    @LanguageCode,
    @PostalCode,
    @ResidenceCode,
    @ResponsiblePayment,
    @FamilyPhysician,
    @EducationLevel,
    @Occupation,
    @LivingArrangement,
    @ResidenceType,
    @HCNProvince,
    @HealthCareNumber,
    @HCNVersion,
    @AdmitDate,
    @AdmitTime,
    @ArrivalMode,
    @ArrivalDate,
    @ArrivalTime,
    @RegisterNumber,
    @SecondChartRegNumber,
    @AgeCode,
    @AgeNumber,
    @AgeGroup,
    @EntryCode,
    @DecisionAdmitDate,
    @DecisionAdmitTime,
    @DecisionAdmitDifference,
    @DecisionAdmitTimeUnknown, 
    @TransferOverloadDate,
    @TransferOverloadTime,
    @TransferOverloadDifference,
    @NextSchedVisitDate,
    @NextSchedVisitTime,
    @WaitTimeER,
    @Weight,
    @AdmitCategory,
    @AdmitAmbulance,
    @AmbulanceReportNumber,
    @Institutionfrom,
    @Program,
    @MISCode,
    @ContactMode,
    @Referredfrom,
    @VisitType,
    @VisitStatus,
    @ReasonForVisit,
    @ReAdmitCode,
    @UnplanReAdmit,
    @AttendingPhysician,
    @AdmittingDiagnosis,
    @ChiefComplaint,
    @Injury,
    @InjuryDate,
    @InjuryLocation,
    @InjuryActivity,
    @InjuryActivityDescription,
    @TriageLevel,
    @TriageDate,
    @TriageTime,
    @TriageTimeUnknown,
    @ArrivalTriageDifference,
    @AssessmentDate,
    @AssessmentTime,
    @WaitAssessmentDifference,
    @AssessmentTimeUnknown, 
    @NurseAssessDate,
    @NurseAssessTime,
    @NurseAssessDiff,
    @AdmittingNurseArea,
    @PreAdmitWorkUp,
    @DischargeDate,
    @DischargeTime,
    @DischargeTimeUnknown,
    @EstimatedDischargeDate,
    @DischargeNurseArea,
    @LOSDays,
    @LOSTime,
    @LOSMinutes,
    @LOSTotal,
    @PhysicianEstimatedLOS,
    @DischargeAge,
    @DischargeAgeCode,
    @ExitCode,
    @DispositionCode,
    @ReferredTo,
    @DischargePlanning,
    @DateReadyDischarge,
    @DateLeftER,
    @TimeLeftER,
    @InstitutionTo,
    @SocialService,
    @NewbornChart,
    @NewbornDischargeDate,
    @AcuteLOS,
    @ALCLOS,
    @GlasgowComaScale,
    @Complication,
    @SurgicalCase,
    @PreOpDays,
    @PostOpDays,
    @InterfaceDate,
    @InterfaceTime,
    @InterfaceCoder,
    @InputDate,
    @InputTime,
    @DataEntryCoder,
    @FinishDate,
    @FinishTime,
    @Secret,
    @AbstractOverflow,
    @TSIDate,
    @TSITime,
    @TSICoder, 
    @PCTASIndicator, 
    @SchedEDVisit,
    @SeatbeltIndicator,
    @HelmetIndicator, 
    @ReferralDate, 
    @CompleteRecord,
    @StakeHolder,
    @TimeLeftERUnknown,
    @RefPhysician,
    @AmbulanceArrDate, 
    @AmbulanceArrTime,
    @AmbulanceTranDate,
    @AmbulanceTranTime,
    @CDUArrivalDate, 
    @CDUArrivalTime,
    @CDUFlag,
    @CDUInTimeUnknown,
    @CDUOutDate,
    @CDUOutTime,
    @CDUOutTimeUnknown,
    @AccessCareCode,
    @SubmissionLevel,
    @AmbulanceArrTimeUnknown,
    @AmbulanceTranTimeUnknown,
    @IsSubmitLevel1, 
    @IsCorrectLevel1,
    @IsValidLevel1,
    @CIHIDateSentLevel1,
    @IsCompleteLevel1,
    @AdmitTimeUnknown,
    @ArrivalTimeUnknown,
    @RegionalPatientID,
    @FixedChartNumber,
	@IsCustomValidated,
    @WaitTimeERHour,
    @Height,
    @WeightKilo,
	@InstitutionFromType,
	@InstitutionToType,
	@UniversalEpisodeIdentifier,
    @IsLiteSubmission,
    @HospitalAccountRecord,
	@IndigenousIdentity,
	@RacializedGroups
)

/*update multi Enc No's data for common fields*/
if @AdmitDate < '2006/04/01' -- PR-00673
begin
	if @Caretype = 5 and isnull(@EncounterNumber, '') <> ''
	begin
		update [AB_Abstract] 
		set         
			[ChartNumber]   	= @ChartNumber,
		    	[UniqiueLifetimeID] 	= @UniqiueLifetimeID,
		    	[Gender]        	= @Gender,
		    	[BirthDate]     	= @BirthDate,
		    	[BirthDateEstimated]    = @BirthDateEstimated,
		    	[MaritalStatus]         = @MaritalStatus,
		    	[PostalCode]    	= @PostalCode,
		    	[ResidenceCode]         = @ResidenceCode,
		    	[ResponsiblePayment]    = @ResponsiblePayment,
		    	[HCNProvince]   	= @HCNProvince,
		    	[HealthCareNumber]      = @HealthCareNumber,
		    	[HCNVersion]    	= @HCNVersion,
		    	[AdmitDate]     	= @AdmitDate,
		    	[RegisterNumber]        = @RegisterNumber,
		    	[DischargeDate]         = @DischargeDate,
		    	[DischargeTime]         = @DischargeTime,
		    	[DischargeTimeUnknown]	= @DischargeTimeUnknown,
		    	[DispositionCode]       = @DispositionCode
	
		where	[EncounterNumber]       = @EncounterNumber 
		and     [EncounterSequence]     <> @EncounterSequence 
		and 	[ChartNumber]		= @ChartNumber
		and     [AdmitDate] 		= @AdmitDate 
		and 	[AdmitTime] 		= @AdmitTime 
		and 	[InstitutionNumber] 	= @InstitutionNumber
		and     [CareType]             	= 5
	
	    	--10489 Hong added temp
	    	declare @count     int
	    	declare @ID_001    int
	    	declare @Del_001   int
	    	declare @Sub_001   int
	    	declare @Cor_001   int
	    	declare @old_link  int
	
	    	set @count = isnull((select count(*) 
					from AB_Abstract 
		            		where [EncounterNumber]	= @EncounterNumber 
		            		and ChartNumber 	= @ChartNumber
		            		and [AdmitDate] 	= @AdmitDate 
		            		and [AdmitTime] 	= @AdmitTime 
		            		and [InstitutionNumber] = @InstitutionNumber
		            		and [CareType]  	= 5), 0)
	    	if @count > 1
	    	begin
	        	select top 1 
				@ID_001 = AbstractID, 
				@Del_001 = IsDeleted,
	            		@Sub_001 = IsSubmited, 
				@Cor_001 = IsCorrected, 
				@old_link = LinkID
	        	from AB_Abstract 
	        	where  [EncounterNumber]= @EncounterNumber 
	            	and ([EncounterSequence]= '1' or [EncounterSequence] = '001')
	            	and ChartNumber 	= @ChartNumber
	            	and [AdmitDate] 	= @AdmitDate 
	            	and [AdmitTime] 	= @AdmitTime 
	            	and [InstitutionNumber] = @InstitutionNumber
	            	and [CareType]  	= 5
	
	        	if @Sub_001 = 1 and @Cor_001 <> 2 and isnull(@old_link, 0) = 0
	            		update AB_Abstract set IsCorrected = 2 where abstractId = @ID_001
	
	    		-- 10758

	    		update [AB_Abstract] 
			set [LinkID] = @ID_001 
			from [AB_Abstract] 
	    		where  [EncounterNumber]= @EncounterNumber 
	    		and ChartNumber 	= @ChartNumber
	    		and [AdmitDate] 	= @AdmitDate 
	    		and [AdmitTime] 	= @AdmitTime 
	    		and [InstitutionNumber] = @InstitutionNumber
	    		and [CareType]  	= 5
	
	        	if @Del_001 = 1 
	            		update Ab_Abstract 
				set 	IsDeleted = 2, 
					IsCorrected = (case when IsSubmited = 1 then 2 else IsCorrected end) 
	            		where LinkID 	= @ID_001 
				and CareType 	= 5 
				and abstractId 	<> @ID_001 
				and IsDeleted 	= 1
	    	end
	end
end

--Clear the MIS Code for New Contacts. The User must Enter a Unique one.
if @IsMultiContact = 1 
   update AB_Abstract set MISCode = 0, AssessmentDate = NULL, AssessmentTime = NULL, WaitAssessmentDifference = 0 where AbstractID = @AbstractID 

declare @UseDate as DateTime
declare @P as int 
declare @V as int
set @UseDate = @DischargeDate
if @Caretype = 5 set @UseDate = @AdmitDate
select top 1 @P = PatientID from CM_CPI where ChartNumber = @ChartNumber
	and (isnull(HospitalID, 0) = 0 or @HospitalID = case @HospitalID when 0 then 0 else isnull(HospitalID, 0) end) --PR-04125
select top 1 @V = isnull(VolumeID, 0) from CM_CPI_Volume where PatientID = @P and (([VolumeDatefrom] <= @UseDate) and (@UseDate <= [VolumenDateTo])) order by VolumeNumber desc, VolumeID desc
if isnull(@V, 0) = 0 
    select top 1 @V = isnull(VolumeID, 0) from CM_CPI_Volume where PatientID = @P order by VolumenDateTo desc, VolumeID desc
 
exec P_updateAbstractVolume @V, 0, @AbstractID -- 13419: Abst ID is now the 3rd parameter.

-- RM- REMOVED: if @CareType = 5 exec P_UpdateAbstractNumber @AbstractID, @AdmitDate, @DischargeDate --PR-01550

return @AbstractID

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [I_AB_Ancillary]
	(@AbstractID	 	[int],
	 @AncillaryField1 	[int],
	 @AncillaryField2 	[int],
	 @AncillaryField3 	[int],
	 @AncillaryField4 	[int],
	 @AncillaryField5 	[int],
	 @AncillaryField6 	[int],
	 @AncillaryField7 	[int],
	 @AncillaryField8 	[int],
	 @AncillaryField9 	[int],
	 @AncillaryField10 	[int],
	 @AncillaryField11 	[int],
	 @AncillaryField12 	[int],
	 @AncillaryField13 	[int],
	 @AncillaryField14 	[int],
	 @AncillaryField15 	[int],
	 @AncillaryField16 	[int],
	 @AncillaryField17 	[int])
AS 

INSERT INTO [AB_Ancillary] 
	 ( [AbstractID],
	 [AncillaryField1],
	 [AncillaryField2],
	 [AncillaryField3],
	 [AncillaryField4],
	 [AncillaryField5],
	 [AncillaryField6],
	 [AncillaryField7],
	 [AncillaryField8],
	 [AncillaryField9],
	 [AncillaryField10],
	 [AncillaryField11],
	 [AncillaryField12],
	 [AncillaryField13],
	 [AncillaryField14],
	 [AncillaryField15],
	 [AncillaryField16],
	 [AncillaryField17]) 
 
VALUES 
	(@AbstractID,
	 @AncillaryField1,
	 @AncillaryField2,
	 @AncillaryField3,
	 @AncillaryField4,
	 @AncillaryField5,
	 @AncillaryField6,
	 @AncillaryField7,
	 @AncillaryField8,
	 @AncillaryField9,
	 @AncillaryField10,
	 @AncillaryField11,
	 @AncillaryField12,
	 @AncillaryField13,
	 @AncillaryField14,
	 @AncillaryField15,
	 @AncillaryField16,
	 @AncillaryField17)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [I_AB_BasicOption]
	(@AbstractID 	[int],
	 @BasicOption1 	[int],
	 @BasicOption2 	[int],
	 @BasicOption3 	[int],
	 @BasicOption4 	[int],
	 @BasicOption5 	[int],
	 @BasicOption6 	[int],
	 @BasicOption7 	[int],
	 @BasicOption8 	[int],
	 @BasicOption9 	[int],
	 @BasicOption10 	[int],
	 @BasicOption11 	[int],
	 @BasicOption12 	[int],
	 @BasicOption13 	[int],
	 @BasicOption14 	[int],
	 @BasicOption15 	[int],
	 @BasicOption16 	[int],
	 @BasicOption17 	[int],
	 @BasicOption18 	[int],
	 @BasicOption19 	[int])
AS 

INSERT INTO [AB_BasicOption] 
	 ([AbstractID],
	 [BasicOption1],
	 [BasicOption2],
	 [BasicOption3],
	 [BasicOption4],
	 [BasicOption5],
	 [BasicOption6],
	 [BasicOption7],
	 [BasicOption8],
	 [BasicOption9],
	 [BasicOption10],
	 [BasicOption11],
	 [BasicOption12],
	 [BasicOption13],
	 [BasicOption14],
	 [BasicOption15],
	 [BasicOption16],
	 [BasicOption17],
	 [BasicOption18],
	 [BasicOption19]) 
 
VALUES 
	(@AbstractID,
	 @BasicOption1,
	 @BasicOption2,
	 @BasicOption3,
	 @BasicOption4,
	 @BasicOption5,
	 @BasicOption6,
	 @BasicOption7,
	 @BasicOption8,
	 @BasicOption9,
	 @BasicOption10,
	 @BasicOption11,
	 @BasicOption12,
	 @BasicOption13,
	 @BasicOption14,
	 @BasicOption15,
	 @BasicOption16,
	 @BasicOption17,
	 @BasicOption18,
	 @BasicOption19)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE    PROCEDURE [I_AB_Blood]
    (
    @AbstractID	 	[int],
	@TransfusionIndicator 	[int],
	@RedBloodCell		[int],
	@RedCellTyped 	[int],
	@RedCellUnits	 	[varchar](10),
	@RedCellXMatch 	[int],
	@Platelets		[int],
	@PlateletsTyped 	[int],
	@PlateletsUnits 	[varchar](10),
	@PlateletsXMatch 	[int],
	@Plasma		[int],
	@PlasmaTyped 	[int],
	@PlasmaUnits	 	[varchar](10),
	@PlasmaXMatch 	[int],
	@Albumin	 	[int],
	@AlbuminTyped 	[int],
	@AlbuminUnits	 	[varchar](10),
	@AlbuminXMatch 	[int],
	@OtherBlood	 	[int],
	@OtherBloodTyped 	[int],
	@OtherBloodUnits 	[varchar](10),
	@OtherBloodXMatch 	[int],
	@AutoTransfusion 	[int],
    @CryoprecipitatePlasma [int],
    @CryosupernatantPlasma [int],
    @IVIG_SCIG [int],
    @Fibrinogen [int],
    @PCC [int],
    @FEIBA  [int],
    @AntithrombinIII [int],
    @C1Inhibitor [int],
    @ProteinC_OtherFactors [int]
)
AS 

INSERT INTO [AB_Blood] 
	([AbstractID],
	[TransfusionIndicator],
	[RedBloodCell],
	[RedCellTyped],
	[RedCellUnits],
	[RedCellXMatch],
	[Platelets],
	[PlateletsTyped],
	[PlateletsUnits],
	[PlateletsXMatch],
	[Plasma],
	[PlasmaTyped],
	[PlasmaUnits],
	[PlasmaXMatch],
	[Albumin],
	[AlbuminTyped],
	[AlbuminUnits],
	[AlbuminXMatch],
	[OtherBlood],
	[OtherBloodTyped],
	[OtherBloodUnits],
	[OtherBloodXMatch],
	[AutoTransfusion],
    [CryoprecipitatePlasma],
    [CryosupernatantPlasma],
    [IVIG_SCIG],
    [Fibrinogen],
    [PCC],
    [FEIBA],
    [AntithrombinIII],
    [C1Inhibitor],
    [ProteinC_OtherFactors]) 
 
VALUES 
	(@AbstractID,
	 @TransfusionIndicator,
	 @RedBloodCell,
	 @RedCellTyped,
	 @RedCellUnits,
	 @RedCellXMatch,
	 @Platelets,
	 @PlateletsTyped,
	 @PlateletsUnits,
	 @PlateletsXMatch,
	 @Plasma,
	 @PlasmaTyped,
	 @PlasmaUnits,
	 @PlasmaXMatch,
	 @Albumin,
	 @AlbuminTyped,
	 @AlbuminUnits,
	 @AlbuminXMatch,
	 @OtherBlood,
	 @OtherBloodTyped,
	 @OtherBloodUnits,
	 @OtherBloodXMatch,
	 @AutoTransfusion,
     @CryoprecipitatePlasma,
     @CryosupernatantPlasma,
     @IVIG_SCIG,
     @Fibrinogen,
     @PCC,
     @FEIBA, 
     @AntithrombinIII,
     @C1Inhibitor,
     @ProteinC_OtherFactors)

/*Update Amcare Multi EncNo's*/
--13298:  Do not update the blood automatially.
/*if not exists (Select Encounternumber from AB_Abstract where abstractid = @AbstractID and (encounternumber = '' or encounternumber is null))
Update [AB_Blood] Set
	 [TransfusionIndicator] = @TransfusionIndicator,
	 [RedBloodCell] = @RedBloodCell,
	 [RedCellUnits] = @RedCellUnits,
	 [Platelets] = @Platelets,
	 [PlateletsUnits] = @PlateletsUnits,
	 [Plasma] = @Plasma,
	 [PlasmaUnits] = @PlasmaUnits,
	 [Albumin] = @Albumin,
	 [AlbuminUnits] = @AlbuminUnits,
	 [OtherBlood] = @OtherBlood,
	 [OtherBloodUnits] = @OtherBloodUnits
Where AbstractID in
	(select A1.AbstractID 
	 from AB_Abstract A1, AB_Abstract A2
	 where A2.AbstractID = @AbstractID
		and A1.EncounterNumber = A2.EncounterNumber 
		and A1.EncounterSequence <> A2.EncounterSequence 
		and A1.ChartNumber = A2.ChartNumber
		and A1.AdmitDate = A2.AdmitDate 
		and A1.AdmitTime = A2.AdmitTime 
		and A1.InstitutionNumber = A2.InstitutionNumber
		and A1.CareType = 5)
*/

-- 13298: Changed the criteria to be more narrow (to match the I_AB_Abstract)
-- (Select AbstractID From AB_Abstract, (Select Encounternumber as EncNoMulti,
--EncounterSequence as EncSeqMulti from AB_Abstract where
--AbstractID = @AbstractID) as EncTemp where Encounternumber = EncTemp.EncNoMulti and 
--EncounterSequence <> EncTemp.EncSeqMulti)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [I_AB_CACS]
	(@AbstractID 		[int],
	 @OccurrenceNumber 	[int],
	 @CACS_Year 		[int],
	 @MAC 		[varchar](2),
	 @CACSCell 		[varchar](6),
	 @ACW			[decimal](6,4),
	 @CACS_Description 	[varchar](150),
	 @InterventionCode	[int],
	 @AgeCategory   varchar(1) = null, 
	 @AnaestheticCategory varchar(1) = null, 
	 @MITTotalCount    int = null,
	 @BatchGroupDate varchar(20),
	 @ACW_HBAM decimal(6, 4) = null, 
	 @ACW_Base decimal(6, 4) = null, 
	 @CACSPartition char(1) = null, 
	 @MIT_Category_01 varchar(10) = null, 
	 @MIT_Category_Count_01 varchar(10) = null, 
	 @MIT_Category_02 varchar(10) = null, 
	 @MIT_Category_Count_02 varchar(10) = null, 
	 @MIT_Category_03 varchar(10) = null, 
	 @MIT_Category_Count_03 varchar(10) = null, 
	 @MIT_Category_04 varchar(10) = null, 
	 @MIT_Category_Count_04 varchar(10) = null, 
	 @MIT_Category_05 varchar(10) = null, 
	 @MIT_Category_Count_05 varchar(10) = null, 
	 @MIT_Category_06 varchar(10) = null, 
	 @MIT_Category_Count_06 varchar(10) = null, 
	 @MIT_Category_07 varchar(10) = null, 
	 @MIT_Category_Count_07 varchar(10) = null, 
	 @MIT_Category_08 varchar(10) = null, 
	 @MIT_Category_Count_08 varchar(10) = null, 
	 @MIT_Category_09 varchar(10) = null, 
	 @MIT_Category_Count_09 varchar(10) = null, 
	 @MIT_Category_10 varchar(10) = null, 
	 @MIT_Category_Count_10 varchar(10) = null
	 )
AS 
declare @Year int
declare @BatchDate datetime	--EN - 00510
if isdate(@BatchGroupDate) = 1 set @BatchDate = cast(@BatchGroupDate as datetime)

set @year = datepart(year, getdate())

if not exists (select * from [AB_CACS] where abstractid = @AbstractID and [OccurrenceNumber] = @OccurrenceNumber
                and [CACS_Year] = @CACS_Year) and @CACS_Year <= @year
    INSERT INTO [dbo].[AB_CACS] 
	     ([AbstractID],
	     [OccurrenceNumber],
	     [CACS_Year],
	     [MAC],
	     [CACSCell],
	     [ACW],
	     [CACSDescription], 
	     [InterventionCode],
	     [AgeCategory], 
	     [AnaestheticCategory], 
	     [MITTotalCount],
	     [BatchGroupDate],
	     [ACW_HBAM], 
	     [ACW_Base]) 
    VALUES 
	    (@AbstractID,
	     @OccurrenceNumber,
	     @CACS_Year,
	     @MAC,
	     @CACSCell,
	     @ACW,
	     @CACS_Description,
	     @InterventionCode,
	     @AgeCategory, 
	     @AnaestheticCategory, 
	     @MITTotalCount,
	     @BatchDate,
	     @ACW_HBAM, 
	     @ACW_Base)

if @CACS_Year >= 2011
begin
    if not exists (select * from [AB_CACS_Investigative] where abstractid = @AbstractID and [OccurrenceNumber] = @OccurrenceNumber
                and [CACS_Year] = @CACS_Year) and @CACS_Year <= @year
    insert into dbo.AB_CACS_Investigative(
        AbstractID, 
        OccurrenceNumber, 
        CACS_Year, 
        CACSPartition, 
        MIT_Category_01, MIT_Category_Count_01, 
        MIT_Category_02, MIT_Category_Count_02, 
        MIT_Category_03, MIT_Category_Count_03, 
        MIT_Category_04, MIT_Category_Count_04, 
        MIT_Category_05, MIT_Category_Count_05, 
        MIT_Category_06, MIT_Category_Count_06, 
        MIT_Category_07, MIT_Category_Count_07, 
        MIT_Category_08, MIT_Category_Count_08, 
        MIT_Category_09, MIT_Category_Count_09, 
        MIT_Category_10, MIT_Category_Count_10
    )
    values
    (   @AbstractID,
	    @OccurrenceNumber,
	    @CACS_Year,
        @CACSPartition, 
        @MIT_Category_01, @MIT_Category_Count_01, 
        @MIT_Category_02, @MIT_Category_Count_02, 
        @MIT_Category_03, @MIT_Category_Count_03, 
        @MIT_Category_04, @MIT_Category_Count_04, 
        @MIT_Category_05, @MIT_Category_Count_05, 
        @MIT_Category_06, @MIT_Category_Count_06, 
        @MIT_Category_07, @MIT_Category_Count_07, 
        @MIT_Category_08, @MIT_Category_Count_08, 
        @MIT_Category_09, @MIT_Category_Count_09, 
        @MIT_Category_10, @MIT_Category_Count_10
    )
end

--QA - 00035 For Audit
declare @OldValue varchar(100)
if @OccurrenceNumber = 1 and @CACS_Year > 2013
begin
    set @OldValue = dbo.GetGrouperAuditValue(@AbstractID, @CACS_Year, 'MCC')
    if isnull(@OldValue, '') <> @MAC
        insert into dbo.AB_GrouperAudit(AbstractID, GroupingYear, FieldChanged, OldValue, NewValue, DateGrouped)
        select @AbstractID, @CACS_Year, 'MCC', @OldValue, @MAC, getdate()

    set @OldValue = dbo.GetGrouperAuditValue(@AbstractID, @CACS_Year, 'CACSCell')
    if isnull(@OldValue, '') <> @CACSCell
        insert into dbo.AB_GrouperAudit(AbstractID, GroupingYear, FieldChanged, OldValue, NewValue, DateGrouped)
        select @AbstractID, @CACS_Year, 'CACSCell', @OldValue, @CACSCell, getdate()
        
    set @OldValue = dbo.GetGrouperAuditValue(@AbstractID, @CACS_Year, 'ACW')
    if isnull(@OldValue, '') <> isnull(cast(@ACW as varchar(10)), '')
        insert into dbo.AB_GrouperAudit(AbstractID, GroupingYear, FieldChanged, OldValue, NewValue, DateGrouped)
        select @AbstractID, @CACS_Year, 'ACW', @OldValue, cast(@ACW as varchar(10)), getdate()
    
    if @CACS_Year >= 2012 and isnull(cast(@ACW_HBAM as varchar(10)), '') <> ''
    begin
        set @OldValue = dbo.GetGrouperAuditValue(@AbstractID, @CACS_Year, 'CACSON')
        if isnull(@OldValue, '') <> isnull(cast(@ACW_HBAM as varchar(10)), '')
            insert into dbo.AB_GrouperAudit(AbstractID, GroupingYear, FieldChanged, OldValue, NewValue, DateGrouped)
            select @AbstractID, @CACS_Year, 'CACSON', @OldValue, cast(@ACW_HBAM as varchar(10)), getdate()
    end
end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [I_AB_CancerStaging]
	(@AbstractID 		[int],
	 @ClinicalTumor 	[varchar](1),
	 @ClinicalNode	 	[varchar](2),
	 @ClinicalMetastasis 	[varchar](2),
	 @PathTumor	 	[varchar](1),
	 @PathNode	 	[varchar](2),
	 @PathMetastasis 	[varchar](2),
	 @SummaryStage 	[varchar](4))
AS 

INSERT INTO [AB_CancerStaging] 
	 ([AbstractID],
	 [ClinicalTumor],
	 [ClinicalNode],
	 [ClinicalMetastasis],
	 [PathTumor],
	 [PathNode],
	 [PathMetastasis],
	 [SummaryStage]) 
 
VALUES 
	(@AbstractID,
	 @ClinicalTumor,
	 @ClinicalNode,
	 @ClinicalMetastasis,
	 @PathTumor,
	 @PathNode,
	 @PathMetastasis,
	 @SummaryStage)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [I_AB_CCM_CancerCareInformation]
(   @AbstractID int, 
    @CancerCareVisit int, 
    @VisitProgramCode int, 
    @CCMVisitType int, 
    @InpatientFlag int, 
    @RadiationReviewFlag int, 
    @ChemoFlag int, 
    @ClinicalTrialFlag int, 
    @HealthCareProviderNumber int,
    @ArrivedByNotTreatedFlag int
)   
as
    insert into dbo.AB_CCM_CancerCareInformation(
        AbstractID, 
        CancerCareVisit, 
        VisitProgramCode, 
        CCMVisitType, 
        InpatientFlag, 
        RadiationReviewFlag, 
        ChemoFlag, 
        ClinicalTrialFlag, 
        HealthCareProviderNumber,
        ArrivedByNotTreatedFlag
        )
    values(
        @AbstractID, 
        @CancerCareVisit, 
        @VisitProgramCode, 
        @CCMVisitType, 
        @InpatientFlag, 
        @RadiationReviewFlag, 
        @ChemoFlag, 
        @ClinicalTrialFlag, 
        @HealthCareProviderNumber,
        @ArrivedByNotTreatedFlag
    )
   
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [I_AB_CCM_Radiation]
(   @AbstractID int, 
    @CourseOfRadiationTreatment int, 
    @CourseCompleteFlag int, 
    @NHPIPCode int, 
    @BodyRegionCode int, 
    @DosePerFraction varchar(12), 
    @IntentOfRadiationTreatment int, 
    @DecisionToTreatDate datetime, 
    @ReadyToTreatDate datetime, 
    @UrgencyCategory int, 
    @TreatmentUnitName varchar(20),
    @RTProtocol int
)
as
    insert into dbo.AB_CCM_Radiation(
        AbstractID, 
        CourseOfRadiationTreatment, 
        CourseCompleteFlag, 
        NHPIPCode, 
        BodyRegionCode, 
        DosePerFraction, 
        IntentOfRadiationTreatment, 
        DecisionToTreatDate, 
        ReadyToTreatDate, 
        UrgencyCategory, 
        TreatmentUnitName,
        RTProtocol) 
    values(
        @AbstractID, 
        @CourseOfRadiationTreatment, 
        @CourseCompleteFlag, 
        @NHPIPCode, 
        @BodyRegionCode, 
        @DosePerFraction, 
        @IntentOfRadiationTreatment, 
        @DecisionToTreatDate, 
        @ReadyToTreatDate, 
        @UrgencyCategory, 
        @TreatmentUnitName,
        @RTProtocol
    )
    
   
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [I_AB_CCM_SystemicDrug](
    @AbstractID int, 
    @DrugOccurrence int,
    @CCORegimen int, 
    @CCODrugCode varchar(10), 
    @CCMDIN varchar(8), 
    @DrugOriginFlag int, 
    @BodySurfaceArea varchar(12), 
    @DoseAdministered varchar(8), 
    @MeasurementUnit int, 
    @Route int, 
    @IntentOfSystemicTreatment int, 
    @LineOfTherapy int,
    @CMIRSeverity int
)
as    
    insert into dbo.AB_CCM_SystemicDrug(
        AbstractID, 
        CCORegimen, 
        CCODrugCode, 
        CCMDIN, 
        DrugOriginFlag, 
        BodySurfaceArea, 
        DoseAdministered, 
        MeasurementUnit, 
        [Route], 
        IntentOfSystemicTreatment, 
        LineOfTherapy, 
        CMIRSeverity,
        Occurrence
    )
    values(
        @AbstractID, 
        @CCORegimen, 
        @CCODrugCode, 
        @CCMDIN, 
        @DrugOriginFlag, 
        @BodySurfaceArea, 
        @DoseAdministered, 
        @MeasurementUnit, 
        @Route, 
        @IntentOfSystemicTreatment, 
        @LineOfTherapy, 
        @CMIRSeverity,
        @DrugOccurrence
    )
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_AB_CMG]
	(@AbstractID 	[int],
	 @OccurrenceNumber 	[int],
	 @CMG_Year 	[int],
	 @ICD_Type 	[varchar](1),
	 @Diagnosis_Code 	[int],
	 @Diagnosis_Type 	[int],
	 @CMG 	[varchar](3),
	 @Complexity 	[varchar](1),
	 @MCC 	[varchar](3),
	 @MCC_Surg	[varchar](1),
	 @AcuteQuartile 	[varchar](1),
	 @CMG_RIW 	[varchar](10),
	 @MOH_RIW 	[varchar](10),
	 @RIW_Dollar 	[money],
	 @MOH_Dollar 	[money],
	 @CMG_ELOS 	[varchar](7),
	 @CMG_Trim 	[varchar](7),
	 @CMG_Description 	[varchar](255))

AS 
declare @Year int
set @year = datepart(year, getdate())

if not exists (select * from AB_cmg where [AbstractID] = @AbstractID and [OccurrenceNumber] = @OccurrenceNumber
                and [CMG_Year] = @CMG_Year) and @CMG_Year <= @year 
INSERT INTO [dbo].[AB_CMG] 
	 ( [AbstractID],
	 [OccurrenceNumber],
	 [CMG_Year],
	 [ICD_Type],
	 [Diagnosis_Code],
	 [Diagnosis_Type],
	 [CMG],
	 [Complexity],
	 [MCC],
	 [MCC_Surg],
	 [AcuteQuartile],
	 [CMG_RIW],
	 [MOH_RIW],
	 [RIW_Dollar],
	 [MOH_Dollar],
	 [CMG_ELOS],
	 [CMG_Trim],
	 [CMG_Description]) 
 
VALUES 
	( @AbstractID,
	 @OccurrenceNumber,
	 @CMG_Year,
	 @ICD_Type,
	 @Diagnosis_Code,
	 @Diagnosis_Type,
	 @CMG,
	 @Complexity,
	 @MCC,
	 @MCC_Surg,
	 @AcuteQuartile,
	 @CMG_RIW,
	 @MOH_RIW,
	 @RIW_Dollar,
	 @MOH_Dollar,
	 @CMG_ELOS,
	 @CMG_Trim,
	 @CMG_Description)

--This Section is for Percentile information.
	Declare @Age as Int  
	Declare @AgeCode as int
	Declare @AgeGroup as int

	select @AgeCode = AgeCode, @Age = AgeNumber from ab_abstract where abstractid = @Abstractid 

	If @Agecode in (1,2) or (@Agecode = 3 and @Age >= 0 and @Age <= 17) 
		Set @AgeGroup = 1   
	Else If @Agecode = 3 and @Age >= 18 and @Age <= 69   
		Set @AgeGroup = 2   
	Else   
		Set @AgeGroup = 3   

	If @CMG_Year = '2002'
		Update ab_CMG set CMGModelType = ModelType, CMGTenthPercent = TenthPercent, CMGTwentyFifthPercent = TwentyFifthPercent, CMGFiftiethPercent = FiftiethPercent
		FROM dbo.CMG_ETC_2002T RIGHT OUTER JOIN
                      dbo.AB_CMG ON dbo.CMG_ETC_2002T.cicpxlvl = dbo.AB_CMG.Complexity AND dbo.CMG_ETC_2002T.cmgcode = dbo.AB_CMG.CMG
		WHERE (dbo.AB_CMG.AbstractID = @AbstractID) AND (dbo.AB_CMG.CMG_Year = 2002) AND (dbo.CMG_ETC_2002T.ciagegroup = @AgeGroup)
	Else If @CMG_Year = '2003'
		Update ab_CMG set CMGModelType = ModelType, CMGTenthPercent = TenthPercent, CMGTwentyFifthPercent = TwentyFifthPercent, CMGFiftiethPercent = FiftiethPercent
		FROM dbo.CMG_ETC_2003T RIGHT OUTER JOIN
                      dbo.AB_CMG ON dbo.CMG_ETC_2003T.cicpxlvl = dbo.AB_CMG.Complexity AND dbo.CMG_ETC_2003T.cmgcode = dbo.AB_CMG.CMG
		WHERE (dbo.AB_CMG.AbstractID = @AbstractID) AND (dbo.AB_CMG.CMG_Year = 2003) AND (dbo.CMG_ETC_2003T.ciagegroup = @AgeGroup)
	Else If @CMG_Year = '2004'
		Update ab_CMG set CMGModelType = ModelType, CMGTenthPercent = TenthPercent, CMGTwentyFifthPercent = TwentyFifthPercent, CMGFiftiethPercent = FiftiethPercent
		FROM dbo.CMG_ETC_2003T RIGHT OUTER JOIN
                      dbo.AB_CMG ON dbo.CMG_ETC_2003T.cicpxlvl = dbo.AB_CMG.Complexity AND dbo.CMG_ETC_2003T.cmgcode = dbo.AB_CMG.CMG
		WHERE (dbo.AB_CMG.AbstractID = @AbstractID) AND (dbo.AB_CMG.CMG_Year = 2004) AND (dbo.CMG_ETC_2003T.ciagegroup = @AgeGroup)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_AB_CMG2007P]
	(@AbstractID 	[int],
	@OccurrenceNumber 	[int],
	@CMG_Year 	[int],
	@ICD_Type 	[varchar](1),
	@Diagnosis_Code 	[int],
	@Diagnosis_Type 	[int],
	@CMG 	[varchar](3),
	@MCC 	[varchar](3),
	@CMG_RIW 	[varchar](10),
	@RIW_Dollar 	[money],
	@CMG_ELOS 	[varchar](7),
	@CMG_Trim 	[varchar](7),
	@CMG_Description 	[varchar](255),
	@CMGAgeCategory [varchar](1), 
	@ComorbidityLevel [varchar](1),  
	@FlaggedIntervFactorCount [varchar](1), 
	@InterventionEventCount [varchar](1),  
	@InterventionOOHCount [varchar](1),  
	@InpatientRIWAtypicalCode [varchar](2), 
	@InpatientRILevel [varchar](1),  
	@IntervCode [int],
    @Partition varchar(1) = null,        --PR-03002
    @CMGTenthPercent varchar(10),        --PR-03062
    @CMGTwentyFifthPercent varchar(10),  --PR-03062
    @CMGFiftiethPercent varchar(10),     --PR-03062
    @FI_CardioversionFlag char(1),          --HDIU
    @FI_CellSaverFlag char(1),              --HDIU
    @FI_ChemotherapyFlag char(1),           --HDIU
    @FI_DialysisFlag char(1),               --HDIU
    @FI_HeartResuscitationFlag char(1),     --HDIU
    @FI_MechanicalVentGreat96Hours char(1), --HDIU
    @FI_MechanicalVentLess96Hours char(1),  --HDIU
    @FI_FeedingTubeFlag char(1),            --HDIU
    @FI_ParacentesisFlag char(1),           --HDIU
    @FI_ParenteralNutritionFlag char(1),    --HDIU
    @FI_PleurocentesisFlag char(1),         --HDIU
    @FI_RadiotherapyFlag char(1),           --HDIU
    @FI_TracheostomyFlag char(1),           --HDIU
    @FI_VascularAccessDdeviceFlag char(1),   --HDIU
    @FI_EndoscopyFlag char(1),   --PR - 04306
    @FI_BiopsyFlag char(1),   --PR - 04306
    @FI_ECMOFlag char(1),   
    @InpatientRITotalFactor varchar(12),   --PR - 04393
    @ComorbidityTotalFactor varchar(10),    --PR - 04393
    @IntervEpisode varchar(10),	--PR - 04607
	@IntervAttStatus varchar(12), --PR - 04607
	@IntervAttLocation varchar(12), --PR - 04607
	@IntervAttExtent varchar(12), --PR - 04607
	@BatchGroupDate varchar(20),
	@MedicalCMG char(3),
    @InpatientTypicalRIW varchar(10),
	@HL_CMG char(3),
	@CMGCareLevel char(1),
	@CMGProviderService varchar(5),
	@CMGProviderServiceGroup char(1),
	@CMGTransplantFlag char(1),

	--EN - 00554  HIGs
	@HIG_Code   varchar(10),
    @HIG_Weight varchar(10),
    @HIG_Description varchar(250),
    @HIG_AgeCategory char(1),    
    @HIG_AtypicalCode char(2),
    @HIG_ELOS  varchar(10),
    @HIG_FI_TotalCount varchar(2),
    @HIG_HomeCareFlag char(1),
    @HIG_MaternalAgeFlag char(1),
    @HIG_PalliativeCareFlag char(1),
    @HIG_OOHFlag char(1),
    @HIG_SCUFlag char(1),
    @HIG_LongStayTrimDays  varchar(10),
    @HIG_ShortStayTrimDays  varchar(10)
) 
AS 
declare @Year int
declare @BatchDate datetime	--EN - 00510
if isdate(@BatchGroupDate) = 1 set @BatchDate = cast(@BatchGroupDate as datetime)

set @year = datepart(year, getdate()) --PR - 05196

declare @IntervEpisodeCode int
if isnumeric(@IntervEpisode) = 1 set @IntervEpisodeCode = cast(@IntervEpisode as int)

if not exists (select * from AB_cmg with(nolock) where [AbstractID] = @AbstractID and [OccurrenceNumber] = @OccurrenceNumber
                and [CMG_Year] = @CMG_Year) and @CMG_Year <= @year
begin
    INSERT INTO [dbo].[AB_CMG] 
    (   [AbstractID],
	    [OccurrenceNumber],
	    [CMG_Year],
	    [ICD_Type],
	    [Diagnosis_Code],
	    [Diagnosis_Type],
	    [CMG],
	    [MCC],
	    [CMG_RIW],
	    [RIW_Dollar],
	    [CMG_ELOS],
	    [CMG_Trim],
	    [CMG_Description],
	    CMGAgeCategory, 
	    ComorbidityLevel, 
	    FlaggedIntervFactorCount, 
	    InterventionEventCount, 
	    InterventionOOHCount, 
	    InpatientRIWAtypicalCode, 
	    InpatientRILevel, 
	    IntervCode,
        CMG_Partition,
        CMGTenthPercent,
        CMGTwentyFifthPercent,
        CMGFiftiethPercent,
        BatchGroupDate
    ) 
     
    VALUES 
    (   @AbstractID,
	    @OccurrenceNumber,
	    @CMG_Year,
	    @ICD_Type,
	    @Diagnosis_Code,
	    @Diagnosis_Type,
	    @CMG,
	    @MCC,
	    @CMG_RIW,
	    @RIW_Dollar,
	    @CMG_ELOS,
	    @CMG_Trim,
	    @CMG_Description,
	    @CMGAgeCategory, 
	    @ComorbidityLevel, 
	    @FlaggedIntervFactorCount, 
	    @InterventionEventCount, 
	    @InterventionOOHCount, 
	    @InpatientRIWAtypicalCode, 
	    @InpatientRILevel, 
	    @IntervCode,
        @Partition,
        @CMGTenthPercent,
        @CMGTwentyFifthPercent,
        @CMGFiftiethPercent,
        @BatchDate) 
        
    if isnumeric(@InpatientTypicalRIW) = 0 set @InpatientTypicalRIW = null
    if @CMG_Year > 2006
        insert into dbo.AB_CMG_FI(AbstractID, OccurrenceNumber, CMG_Year, FI_CardioversionFlag, FI_CellSaverFlag, FI_ChemotherapyFlag, FI_DialysisFlag, FI_HeartResuscitationFlag, 
			FI_MechanicalVentGreat96Hours, FI_MechanicalVentLess96Hours, FI_FeedingTubeFlag, FI_ParacentesisFlag, FI_ParenteralNutritionFlag, FI_PleurocentesisFlag, 
			FI_RadiotherapyFlag, FI_TracheostomyFlag, FI_VascularAccessDdeviceFlag, FI_EndoscopyFlag, FI_BiopsyFlag, InpatientRITotalFactor, ComorbidityTotalFactor, 
			IntervEpisode, IntervAttStatus, IntervAttLocation, IntervAttExtent, FI_ECMOFlag, MedicalCMG, InpatientTypicalRIW,
			HL_CMG, CMGCareLevel, CMGProviderService, CMGProviderServiceGroup, CMGTransplantFlag)
        values(@AbstractID, @OccurrenceNumber, @CMG_Year, @FI_CardioversionFlag, @FI_CellSaverFlag, @FI_ChemotherapyFlag, @FI_DialysisFlag, @FI_HeartResuscitationFlag, 
			@FI_MechanicalVentGreat96Hours, @FI_MechanicalVentLess96Hours, @FI_FeedingTubeFlag, @FI_ParacentesisFlag, @FI_ParenteralNutritionFlag, @FI_PleurocentesisFlag, 
			@FI_RadiotherapyFlag, @FI_TracheostomyFlag, @FI_VascularAccessDdeviceFlag, @FI_EndoscopyFlag, @FI_BiopsyFlag, @InpatientRITotalFactor, @ComorbidityTotalFactor, 
			@IntervEpisodeCode, @IntervAttStatus, @IntervAttLocation, @IntervAttExtent, @FI_ECMOFlag, @MedicalCMG, @InpatientTypicalRIW,
			@HL_CMG, @CMGCareLevel, @CMGProviderService, @CMGProviderServiceGroup, @CMGTransplantFlag)
end

--EN - 00554
if @CMG_Year >= 2012 and isnull(@HIG_Code, '') <> ''
begin
    if isnumeric(@HIG_Weight) = 0 set @HIG_Weight = null
    if isnumeric(@HIG_ELOS) = 0 set @HIG_ELOS = null
    if isnumeric(@HIG_LongStayTrimDays) = 0 set @HIG_LongStayTrimDays = 0
    if isnumeric(@HIG_ShortStayTrimDays) = 0 set @HIG_ShortStayTrimDays = 0
    if not exists (select * from AB_HIG with(nolock) where [AbstractID] = @AbstractID and [OccurrenceNumber] = @OccurrenceNumber
                and GrouperYear = @CMG_Year and isnull(IsFixed, 0) <> 1) and @CMG_Year <= @year
        insert into dbo.AB_HIG(AbstractID, OccurrenceNumber, GrouperYear, HIG_Code, HIG_Weight, HIG_Description, HIG_AgeCategory, HIG_AtypicalCode, HIG_ELOS,
            HIG_FI_TotalCount, HIG_HomeCareFlag, HIG_MaternalAgeFlag, HIG_PalliativeCareFlag, HIG_OOHFlag, HIG_SCUFlag, HIG_LongStayTrimDays, HIG_ShortStayTrimDays)
        values(@AbstractID, @OccurrenceNumber, @CMG_Year, @HIG_Code, @HIG_Weight, @HIG_Description, @HIG_AgeCategory, @HIG_AtypicalCode, @HIG_ELOS,
            @HIG_FI_TotalCount, @HIG_HomeCareFlag, @HIG_MaternalAgeFlag, @HIG_PalliativeCareFlag, @HIG_OOHFlag, @HIG_SCUFlag, 
            @HIG_LongStayTrimDays, @HIG_ShortStayTrimDays)
end
--QA - 00035 For Audit
declare @OldValue varchar(100)
if @OccurrenceNumber = 1 and @CMG_Year > 2013
begin
    set @OldValue = dbo.GetGrouperAuditValue(@AbstractID, @CMG_Year, 'CMG')
    if isnull(@OldValue, '') <> @CMG
        insert into dbo.AB_GrouperAudit(AbstractID, GroupingYear, FieldChanged, OldValue, NewValue, DateGrouped)
        select @AbstractID, @CMG_Year, 'CMG', @OldValue, @CMG, getdate()
        
    set @OldValue = dbo.GetGrouperAuditValue(@AbstractID, @CMG_Year, 'MCC')
    if isnull(@OldValue, '') <> @MCC
        insert into dbo.AB_GrouperAudit(AbstractID, GroupingYear, FieldChanged, OldValue, NewValue, DateGrouped)
        select @AbstractID, @CMG_Year, 'MCC', @OldValue, @MCC, getdate()
        
    set @OldValue = dbo.GetGrouperAuditValue(@AbstractID, @CMG_Year, 'RIW')
    if isnull(@OldValue, '') <> @CMG_RIW
        insert into dbo.AB_GrouperAudit(AbstractID, GroupingYear, FieldChanged, OldValue, NewValue, DateGrouped)
        select @AbstractID, @CMG_Year, 'RIW', @OldValue, @CMG_RIW, getdate()
    
    if @CMG_Year >= 2012 and isnull(@HIG_Code, '') <> ''
    begin
        set @OldValue = dbo.GetGrouperAuditValue(@AbstractID, @CMG_Year, 'HIG')
        if isnull(@OldValue, '') <> @HIG_Code
            insert into dbo.AB_GrouperAudit(AbstractID, GroupingYear, FieldChanged, OldValue, NewValue, DateGrouped)
            select @AbstractID, @CMG_Year, 'HIG', @OldValue, @HIG_Code, getdate()

        set @OldValue = dbo.GetGrouperAuditValue(@AbstractID, @CMG_Year, 'HIGRIW')
        if isnull(@OldValue, '') <> @HIG_Weight
            insert into dbo.AB_GrouperAudit(AbstractID, GroupingYear, FieldChanged, OldValue, NewValue, DateGrouped)
            select @AbstractID, @CMG_Year, 'HIGRIW', @OldValue, @HIG_Weight, getdate()
    end
end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_AB_Consult](
    @AbstractID	 	[int],
	@Occurrence 	[int],
	@ConsultNumber		[int],
	@ConsultService 	[int],
	@ConsultRequestDate	 datetime,
	@ConsultRequestTime 	datetime,
	@ConsultRequestTimeUnknown		[int],
	@ConsultArrivalDate	 datetime,
	@ConsultArrivalTime 	datetime,
	@ConsultArrivalTimeUnknown		[int]
)
AS 
--NP - 00151
INSERT INTO [AB_Consult] 
	 (AbstractID,
	Occurrence,
	ConsultNumber,
	ConsultService,
	ConsultRequestDate,
	ConsultRequestTime,
	ConsultRequestTimeUnknown,
	ConsultArrivalDate,
	ConsultArrivalTime,
	ConsultArrivalTimeUnknown) 
 
VALUES 
	(@AbstractID,
	@Occurrence,
	@ConsultNumber,
	@ConsultService,
	@ConsultRequestDate,
	@ConsultRequestTime,
	@ConsultRequestTimeUnknown,
	@ConsultArrivalDate,
	@ConsultArrivalTime,
	@ConsultArrivalTimeUnknown)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [I_AB_DeathInformation]
	(@AbstractID	 	[int],
	 @AutopsyPerformed 	[int],
	 @CoronerCase	 	[int],
	 @DeathInSCU	 	[int],
	 @DeathInOR	 	[int],
	 @DeathLessTwoPO 	[int],
	 @DeathTwoTenPO 	[int],
	 @DeathGreaterTenPO 	[int],
	 @DeathAfterAdmit 	[int],
	 @DeathOnArrival 	[int],
	 @DeathInER	 	[int],
	 @TraumaDeath 	[int],
	 @PregnancyDeath 	[int],
	 @OtherDeath	 	[int])
AS 

INSERT INTO [AB_DeathInformation] 
	 ([AbstractID],
	 [AutopsyPerformed],
	 [CoronerCase],
	 [DeathInSCU],
	 [DeathInOR],
	 [DeathLessTwoPO],
	 [DeathTwoTenPO],
	 [DeathGreaterTenPO],
	 [DeathAfterAdmit],
	 [DeathOnArrival],
	 [DeathInER],
	 [TraumaDeath],
	 [PregnancyDeath],
	 [OtherDeath]) 
 
VALUES 
	(@AbstractID,
	 @AutopsyPerformed,
	 @CoronerCase,
	 @DeathInSCU,
	 @DeathInOR,
	 @DeathLessTwoPO,
	 @DeathTwoTenPO,
	 @DeathGreaterTenPO,
	 @DeathAfterAdmit,
	 @DeathOnArrival,
	 @DeathInER,
	 @TraumaDeath,
	 @PregnancyDeath,
	 @OtherDeath)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_AB_Diagnosis]
	(@AbstractID 		[int],
	 @DiagnosisICDType	[varchar](1),
	 @DiagnosisOccurrence	[int],
	 @DiagnosisPrefix 	[int],
	 @DiagnosisCode 	[int],
	 @DiagnosisSuffix 	[int],
	 @DiagnosisType 	[int],
	 @ProvinceDiagCode 	[int], 
	 @ServiceCode 		[int], 
	 @ServiceSuffix 	[varchar](50),
     @DiagnosisCluster  char(1))
AS 

INSERT INTO [AB_Diagnosis] 
	 ([AbstractID],
	 [DiagnosisOccurrence],
	 [DiagnosisICDType],
	 [DiagnosisPrefix],
	 [DiagnosisCode],
	 [DiagnosisSuffix],
	 [DiagnosisType],
	 [ProvinceDiagCode], 
	 [ServiceCode], 
	 [ServiceSuffix],
     [DiagnosisCluster]) 
 
VALUES 
	(@AbstractID,
	 @DiagnosisOccurrence,
	 @DiagnosisICDType,
	 @DiagnosisPrefix,
	 @DiagnosisCode,
	 @DiagnosisSuffix,
	 @DiagnosisType,
	 @ProvinceDiagCode, 
	 @ServiceCode, 
	 @ServiceSuffix,
     @DiagnosisCluster)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_AB_Diagnosis_CodeSmart]
	(@AbstractID	 	[int],
	 @cSDiagnosisOccurrence	 	[int],
	 @cSDiagnosisText 	[varchar] (8000))

AS 
insert into [dbo].AB_Diagnosis_CodeSmart 
	 ( [AbstractID],
	 cSDiagnosisOccurrence,
	 cSDiagnosisText) 
 
values
	( @AbstractID,
	 @cSDiagnosisOccurrence,
	 @cSDiagnosisText)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [I_AB_DischargeDiagnosis]
	(@AbstractID	 	[int],
	 @Occurrence	 	[int],
	 @DischargeDiagnosis 	[int])

AS 
insert into [dbo].[AB_DischargeDiagnosis] 
	 ( [AbstractID],
	 [Occurrence],
	 [DischargeDiagnosis]) 
 
values
	( @AbstractID,
	 @Occurrence,
	 @DischargeDiagnosis)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [I_AB_DPG]
	(@AbstractID 		[int],
	 @OccurrenceNumber 	[int],
	 @DPG_Year 		[int],
	 @DPG 		[varchar](6),
	 @DPG_RIW 		[decimal](8,4),
	 @DPG_MOH_RIW 	[decimal](8,4),
	 @DPG_Description 	[varchar](255),
	 @InterventionCode	[int])
AS 

declare @Year int
set @year = datepart(year, getdate()) --PR - 05196

if not exists (select * from [AB_DPG] where [AbstractID] = @AbstractID and [OccurrenceNumber] = @OccurrenceNumber
                and [DPG_Year] = @DPG_Year) and @DPG_Year <= @year

    INSERT INTO [dbo].[AB_DPG] 
	     ([AbstractID],
	     [OccurrenceNumber],
	     [DPG_Year],
	     [DPG],
	     [DPG_RIW],
	     [DPG_MOH_RIW],
	     [DPG_Description],
	     [InterventionCode]) 
     
    VALUES 
	    (@AbstractID,
	     @OccurrenceNumber,
	     @DPG_Year,
	     @DPG,
	     @DPG_RIW,
	     @DPG_MOH_RIW,
	     @DPG_Description,
	     @InterventionCode)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [I_AB_EDInterventionPicklist](
	@AbstractID int,
	@Occurrence int,
	@EDInterventionPickList int)
as
	Insert into [dbo].[AB_EDInterventionPicklist](
	[AbstractID],
	[Occurrence],
	[EDInterventionPickList])
	values(	
	@AbstractID,
	@Occurrence,
	@EDInterventionPickList
	)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create procedure [I_AB_EDInterventionValueSet]
	@AbstractID [int],
	@Occurrence [int],
	@EDInterventionValueSet int,
	@NumberEDInvestigativeTechnologiesPerformed int
as
	insert into AB_EDInterventionValueSet([AbstractID], [Occurrence], [EDInterventionValueSet], [NumberEDInvestigativeTechnologiesPerformed])
	values(@AbstractID, @Occurrence, @EDInterventionValueSet, @NumberEDInvestigativeTechnologiesPerformed)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE  PROCEDURE [I_AB_History] 
	@AbstractID as int,
	@Coder as int,
	@UpdateType as varchar(10) = 'Saved'
AS 

declare @HID as int --NP-00025
select @HID = HospitalID from U_Users where Code = @Coder
insert into AB_UpdateHistory (AbstractID, HospitalID, Coder, Updated, UpdateType) Values (@AbstractID, @HID, @Coder, GetDate(), @UpdateType) --'Saved')



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_AB_Intervention]
	(@AbstractID	 		[int],
	 @IntervICDType 		[varchar](1),
	 @IntervOccurrence 		[int],
	 @IntervDate	 		[datetime],
	 @IntervCode	 		[int],
	 @IntervSuffix	 		[int],
	 @IntervAttribStatus 		[int],
	 @IntervAttribLocation 		[int],
	 @IntervAttribExtent 		[int],
	 @IntervEUL	 		[int],
	 @IntervExtra	 		[int],
	 @IntervOOHIndicator 		[int],
	 @IntervOOHInstitution 		[int],
	 @IntervProviderNumber		[int],
	 @IntervProviderService 		[int],
	 @IntervTissueCode 		[int],
	 @IntervDateIn			[datetime],
	 @IntervTimeIn	 		[datetime],
	 @IntervDateOut 		[datetime],
	 @IntervTimeOut 		[datetime],
	 @IntervTimeMinutes 		[varchar](10),
	 @IntervLocation 		[int],
	 @IntervAnaestID 		[int],
	 @IntervAnaestTechnique	[int],
	 @IntervUnplanReturn		[int],
     @IntervTripNumber      int,
     @IntervPreAdmitFlag    int,
     @IntervTimeInUnknown   int,
     @IntervTimeOutUnknown  int,
     @FlaggedIntervention   int,
     @ORURN                 int = null,
     @IntervJointIdentifier int = null,
     @IntervRevisionReason  int = null,
	 @IntervComments        varchar(1000)
)
AS 

INSERT INTO [AB_Intervention] 
	 ([AbstractID],
	 [IntervOccurrence],
	 [IntervICDType],
	 [IntervDate],
	 [IntervCode],
	 [IntervSuffix],
	 [IntervAttribStatus],
	 [IntervAttribLocation],
	 [IntervAttribExtent],
	 [IntervEUL],
	 [IntervExtra],
	 [IntervOOHIndicator],
	 [IntervOOHInstitution],
	 [IntervProviderNumber],
	 [IntervProviderService],
	 [IntervTissueCode],
	 [IntervDateIn],
	 [IntervTimeIn],
	 [IntervDateOut],
	 [IntervTimeOut],
	 [IntervTimeMinutes],
	 [IntervLocation],
	 [IntervAnaestID],
	 [IntervAnaestTechnique],
	 [IntervUnplanReturn],
     [IntervTripNumber],
     [IntervPreAdmitFlag],
     [IntervTimeInUnknown],
     [IntervTimeOutUnknown],
     [FlaggedIntervention],
     [ORURN],
     [IntervJointIdentifier],
     [IntervRevisionReason],
	 [IntervComments]
) 
VALUES 
	(@AbstractID,
	 @IntervOccurrence,
	 @IntervICDType,
	 @IntervDate,
	 @IntervCode,
	 @IntervSuffix,
	 @IntervAttribStatus,
	 @IntervAttribLocation,
	 @IntervAttribExtent,
	 @IntervEUL,
	 @IntervExtra,
	 @IntervOOHIndicator,
	 @IntervOOHInstitution,
	 @IntervProviderNumber,
	 @IntervProviderService,
	 @IntervTissueCode,
	 @IntervDateIn,
	 @IntervTimeIn,
	 @IntervDateOut,
	 @IntervTimeOut,
	 @IntervTimeMinutes,
	 @IntervLocation,
	 @IntervAnaestID,
	 @IntervAnaestTechnique,
	 @IntervUnplanReturn,
     @IntervTripNumber,
     @IntervPreAdmitFlag,
     @IntervTimeInUnknown,
     @IntervTimeOutUnknown,
     @FlaggedIntervention,
     @ORURN,
     @IntervJointIdentifier,
     @IntervRevisionReason,
	 @IntervComments
)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_AB_Intervention_CodeSmart]
	(@AbstractID	 	[int],
	 @cSInterventionOccurrence	 	[int],
	 @cSInterventionText 	[varchar] (8000))

AS 
insert into [dbo].AB_Intervention_CodeSmart 
	 ( [AbstractID],
	 cSInterventionOccurrence,
	 cSInterventionText) 
 
values
	( @AbstractID,
	 @cSInterventionOccurrence,
	 @cSInterventionText)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [I_AB_Intervention_Replicate]
	@AbstractID int
as
	Delete from AB_Intervention_Replicate where AbstractID = @AbstractID
	
	declare @Replicate table(
		[AbstractID] [int],
		[IntervOccurrence] [int],
		[IntervDate] [datetime] ,
		[IntervCode] [int] ,
		[IntervSuffix] [int] ,
		[IntervAttribStatus] [int] ,
		[IntervAttribLocation] [int] ,
		[IntervAttribExtent] [int] ,
		[IntervEUL] [int] ,
		[IntervExtra] [int] ,
		[IntervOOHIndicator] [int] ,
		[IntervOOHInstitution] [int] ,
		[IntervProviderNumber] [int] ,
		[IntervProviderService] [int] ,
		[IntervTissueCode] [int] ,
		[IntervDateIn] [datetime] ,
		[IntervTimeIn] [datetime] ,
		[IntervDateOut] [datetime] ,
		[IntervTimeOut] [datetime] ,
		[IntervTimeMinutes] [int] ,
		[IntervLocation] [int] ,
		[IntervAnaestID] [int] ,
		[IntervAnaestTechnique] [int] ,
		[IntervUnplanReturn] [int] ,
		[IntervTripNumber] [int] ,
		[IntervPreAdmitFlag] [int] ,
		[IntervTimeInUnknown] [int] ,
		[IntervTimeOutUnknown] [int],
		[FlaggedIntervention] [int],
		[ORURN]               [int],
        [IntervJointIdentifier] [int],
        [IntervRevisionReason]  [int]
    )

	insert into @Replicate(AbstractID, IntervOccurrence, IntervDate, IntervCode, IntervSuffix, IntervAttribStatus, IntervAttribLocation, IntervAttribExtent, IntervEUL, IntervExtra, IntervOOHIndicator, IntervOOHInstitution, IntervProviderNumber, IntervProviderService, IntervTissueCode, IntervDateIn, IntervTimeIn, IntervDateOut, IntervTimeOut, IntervTimeMinutes, IntervLocation, IntervAnaestID, IntervAnaestTechnique, IntervUnplanReturn, IntervTripNumber, IntervPreAdmitFlag, IntervTimeInUnknown, IntervTimeOutUnknown, FlaggedIntervention, ORURN, IntervJointIdentifier, IntervRevisionReason)		
	select AbstractID, IntervOccurrence, IntervDate, IntervCode, IntervSuffix, IntervAttribStatus, IntervAttribLocation, IntervAttribExtent, IntervEUL, IntervExtra, IntervOOHIndicator, IntervOOHInstitution, IntervProviderNumber, IntervProviderService, IntervTissueCode, IntervDateIn, IntervTimeIn, IntervDateOut, IntervTimeOut, IntervTimeMinutes, IntervLocation, IntervAnaestID, IntervAnaestTechnique, IntervUnplanReturn, IntervTripNumber, IntervPreAdmitFlag, IntervTimeInUnknown, IntervTimeOutUnknown, FlaggedIntervention, ORURN, IntervJointIdentifier, IntervRevisionReason
	from AB_Intervention
	where AbstractID = @AbstractID
	order by IntervOccurrence
	--20864 Add Intervention Code and Attributes
	Update @Replicate
	set IntervCode = R.IntervCode,
        IntervAttribStatus = r.IntervAttribStatus,
        IntervAttribLocation = r.IntervAttribLocation,
        IntervAttribExtent = r.IntervAttribExtent,
        IntervJointIdentifier = r.IntervJointIdentifier,
        IntervRevisionReason = r.IntervRevisionReason
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervCode, p.IntervAttribStatus, p.IntervAttribLocation, p.IntervAttribExtent, p.IntervJointIdentifier, p.IntervRevisionReason
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervCode > 0) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervCode, 0) <> isnull(R.IntervCode, 0)    

	--IntervSuffix
	Update @Replicate
	set IntervSuffix = R.IntervSuffix
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervSuffix
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervSuffix > 0) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervSuffix, 0) <> isnull(R.IntervSuffix, 0)

	--IntervEUL
	Update @Replicate
	set IntervEUL = R.IntervEUL
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervEUL
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervEUL > 0) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervEUL, 0) <> isnull(R.IntervEUL, 0)
	
	--IntervExtra
	Update @Replicate
	set IntervExtra = R.IntervExtra
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervExtra
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervExtra > 0) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervExtra, 0) <> isnull(R.IntervExtra, 0)

	--IntervOOHIndicator
	Update @Replicate
	set IntervOOHIndicator = R.IntervOOHIndicator
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervOOHIndicator
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervOOHIndicator > 0) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervOOHIndicator, 0) <> isnull(R.IntervOOHIndicator, 0)

	--IntervOOHInstitution
	Update @Replicate
	set IntervOOHInstitution = R.IntervOOHInstitution
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervOOHInstitution
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervOOHInstitution > 0) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervOOHInstitution, 0) <> isnull(R.IntervOOHInstitution, 0)
	
	--IntervProviderNumber
	Update @Replicate
	set IntervProviderNumber = R.IntervProviderNumber
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervProviderNumber
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervProviderNumber > 0) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervProviderNumber, 0) <> isnull(R.IntervProviderNumber, 0)

	--IntervProviderService
	Update @Replicate
	set IntervProviderService = R.IntervProviderService
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervProviderService
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervProviderService > 0) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervProviderService, 0) <> isnull(R.IntervProviderService, 0)

	--IntervTissueCode
	Update @Replicate
	set IntervTissueCode = R.IntervTissueCode
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervTissueCode
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervTissueCode > 0) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervTissueCode, 0) <> isnull(R.IntervTissueCode, 0)

	--IntervDateIn
	Update @Replicate
	set IntervDateIn = R.IntervDateIn
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervDateIn
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervDateIn > 0) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervDateIn, 0) <> isnull(R.IntervDateIn, 0)

	--IntervTimeIn
	Update @Replicate
	set IntervTimeIn = R.IntervTimeIn
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervTimeIn
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervTimeIn is not null) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervTimeIn, '1950/01/01') <> isnull(R.IntervTimeIn, '1950/01/01')
	
	--IntervDateOut
		Update @Replicate
	set IntervDateOut = R.IntervDateOut
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervDateOut
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervDateOut is not null) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervDateOut, '1950/01/01') <> isnull(R.IntervDateOut, '1950/01/01')

	--IntervTimeOut
	Update @Replicate
	set IntervTimeOut = R.IntervTimeOut
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervTimeOut
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervTimeOut is not null) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervTimeOut, 0) <> isnull(R.IntervTimeOut, 0)
								
	--IntervTimeMinutes
	Update @Replicate
	set IntervTimeMinutes = R.IntervTimeMinutes
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervTimeMinutes
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervTimeMinutes > 0) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervTimeMinutes, 0) <> isnull(R.IntervTimeMinutes, 0)

	--IntervLocation
	Update @Replicate
	set IntervLocation = R.IntervLocation
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervLocation
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervLocation > 0) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervLocation, 0) <> isnull(R.IntervLocation, 0)

	--IntervAnaestID
	Update @Replicate
	set IntervAnaestID = R.IntervAnaestID
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervAnaestID
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervAnaestID > 0) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervAnaestID, 0) <> isnull(R.IntervAnaestID, 0)

	--IntervAnaestTechnique
	Update @Replicate
	set IntervAnaestTechnique = R.IntervAnaestTechnique
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervAnaestTechnique
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervAnaestTechnique > 0) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervAnaestTechnique, 0) <> isnull(R.IntervAnaestTechnique, 0)

	--IntervUnplanReturn
	Update @Replicate
	set IntervUnplanReturn = R.IntervUnplanReturn
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervUnplanReturn
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervUnplanReturn > 0) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervUnplanReturn, 0) <> isnull(R.IntervUnplanReturn, 0)

	--IntervTripNumber	
	Update @Replicate
	set IntervTripNumber = R.IntervTripNumber
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervTripNumber
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervTripNumber > 0) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervTripNumber, 0) <> isnull(R.IntervTripNumber, 0)
	
	--IntervPreAdmitFlag
		Update @Replicate
	set IntervPreAdmitFlag = R.IntervPreAdmitFlag
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervPreAdmitFlag
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervPreAdmitFlag > 0) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervPreAdmitFlag, 0) <> isnull(R.IntervPreAdmitFlag, 0)

	--IntervTimeInUnknown
	Update @Replicate
	set IntervTimeInUnknown = R.IntervTimeInUnknown
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervTimeInUnknown
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervTimeInUnknown > 0) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervTimeInUnknown, 0) <> isnull(R.IntervTimeInUnknown, 0)

	--IntervTimeOutUnknown
	Update @Replicate
	set IntervTimeOutUnknown = R.IntervTimeOutUnknown
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervTimeOutUnknown
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A  inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervTimeOutUnknown > 0) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervTimeOutUnknown, 0) <> isnull(R.IntervTimeOutUnknown, 0)

	--IntervDate
	Update @Replicate
	set IntervDate = R.IntervDate
	from  @Replicate AB
		inner join
		(select  p.AbstractID, v.IntervOccurrence, p.IntervDate
		 from @Replicate p inner join
			(select A.AbstractID, A.IntervOccurrence, min((case when P.IntervOccurrence is null then MinOcc else A.IntervOccurrence - P.IntervOccurrence end)) as MinOcc
			from @Replicate A inner join (
				SELECT     s.AbstractID, S.IntervOccurrence, MIN(S.IntervOccurrence - T.IntervOccurrence) AS MinOcc
				FROM  @Replicate s  INNER JOIN
				   (SELECT     AbstractID, IntervOccurrence
					 FROM          @Replicate 
					 WHERE      IntervDate IS NOT NULL or IntervOccurrence = 1) T ON S.AbstractID = T.AbstractID AND S.IntervOccurrence >= T.IntervOccurrence
				GROUP BY S.AbstractID, S.IntervOccurrence) InterventionEpisode_VR
					on A.AbstractID = InterventionEpisode_VR.AbstractID and A.IntervOccurrence = InterventionEpisode_VR.IntervOccurrence
				left join (select AbstractID, IntervOccurrence from @Replicate  where IntervDate is null and IntervDate is not null) P
					on A.AbstractID = P.AbstractID 
						and (P.IntervOccurrence >= InterventionEpisode_VR.IntervOccurrence - InterventionEpisode_VR.MinOcc) 
						and A.IntervOccurrence >= P.IntervOccurrence
			group by A.AbstractID, A.IntervOccurrence) v 
		on p.AbstractID = v.AbstractID and p.IntervOccurrence = v.IntervOccurrence - v.MinOcc
		) R on AB.AbstractID = R.AbstractID and AB.IntervOccurrence = R.IntervOccurrence
	where isnull(AB.IntervDate, '1950/01/01') <> isnull(R.IntervDate, '1950/01/01')
			
	insert into AB_Intervention_Replicate(AbstractID, IntervOccurrence, IntervDate, IntervCode, IntervSuffix, IntervAttribStatus, IntervAttribLocation, IntervAttribExtent, IntervEUL, IntervExtra, IntervOOHIndicator, IntervOOHInstitution, IntervProviderNumber, IntervProviderService, IntervTissueCode, IntervDateIn, IntervTimeIn, IntervDateOut, IntervTimeOut, IntervTimeMinutes, IntervLocation, IntervAnaestID, IntervAnaestTechnique, IntervUnplanReturn, IntervTripNumber, IntervPreAdmitFlag, IntervTimeInUnknown, IntervTimeOutUnknown, FlaggedIntervention, ORURN, IntervJointIdentifier, IntervRevisionReason)
	select AbstractID, IntervOccurrence, IntervDate, IntervCode, IntervSuffix, IntervAttribStatus, IntervAttribLocation, IntervAttribExtent, IntervEUL, IntervExtra, IntervOOHIndicator, IntervOOHInstitution, IntervProviderNumber, IntervProviderService, IntervTissueCode, IntervDateIn, IntervTimeIn, IntervDateOut, IntervTimeOut, IntervTimeMinutes, IntervLocation, IntervAnaestID, IntervAnaestTechnique, IntervUnplanReturn, IntervTripNumber, IntervPreAdmitFlag, IntervTimeInUnknown, IntervTimeOutUnknown, FlaggedIntervention, ORURN, IntervJointIdentifier, IntervRevisionReason
	from @Replicate 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [I_AB_InvestigativeTechnology](
	@AbstractID [int],
	@Occurrence [int],
	@InvestigativeTechnology [int],
	@NumberInvestigativeTechnologyPerformed [int]
)
as
	insert into [dbo].[AB_InvestigativeTechnology](
	[AbstractID],
	[Occurrence],
	[InvestigativeTechnology],
	[NumberInvestigativeTechnologyPerformed]
	)
	values(
	@AbstractID,
	@Occurrence,
	@InvestigativeTechnology,
	@NumberInvestigativeTechnologyPerformed
)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE      PROCEDURE [I_AB_Main]
	(@UniversalID 	[bigint],
	 @ChartNumber 	[varchar](10),
	 @LastName 	[varchar](40),
	 @FirstName 	[varchar](35),
	 @MiddleName 	[varchar](15),
	 @MaidenName 	[varchar](35),
	 @Gender 	[int],
	 @Birthdate 	[datetime],
	 @HealthCareNumber 	[varchar](12),
	 @AdmitDate 	[datetime],
	 @AdmitTime 	[datetime],
	 @DischargeDate 	[datetime],
	 @DischargeTime 	[datetime],
	 @EncounterNumber 	[varchar](20),
	 @EncounterSequence 	[int],
	 @RegisterNumber 	[varchar](8),
	 @SecondChartRegNumber 	[varchar](10),
	 @MISCode 	[int],
	 @HasTrans	[int],
	 @HasDas	[int],
	 @IsDeleted 	[int],
	 @AdmittingNurseArea [int], 
	 @AttendingPhysician [int], 
	 @RefPhysician [int], 
	 @DiagnosisCode [int], 
	 @IntervCode [int],
	 @PatientType [int],
	 @HospitalID [int],
	 @VisitDate  [datetime],
	 @VisitTime  [datetime],
	 @RegionalPatientID [varchar](20),	--PR - 05538
	 @FixedChartNumber [varchar](50),
	 @UniversalEpisodeIdentifier varchar(50),
     @HospitalAccountRecord varchar(50)
)
AS 
	declare @AppType as int
	declare @AppID as int
	declare @DeathIndicator as int
	declare @DeathDate as datetime
	declare @Patientid as int
	declare @Volumeid as int

	set @AppType = 9
	set @AppID = 3
	if isnull(@IsDeleted, 0) = 0 set @IsDeleted = 2   -- PR - 03723
	if isdate(@VisitDate) = 0 set @VisitDate = isnull(@DischargeDate, @AdmitDate)
	if isdate(@VisitTime) = 0 set @VisitTime = isnull(@DischargeTime, @AdmitTime)
	
	select @DeathIndicator = DeathIndicator, @PatientID = PatientID, @VolumeID = VolumeID from AB_Main where (UniversalID = @UniversalID)	
	if @PatientID is null --If new Visit
	begin
		select @PatientID = PatientID, @DeathDate = DeathDate from CM_CPI where ChartNumber = @ChartNumber and Hospitalid = 0
		if @DeathDate > '1900/01/01'
			set @DeathIndicator = 1
	end

	if isnull(@UniversalID, 0) = 0
		select @UniversalID = (select isnull(max(UniversalID), 0) from AB_Main) + 1
	else
		delete AB_Main where UniversalID = @UniversalID

	insert into [AB_Main] (
		 [UniversalID],
		 [HospitalID],
		 [IsDeleted],
		 [AppType],
		 [AppID],
		 [ChartNumber],
		 [LastName],
		 [FirstName],
		 [MiddleName],
		 [MaidenName],
		 [Birthdate],
		 [VisitDate],
		 [VisitTime],
		 [AdmitDate],
		 [AdmitTime],
		 [DischargeDate],
		 [DischargeTime],
		 [EncounterNumber],
		 [EncounterSequence],
		 [RegisterNumber],
		 [HealthCareNumber],
		 [SecondChartRegNumber],
		 [MISCode],
		 [Gender],
		 [DeathIndicator],
		 [VolumeID],
		 [PatientID],
		 [AdmittingNurseArea], 
		 [AttendingPhysician], 
		 [RefPhysician], 
		 [DiagnosisCode], 
		 [IntervCode],
		 [PatientType],
		 [RegionalPatientID],
		 [FixedChartNumber],
		 [UniversalEpisodeIdentifier],
         [HospitalAccountRecord]
	)values (
		 @UniversalID,
		 @HospitalID,
		 @IsDeleted,
		 @AppType,
		 @AppID,
		 @ChartNumber,
		 @LastName,
		 @FirstName,
		 @MiddleName,
		 @MaidenName,
		 @Birthdate,
		 @VisitDate,
		 @VisitTime,
		 @AdmitDate,
		 @AdmitTime,
		 @DischargeDate,
		 @DischargeTime,
		 @EncounterNumber,
		 @EncounterSequence,
		 @RegisterNumber,
		 @HealthCareNumber,
		 @SecondChartRegNumber,
		 @MISCode,
		 @Gender,
		 @DeathIndicator,
		 @VolumeID,
		 @PatientID,
		 @AdmittingNurseArea, 
		 @AttendingPhysician, 
		 @RefPhysician, 
		 @DiagnosisCode, 
		 @IntervCode,
		 @PatientType,
		 @RegionalPatientID,
		 @FixedChartNumber,
		 @UniversalEpisodeIdentifier,
         @HospitalAccountRecord
	)
	
	/*Update CPI*/
	exec U_CM_CPIFromVisit 9, @AdmitDate, @DischargeDate, @ChartNumber, '', '', @MaidenName, @LastName, @MiddleName, @FirstName,  @BirthDate, '', @Gender,  '', '', @HealthCareNumber,  '', '', '', '', '', '', '',  '', '', '', '', ''
    
    	--EN-00183
    	if @PatientID > 0
        	update CM_CPI set LastVisitDate = isnull(@DischargeDate, @AdmitDate)
        	where PatientID = @PatientID and (LastVisitDate is null or LastVisitDate < isnull(@DischargeDate, @AdmitDate))
    
    	--EN - 00369
    	declare @v_UID bigint, @v_VisitDate datetime 
    	if isnull(@VolumeID, 0) > 0
    	begin
        	set @v_UID = (select top 1 UniversalID from cm_cpi_volume where volumeID = @VolumeID)
        	if isnull(@v_UID, 0) <> @UniversalID
        	begin
            		select top 1 @v_VisitDate = isnull(DischargeDate, AdmitDate) 
            		from ab_main
            		where UniversalID = @v_UID

            		if @v_VisitDate > isnull(@DischargeDate, @AdmitDate)
                		update CM_CPI_Volume set UniversalID = @UniversalID where VolumeID = @VolumeID
        	end        
    	end

	return @UniversalID
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE  PROCEDURE [I_AB_MainHistory] 
	@AbstractID as int,
	@Coder as int,
	@UpdateType as varchar(10) = 'Saved'
AS 

declare @HID as int --NP-00025
select @HID = HospitalID from U_Users where Code = @Coder

insert into AB_MainHistory (AbstractID, HospitalID, Coder, Updated, UpdateType) Values (@AbstractID, @HID, @Coder, GetDate(), @UpdateType) --'Saved')



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [I_AB_Manitoba]
	(@AbstractID 			[int],
	 @AbstractType 		[int],
	 @PreviousName 		[varchar](50),
	 @PrimaryPhone 		[varchar](20),
	 @PrimaryAddress 		[varchar](60),
	 @PrimaryAddress2 		[varchar](60),
	 @EmployerName 		[varchar](50),
	 @RegistrantLastName 		[varchar](50),
	 @RegistrantFirstName 		[varchar](50),
	 @DeclarationNumber 		[varchar](50),
	 @MHInstFrom			[int],
	 @MHInstTo	 		[int],
	 @AnestheticLabor		[int],
	 @PrenatalVisitDate 		[datetime],
	 @NumberPrenatalVisits 		[int],
	 @Gravida	 		[int],
	 @Parity	 		[int],
	 @ObsEducation 		[int],
	 @SmokingPerDay 		[int],
	 @SmokingQuitDate 		[datetime],
	 @AlcoholDuringPregnancy 	[int],
	 @Days_WeekAlcoholConsumed	[int],
	 @DrinksPerday		 	[int],
	 @PreConceptionalFolicAcid 	[int],
	 @PostConceptionalFolicAcid 	[int],
	 @FirstStageDate	 	[datetime],
	 @FirstStageTime		[datetime],
	 @FirstStageDuration	 	[varchar](10),
	 @SecondStageDate	 	[datetime],
	 @SecondStageTime	 	[datetime],
	 @SecondStageDuration 	[varchar](10),
	 @Presentation			[int],
	 @RoutineCare			[int],
	 @FreeFlowOxygen		[int],
	 @BagVentilation		[int],
	 @IntubationNotMeconium 	[int],
	 @MedicationResuscitation 	[int],
	 @NarconMaloxone	 	[int],
	 @ChestCompressions	 	[int],
	 @Feeding		 	[int],
	 @Meconium		 	[int],
	 @Apgar1Min		 	[int],
	 @Apgar5Min		 	[int],
	 @Gestation		 	[int],
	 @MotherPHIN			[varchar](50),
	 @Elopements		 	[int],
	 @LeaveCertificates	 	[int],
	 @FirstStageDateUnknown 	[int], 
	 @SecondStageDateUnknown 	[int],
	 @PrenatalVisitDateUnknown 	[int], 
	 @SmokingQuitDateUnknown 	[int],
	 @ALC_TotalDays 		[int],	
	 @MB_Autopsy 			[int],
	 @MB_Weight 			[int],
	 @NumberPrenatal 		[int], 
	 @PositionDelviery 		[int],
	 @PresentDelivery 		[int],
	 @HCNExpiredDate        [datetime],
	 @SmokingInPregnancy    [int],
	 @AlcoholQuitDate       [datetime],
	 @AlcoholQuitDateUnknown [int]
)
AS 
INSERT INTO [dbo].[AB_Manitoba] 
	 ([AbstractID],
	 [AbstractType],
	 [PreviousName],
	 [PrimaryPhone],
	 [PrimaryAddress],
	 [PrimaryAddress2],
	 [EmployerName],
	 [RegistrantLastName],
	 [RegistrantFirstName],
	 [DeclarationNumber],
	 [MHInstFrom],
	 [MHInstTo],
	 [AnestheticLabor],
	 [PrenatalVisitDate],
	 [NumberPrenatalVisits],
	 [Gravida],
	 [Parity],
	 [ObsEducation],
	 [SmokingPerDay],
	 [SmokingQuitDate],
	 [AlcoholDuringPregnancy],
	 [Days_WeekAlcoholConsumed],
	 [DrinksPerday],
	 [PreConceptionalFolicAcid],
	 [PostConceptionalFolicAcid],
	 [FirstStageDate],
	 [FirstStageTime],
	 [FirstStageDuration],
	 [SecondStageDate],
	 [SecondStageTime],
	 [SecondStageDuration],
	 [Presentation],
	 [RoutineCare],
	 [FreeFlowOxygen],
	 [BagVentilation],
	 [IntubationNotMeconium],
	 [MedicationResuscitation],
	 [NarconMaloxone],
	 [ChestCompressions],
	 [Feeding],
	 [Meconium],
	 [Apgar1Min],
	 [Apgar5Min],
	 [Gestation],
	 [MotherPHIN],
	 [Elopements],
	 [LeaveCertificates],
	 [FirstStageDateUnknown],
	 [SecondStageDateUnknown],
	 [PrenatalVisitDateUnknown], 
	 [SmokingQuitDateUnknown],
	 [ALC_TotalDays],
	 [MB_Autopsy],
	 [MB_Weight],
	 [NumberPrenatal], 
	 [PresentDelivery], 
	 [PositionDelviery],
	 [HCNExpiredDate],
	 [SmokingInPregnancy],
	 [AlcoholQuitDate],
	 [AlcoholQuitDateUnknown]
) 
 
VALUES 
	(@AbstractID,
	 @AbstractType,
	 @PreviousName,
	 @PrimaryPhone,
	 @PrimaryAddress,
	 @PrimaryAddress2,
	 @EmployerName,
	 @RegistrantLastName,
	 @RegistrantFirstName,
	 @DeclarationNumber,
	 @MHInstFrom,
	 @MHInstTo,
	 @AnestheticLabor,
	 @PrenatalVisitDate,
	 @NumberPrenatalVisits,
	 @Gravida,
	 @Parity,
	 @ObsEducation,
	 @SmokingPerDay,
	 @SmokingQuitDate,
	 @AlcoholDuringPregnancy,
	 @Days_WeekAlcoholConsumed,
	 @DrinksPerday,
	 @PreConceptionalFolicAcid,
	 @PostConceptionalFolicAcid,
	 @FirstStageDate,
	 @FirstStageTime,
	 @FirstStageDuration,
	 @SecondStageDate,
	 @SecondStageTime,
	 @SecondStageDuration,
	 @Presentation,
	 @RoutineCare,
	 @FreeFlowOxygen,
	 @BagVentilation,
	 @IntubationNotMeconium,
	 @MedicationResuscitation,
	 @NarconMaloxone,
	 @ChestCompressions,
	 @Feeding,
	 @Meconium,
	 @Apgar1Min,
	 @Apgar5Min,
	 @Gestation,
	 @MotherPHIN,
	 @Elopements,
	 @LeaveCertificates,
	 @FirstStageDateUnknown, 
	 @SecondStageDateUnknown,
	 @PrenatalVisitDateUnknown, 
	 @SmokingQuitDateUnknown,
	 @ALC_TotalDays,
	 @MB_Autopsy,
	 @MB_Weight,
	 @NumberPrenatal,
	 @PresentDelivery, 
	 @PositionDelviery,
	 @HCNExpiredDate,
 	 @SmokingInPregnancy,
	 @AlcoholQuitDate,
	 @AlcoholQuitDateUnknown
)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_AB_MB_ALC]
	(@AbstractID			[int],
	 @Occurrence	 		[int],
	 @DateDesignatedALC 		[datetime],
	 @DateReassignedAcute	[datetime],
	 @ALCReasonCode		[int],
	 @ALCDays		 	[int])

AS INSERT INTO [dbo].[AB_MB_ALC] 
	 ([AbstractID],
	 [Occurrence],
	 [DateDesignatedALC],
	 [DateReassignedAcute],
	 [ALCReasonCode],
	 [ALCDays]) 
VALUES 
	(@AbstractID,
	 @Occurrence,
	 @DateDesignatedALC,
	 @DateReassignedAcute,
	 @ALCReasonCode,
	 @ALCDays)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_AB_MB_FacilityStudy]
	(@AbstractID	 	[int],
	 @Occurrence	 	[int],
	 @FacilityDateStudy 	[datetime],
	 @FacilityStudyCode 	[varchar](50))

AS INSERT INTO [dbo].[AB_MB_FacilityStudy] 
	 ([AbstractID],
	 [Occurrence],
	 [FacilityDateStudy],
	 [FacilityStudyCode]) 
VALUES 
	(@AbstractID,
	 @Occurrence,
	 @FacilityDateStudy,
	 @FacilityStudyCode)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_AB_MB_NonALC]
	(@AbstractID		[int],
	 @Occurrence	 	[int],
	 @NonALCDelayReason	[int],
	 @DaysNonALCDelay 	[int])

AS INSERT INTO [dbo].[AB_MB_NonALC] 
	 ([AbstractID],
	 [Occurrence],
	 [NonALCDelayReason],
	 [DaysNonALCDelay]) 
 
VALUES 
	(@AbstractID,
	 @Occurrence,
	 @NonALCDelayReason,
	 @DaysNonALCDelay)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [I_AB_MentalHealth]
	(@AbstractID		[int],
	 @MentalReferralSource [int],
	 @MentalAdmitMethod	[int],
	 @MentalLegalStatus	[int],
	 @MentalAWOL		[int],
	 @MentalSuicide	[int],
	 @MentalPrevPsych 	[int],
	 @MentalReferralTo 	[int],
	 @MentalECTTreatment 	[int],
	 @MentalNumberECT 	[varchar](10),
	 @MentalEducation 	[int],
	 @MentalEmployment 	[int],
	 @MentalFinancial 	[int],
     @LegalStatusUponArrivaltoED [int],
     @LegalStatusAtAdmission [int],
     @TypeOfRestraint01 [int],
     @FrequencyOfRestraint01 [int],
     @TypeOfRestraint02 [int],
     @FrequencyOfRestraint02 [int],
     @TypeOfRestraint03 [int],
     @FrequencyOfRestraint03 [int],
     @TypeOfRestraint04 [int],
     @FrequencyOfRestraint04 [int]
)
AS 

INSERT INTO [AB_MentalHealth] 
	 ([AbstractID],
	 [MentalReferralSource],
	 [MentalAdmitMethod],
	 [MentalLegalStatus],
	 [MentalAWOL],
	 [MentalSuicide],
	 [MentalPrevPsych],
	 [MentalReferralTo],
	 [MentalECTTreatment],
	 [MentalNumberECT],
	 [MentalEducation],
	 [MentalEmployment],
	 [MentalFinancial],
     [LegalStatusUponArrivaltoED],
     [LegalStatusAtAdmission],
     [TypeOfRestraint01],
     [FrequencyOfRestraint01],
     [TypeOfRestraint02],
     [FrequencyOfRestraint02],
     [TypeOfRestraint03],
     [FrequencyOfRestraint03],
     [TypeOfRestraint04],
     [FrequencyOfRestraint04]
) 
 
VALUES 
	(@AbstractID,
	 @MentalReferralSource,
	 @MentalAdmitMethod,
	 @MentalLegalStatus,
	 @MentalAWOL,
	 @MentalSuicide,
	 @MentalPrevPsych,
	 @MentalReferralTo,
	 @MentalECTTreatment,
	 @MentalNumberECT,
	 @MentalEducation,
	 @MentalEmployment,
	 @MentalFinancial,
     @LegalStatusUponArrivaltoED,
     @LegalStatusAtAdmission,
     @TypeOfRestraint01,
     @FrequencyOfRestraint01,
     @TypeOfRestraint02,
     @FrequencyOfRestraint02,
     @TypeOfRestraint03,
     @FrequencyOfRestraint03,
     @TypeOfRestraint04,
     @FrequencyOfRestraint04
)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [I_AB_MIS]
	(@AbstractID	 	[int],
	 @MISOccurrence 	[int],
	 @MISCode		[int],
	 @DirectCost		[money],
	 @IndirectCost	 	[money],
	 @SupplyCost	 	[money]
)
AS 

INSERT INTO [AB_MIS] 
	 ([AbstractID],
	 [MISOccurrence],
	 [MISCode],
	 [DirectCost],
	 [IndirectCost],
	 [SupplyCost]) 
 
VALUES 
	(@AbstractID,
	 @MISOccurrence,
	 @MISCode,
	 @DirectCost,
	 @IndirectCost,
	 @SupplyCost)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE  PROCEDURE [I_AB_NACRS] (
	@AbstractID		[int],
	@SpecialistNumber 	[int],
	@SpecialistService 	[int],
	@SpecialistRequestDate [datetime],
	@SpecialistRequestTime [datetime],
	@SpecialistRequestTimeUnknown [int],
	@NonPhysicianNumber [int],
	@NonPhysicianService [int] ,
	@NonPhysicianAssessmentDate [datetime] ,
	@NonPhysicianAssessmentTime [datetime],
	@NonPhysicianAssessmentTimeUnknown [int],
	@AmCareTypeCode [int], 
	@AmCareGroup [int] ,
	@StatusAfterTriage int,
    @EDVisitIndicator int
)

AS 
insert into [dbo].[AB_NACRS] (
	[AbstractID],
	[SpecialistNumber] ,
	[SpecialistService] ,
	[SpecialistRequestDate]  ,
	[SpecialistRequestTime] ,
	[SpecialistRequestTimeUnknown] ,
	[NonPhysicianNumber]  ,
	[NonPhysicianService] ,
	[NonPhysicianAssessmentDate] ,
	[NonPhysicianAssessmentTime] ,
	[NonPhysicianAssessmentTimeUnknown],
	[AmCareTypeCode],
	[AmCareGroup],
	[StatusAfterTriage],
    [EDVisitIndicator]
)

values (
	@AbstractID,
	@SpecialistNumber,
	@SpecialistService,
	@SpecialistRequestDate,
	@SpecialistRequestTime,
	@SpecialistRequestTimeUnknown ,
	@NonPhysicianNumber,
	@NonPhysicianService ,
	@NonPhysicianAssessmentDate ,
	@NonPhysicianAssessmentTime,
	@NonPhysicianAssessmentTimeUnknown,
	@AmCareTypeCode, 
	@AmCareGroup,
	@StatusAfterTriage,
    @EDVisitIndicator  
)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [I_AB_PatientService]
	(@AbstractID		 	[int],
	 @ServiceOccurrence	 	[int],
	 @PatientService		[int],
	 @ServiceType			[int],
	 @ServiceDays			[int],
	 @ServiceNursingArea	 	[int],
	 @ServiceNursingUnits	 	[varchar](20),
	 @ServiceTransferInDate 	[datetime],
	 @ServiceTransferInTime 	[datetime],
	 @ServiceTransferOutDate 	[datetime],
	 @ServiceTransferOutTime 	[datetime])

AS 

INSERT INTO [dbo].[AB_PatientService] 
	 ([AbstractID],
	 [ServiceOccurrence],
	 [PatientService],
	 [ServiceType],
	 [ServiceDays],
	 [ServiceNursingArea],
	 [ServiceNursingUnits],
	 [ServiceTransferInDate],
	 [ServiceTransferInTime],
	 [ServiceTransferOutDate],
	 [ServiceTransferOutTime]) 
VALUES 
	(@AbstractID,
	 @ServiceOccurrence,
	 @PatientService,
	 @ServiceType,
	 @ServiceDays,
	 @ServiceNursingArea,
	 @ServiceNursingUnits,
	 @ServiceTransferInDate,
	 @ServiceTransferInTime,
	 @ServiceTransferOutDate,
	 @ServiceTransferOutTime)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [I_AB_PresentingComplaints]
	(@AbstractID	 	[int],
	 @Occurrence	 	[int],
	 @PresentingComplaint	[int])

AS 
insert into [dbo].[AB_PresentingComplaints] 
	 ( [AbstractID],
	 [Occurrence],
	 [PresentingComplaint]) 
 
values
	( @AbstractID,
	 @Occurrence,
	 @PresentingComplaint)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [I_AB_Project]
	(@AbstractID	 	[int],
	 @ProjectOccurrence	[int],
	 @ProjectNumber	[int],
	 @Question1		[int],
	 @Question2	 	[int],
	 @Question3	 	[int],
	 @Question4	 	[int],
	 @Question5		[int],
	 @Question6		[int],
	 @Question7	 	[int],
	 @Question8	 	[int],
	 @Question9	 	[int],
	 @Question10	 	[int],
	 @Question11	 	[int],
	 @Question12		[int],
	 @Question13	 	[int],
	 @Question14	 	[varchar](10),
	 @Question15	 	[varchar](10),
	 @Question16	 	[varchar](10),
	 @Question17	 	[varchar](10),
	 @Question18	 	[varchar](10),
	 @Question19	 	[varchar](10),
	 @Question20	 	[varchar](10),
	 @Question21	 	[varchar](10),
	 @Question22	 	[varchar](10),
	 @Question23	 	[varchar](10),
	 @Question24	 	[varchar](10)
	 )
AS 

if @ProjectNumber in (38, 39) --2.x-1355 Special Project 065
begin
    set @Question2 = @Question1 
    set @Question3 = @Question1 
    set @Question4 = @Question1 
    set @Question5 = @Question1 
    set @Question6 = @Question1 
end

INSERT INTO [AB_Project] 
	 ([AbstractID],
	 [ProjectOccurrence],
	 [ProjectNumber],
	 [Question1],
	 [Question2],
	 [Question3],
	 [Question4],
	 [Question5],
	 [Question6],
	 [Question7],
	 [Question8],
	 [Question9],
	 [Question10],
	 [Question11],
	 [Question12],
	 [Question13],
	 [Question14],
	 [Question15],
	 [Question16],
	 [Question17],
	 [Question18],
	 [Question19],
	 [Question20],
	 [Question21],
	 [Question22],
	 [Question23],
	 [Question24]
	 ) 
 
VALUES 
	(@AbstractID,
	 @ProjectOccurrence,
	 @ProjectNumber,
	 @Question1,
	 @Question2,
	 @Question3,
	 @Question4,
	 @Question5,
	 @Question6,
	 @Question7,
	 @Question8,
	 @Question9,
	 @Question10,
	 @Question11,
	 @Question12,
	 @Question13,
	 @Question14,
	 @Question15,
	 @Question16,
	 @Question17,
	 @Question18,
	 @Question19,
	 @Question20,
	 @Question21,
	 @Question22,
	 @Question23,
	 @Question24
	 )
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [I_AB_Provider]
	(@AbstractID	 	[int],
	 @ProviderOccurrence	[int],
	 @ProviderType 	[int],
	 @ProviderNumber 	[int],
	 @ProviderService 	[int],
	 @ProviderSpecialty	[int],
	 @ProviderCallDate 	[datetime],
	 @ProviderCallTime 	[datetime],
	 @ProviderArriveDate 	[datetime],
	 @ProviderArriveTime 	[datetime],
	 @ProviderTotalTime 	[varchar](10),
	 @ConsultMedical 	[int], 
	 @ConsultNonMedical 	[int])
AS 

INSERT INTO [AB_Provider] 
	 ([AbstractID],
	 [ProviderOccurrence],
	 [ProviderType],
	 [ProviderNumber],
	 [ProviderService],
	 [ProviderSpecialty],
	 [ProviderCallDate],
	 [ProviderCallTime],
	 [ProviderArriveDate],
	 [ProviderArriveTime],
	 [ProviderTotalTime],
	 [ConsultMedical], 
	 [ConsultNonMedical]) 
 
VALUES 
	(@AbstractID,
	 @ProviderOccurrence,
	 @ProviderType,
	 @ProviderNumber,
	 @ProviderService,
	 @ProviderSpecialty,
	 @ProviderCallDate,
	 @ProviderCallTime,
	 @ProviderArriveDate,
	 @ProviderArriveTime,
	 @ProviderTotalTime,
	 @ConsultMedical, 
 	 @ConsultNonMedical)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_AB_QBP_Flag]
	(@AbstractID	 	[int],
    @QBP_BilateralJointReplacement [int], 
    @QBP_ChronicObstructivePulmonary [int], 
    @QBP_CongestiveHeartFailure [int], 
    @QBP_CS_Abdominal [int], 
    @QBP_CSBone [int], 
    @QBP_CSBreastDelayedReconstruction [int], 
    @QBP_CSBreastImmediateReconstruction [int], 
    @QBP_CSBreastNoReconstruction [int], 
    @QBP_CSColorectal [int], 
    @QBP_CSEndocrineOther [int], 
    @QBP_CSEsophagus [int], 
    @QBP_CSGastric [int], 
    @QBP_CSGentourinary [int], 
    @QBP_CSGynecology [int], 
    @QBP_CSHNK [int], 
    @QBP_CSLiver [int], 
    @QBP_CSLung [int], 
    @QBP_CSNeuroBrain [int], 
    @QBP_CSNeuroSpinal [int], 
    @QBP_CSNonSiteSpecific [int], 
    @QBP_CSPancreas [int], 
    @QBP_CSProstate [int], 
    @QBP_CSSkinLymphNode [int], 
    @QBP_CSSkinSoftTissue [int], 
    @QBP_CSSoftTissue [int], 
    @QBP_CSThorax [int], 
    @QBP_CSThyroid [int], 
    @QBP_HipFracture [int], 
    @QBP_CornealTransplant [int], 
    @QBP_KneeAthroscopy [int], 
    @QBP_VascularLower [int], 
    @QBP_VascularAortic [int], 
    @QBP_SpineInstruIP [int], 
    @QBP_SpineNonInstruDay [int], 
    @QBP_SpineNonInstruIP [int], 
    @QBP_BilateralCataracts [int], 
    @QBP_Pneumonia [int], 
    @QBP_ShoulderArthroplasties [int], 
    @QBP_ShoulderOther [int], 
    @QBP_ShoulderRepairs [int], 
    @QBP_ShoulderReverseArthroplaties [int], 
    @QBP_StrokeAcuteHemorrhage [int], 
    @QBP_StrokeAcuteIschemic [int], 
    @QBP_StrokeAcuteTransient [int], 
    @QBP_StrokeEndovascularTherapy [int], 
    @QBP_UnilateralHipReplacement [int], 
    @QBP_UnilateralKneeReplacement [int],
    @QBP_Tonsillectomy int,
    @QBP_NonCancerHysterectomy int,
    @QBP_Retinal int
)
AS 

INSERT INTO [AB_QBP_Flag] 
	 ( [AbstractID],
    QBP_BilateralJointReplacement, 
    QBP_ChronicObstructivePulmonary, 
    QBP_CongestiveHeartFailure, 
    QBP_CS_Abdominal, 
    QBP_CSBone, 
    QBP_CSBreastDelayedReconstruction, 
    QBP_CSBreastImmediateReconstruction, 
    QBP_CSBreastNoReconstruction, 
    QBP_CSColorectal, 
    QBP_CSEndocrineOther, 
    QBP_CSEsophagus, 
    QBP_CSGastric, 
    QBP_CSGentourinary, 
    QBP_CSGynecology, 
    QBP_CSHNK, 
    QBP_CSLiver, 
    QBP_CSLung, 
    QBP_CSNeuroBrain, 
    QBP_CSNeuroSpinal, 
    QBP_CSNonSiteSpecific, 
    QBP_CSPancreas, 
    QBP_CSProstate, 
    QBP_CSSkinLymphNode, 
    QBP_CSSkinSoftTissue, 
    QBP_CSSoftTissue, 
    QBP_CSThorax, 
    QBP_CSThyroid, 
    QBP_HipFracture, 
    QBP_CornealTransplant, 
    QBP_KneeAthroscopy, 
    QBP_VascularLower, 
    QBP_VascularAortic, 
    QBP_SpineInstruIP, 
    QBP_SpineNonInstruDay, 
    QBP_SpineNonInstruIP, 
    QBP_BilateralCataracts, 
    QBP_Pneumonia, 
    QBP_ShoulderArthroplasties, 
    QBP_ShoulderOther, 
    QBP_ShoulderRepairs, 
    QBP_ShoulderReverseArthroplaties, 
    QBP_StrokeAcuteHemorrhage, 
    QBP_StrokeAcuteIschemic, 
    QBP_StrokeAcuteTransient, 
    QBP_StrokeEndovascularTherapy, 
    QBP_UnilateralHipReplacement, 
    QBP_UnilateralKneeReplacement,
    QBP_Tonsillectomy,
    QBP_NonCancerHysterectomy,
    QBP_Retinal

) 
 
VALUES 
	(@AbstractID,
    @QBP_BilateralJointReplacement, 
    @QBP_ChronicObstructivePulmonary, 
    @QBP_CongestiveHeartFailure, 
    @QBP_CS_Abdominal, 
    @QBP_CSBone, 
    @QBP_CSBreastDelayedReconstruction, 
    @QBP_CSBreastImmediateReconstruction, 
    @QBP_CSBreastNoReconstruction, 
    @QBP_CSColorectal, 
    @QBP_CSEndocrineOther, 
    @QBP_CSEsophagus, 
    @QBP_CSGastric, 
    @QBP_CSGentourinary, 
    @QBP_CSGynecology, 
    @QBP_CSHNK, 
    @QBP_CSLiver, 
    @QBP_CSLung, 
    @QBP_CSNeuroBrain, 
    @QBP_CSNeuroSpinal, 
    @QBP_CSNonSiteSpecific, 
    @QBP_CSPancreas, 
    @QBP_CSProstate, 
    @QBP_CSSkinLymphNode, 
    @QBP_CSSkinSoftTissue, 
    @QBP_CSSoftTissue, 
    @QBP_CSThorax, 
    @QBP_CSThyroid, 
    @QBP_HipFracture, 
    @QBP_CornealTransplant, 
    @QBP_KneeAthroscopy, 
    @QBP_VascularLower, 
    @QBP_VascularAortic, 
    @QBP_SpineInstruIP, 
    @QBP_SpineNonInstruDay, 
    @QBP_SpineNonInstruIP, 
    @QBP_BilateralCataracts, 
    @QBP_Pneumonia, 
    @QBP_ShoulderArthroplasties, 
    @QBP_ShoulderOther, 
    @QBP_ShoulderRepairs, 
    @QBP_ShoulderReverseArthroplaties, 
    @QBP_StrokeAcuteHemorrhage, 
    @QBP_StrokeAcuteIschemic, 
    @QBP_StrokeAcuteTransient, 
    @QBP_StrokeEndovascularTherapy, 
    @QBP_UnilateralHipReplacement, 
    @QBP_UnilateralKneeReplacement,
    @QBP_Tonsillectomy,
    @QBP_NonCancerHysterectomy,
    @QBP_Retinal

     )





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_AB_ReproductiveCare]
	(@AbstractID	 	[int],
	 @PrevTermDelivery 	[varchar](10),
	 @PrevPreTermDelivery 	[varchar](10),
	 @PrevSpontAbortions 	[varchar](10),
	 @PrevInduceAbortions 	[varchar](10),
	 @PrevLiveBirths 	[varchar](10),
	 @GestationalAge 	[varchar](10),
	 @AbortDate		[datetime],
	 @DeliveryDate	 	[datetime],
	 @DeliveryTime 		[datetime],
	 @LastMensesDate 	[datetime],
	 @BreastFeeding 	[int],
	 @InitialOR	 	[int],
	 @SubsequentOR 	[int],
	 @Sterilization	 	[int],
	 @Complication1	[int],
	 @Complication2	[int],
	 @Complication3 	[int],
	 @ReprodComments 	[varchar](250),
	 @DeliveryTimeUnknown int,
	 @LaborLOS 	[varchar](50),
	 @LaborLOSHour int)
AS 

INSERT INTO [AB_ReproductiveCare] 
	 ([AbstractID],
	 [PrevTermDelivery],
	 [PrevPreTermDelivery],
	 [PrevSpontAbortions],
	 [PrevInduceAbortions],
	 [PrevLiveBirths],
	 [GestationalAge],
	 [DeliveryDate],
	 [DeliveryTime],
	 [LastMensesDate],
	 [BreastFeeding],
	 [InitialOR],
	 [SubsequentOR],
	 [Sterilization],
	 [Complication1],
	 [Complication2],
	 [Complication3],
	 [ReprodComments],
	 [DeliveryTimeUnknown],
     [LaborLOS],
     [LaborLOSHour])
 
VALUES 
	(@AbstractID,
	 @PrevTermDelivery,
	 @PrevPreTermDelivery,
	 @PrevSpontAbortions,
	 @PrevInduceAbortions,
	 @PrevLiveBirths,
	 @GestationalAge,
	 @DeliveryDate,
	 @DeliveryTime,
	 @LastMensesDate,
	 @BreastFeeding,
	 @InitialOR,
	 @SubsequentOR,
	 @Sterilization,
	 @Complication1,
	 @Complication2,
	 @Complication3,
	 @ReprodComments,
	 @DeliveryTimeUnknown,
     @LaborLOS,
     @LaborLOSHour)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_AB_SpecialCareUnit](
    @AbstractID [int], 
    @SCUOccurrence [int], 
    @SCUNumber [int], 
    @SCUAdmitDate [datetime], 
    @SCUAdmitTime [datetime], 
    @SCUDischDate [datetime], 
    @SCUDischTime [datetime], 
    @SCULOS [varchar](10), 
    @SCUDiagCode [int], 
    @SCUHours [int],
    @SCUAdmitTimeUnknown int,
    @SCUDischTimeUnknown int)
AS 
INSERT INTO [AB_SpecialCareUnit] (
    [AbstractID], 
    [SCUOccurrence], 
    [SCUNumber], 
    [SCUAdmitDate], 
    [SCUAdmitTime], 
    [SCUDischDate], 
    [SCUDischTime], 
    [SCULOS], 
    [SCUHours], 
    [SCUDiagCode],
    [SCUAdmitTimeUnknown],
    [SCUDischTimeUnknown]) 
VALUES (
    @AbstractID, 
    @SCUOccurrence, 
    @SCUNumber, 
    @SCUAdmitDate, 
    @SCUAdmitTime, 
    @SCUDischDate, 
    @SCUDischTime, 
    @SCULOS, 
    @SCUHours, 
    @SCUDiagCode,
    @SCUAdmitTimeUnknown,
    @SCUDischTimeUnknown)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [I_AB_SpecialProject](
	@AbstractID [int],
	@CareType [int],
	@OccurrenceNumber [int],
	@SpecialProject [int],
	@Question1 [varchar](50),
	@Question2 [varchar](50),
	@Question3 [varchar](50),
	@Question4 [varchar](50),
	@Question5 [varchar](50),
	@Question6 [varchar](50),
	@Question7 [varchar](50),
	@Question8 [varchar](50),
	@Question9 [varchar](50),
	@Question10 [varchar](50),
	@Question11 [varchar](50),
	@Question12 [varchar](50),
	@Question13 [varchar](50),
	@Question14 [varchar](50),
	@Question15 [varchar](50),
	@Question16 [varchar](50),
	@Question17 [varchar](50),
	@Question18 [varchar](50),
	@Question19 [varchar](50),
	@Question20 [varchar](50))
as
	insert into dbo.AB_SpecialProjects(	
		AbstractID, 
		CareType, 
		OccurrenceNumber, 
		SpecialProject, 
		Question1, Question2, Question3, Question4, Question5, 
		Question6, Question7, Question8, Question9, Question10, 
		Question11, Question12, Question13, Question14, Question15, 
		Question16, Question17, Question18, Question19, Question20)
	values(
		@AbstractID, 
		@CareType, 
		@OccurrenceNumber, 
		@SpecialProject, 
		@Question1, 
		@Question2, 
		@Question3, 
		@Question4, 
		@Question5, 
		@Question6, 
		@Question7, 
		@Question8, 
		@Question9, 
		@Question10, 
		@Question11, 
		@Question12, 
		@Question13, 
		@Question14, 
		@Question15, 
		@Question16, 
		@Question17, 
		@Question18, 
		@Question19, 
		@Question20)
	

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_AB_SpecialProjects]
	(@AbstractID	 	[int],
	 @CareType          [int],
	 @OccurrenceNumber	[int],
	 @SpecialProject	[int],
	 @Question1		[varchar](50),
	 @Question2	 	[varchar](50),
	 @Question3	 	[varchar](50),
	 @Question4	 	[varchar](50),
	 @Question5		[varchar](50),
	 @Question6		[varchar](50),
	 @Question7	 	[varchar](50),
	 @Question8	 	[varchar](50),
	 @Question9	 	[varchar](50),
	 @Question10	[varchar](50),
	 @Question11	[varchar](50),
	 @Question12	[varchar](50),
	 @Question13	[varchar](50),
	 @Question14	[varchar](50),
	 @Question15	[varchar](50),
	 @Question16	[varchar](50),
	 @Question17	[varchar](50),
	 @Question18	[varchar](50),
	 @Question19	[varchar](50),
	 @Question20	[varchar](50))
AS 

INSERT INTO [AB_SpecialProjects] 
	 ([AbstractID],
	 [CareType],
	 [OccurrenceNumber],
	 [SpecialProject],
	 [Question1],
	 [Question2],
	 [Question3],
	 [Question4],
	 [Question5],
	 [Question6],
	 [Question7],
	 [Question8],
	 [Question9],
	 [Question10],
	 [Question11],
	 [Question12],
	 [Question13],
	 [Question14],
	 [Question15],
	 [Question16],
	 [Question17],
	 [Question18],
	 [Question19],
	 [Question20]) 
 
VALUES 
	(@AbstractID,
	 @CareType,
	 @OccurrenceNumber,
	 @SpecialProject,
	 @Question1,
	 @Question2,
	 @Question3,
	 @Question4,
	 @Question5,
	 @Question6,
	 @Question7,
	 @Question8,
	 @Question9,
	 @Question10,
	 @Question11,
	 @Question12,
	 @Question13,
	 @Question14,
	 @Question15,
	 @Question16,
	 @Question17,
	 @Question18,
	 @Question19,
	 @Question20)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [I_AB_Therapeutic]
	(@AbstractID	 		[int],
	 @PhysioTherapy		[int],
	 @PhysioUnits	 		[varchar](10),
	 @OccupationalTherapy 		[int],
	 @OccupationalUnits 		[varchar](10),
	 @SpeechTherapy 		[int],
	 @SpeechUnits	 		[varchar](10),
	 @RespiratoryTherapy		[int],
	 @RespiratoryUnits		[varchar](10),
	 @FirstOptionTherapy 		[int],
	 @FirstOptionUnits 		[varchar](10),
	 @SecondOptionTherapy	[int],
	 @SecondOptionUnits		[varchar](10))
AS 

INSERT INTO [AB_Therapeutic] 
	 ([AbstractID],
	 [PhysioTherapy],
	 [PhysioUnits],
	 [OccupationalTherapy],
	 [OccupationalUnits],
	 [SpeechTherapy],
	 [SpeechUnits],
	 [RespiratoryTherapy],
	 [RespiratoryUnits],
	 [FirstOptionTherapy],
	 [FirstOptionUnits],
	 [SecondOptionTherapy],
	 [SecondOptionUnits]) 
 
VALUES 
	(@AbstractID,
	 @PhysioTherapy,
	 @PhysioUnits,
	 @OccupationalTherapy,
	 @OccupationalUnits,
	 @SpeechTherapy,
	 @SpeechUnits,
	 @RespiratoryTherapy,
	 @RespiratoryUnits,
	 @FirstOptionTherapy,
	 @FirstOptionUnits,
	 @SecondOptionTherapy,
	 @SecondOptionUnits)




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_AB_TransferService]
	(@AbstractID		 	[int],
	 @Occurrence	 		[int],
	 @TransService			[int],
	 @TransType			[int],
	 @TransDays			[int],
	 @TransNursingArea	 	[int],
	 @TransNursingUnits	 	[varchar](20),
	 @TransInDate 			[datetime],
	 @TransInTime 			[datetime],
	 @TransOutDate 		[datetime],
	 @TransOutTime 		[datetime],
	 @TransPriority			[int])

AS 
INSERT INTO [dbo].[AB_TransferService] 
	 ([AbstractID],
	 [Occurrence],
	 [TransService],
	 [TransType],
	 [TransDays],
	 [TransNursingArea],
	 [TransNursingUnits],
	 [TransInDate],
	 [TransInTime],
	 [TransOutDate],
	 [TransOutTime],
	 [TransPriority]) 
VALUES 
	(@AbstractID,
	 @Occurrence,
	 @TransService,
	 @TransType,
	 @TransDays,
	 @TransNursingArea,
	 @TransNursingUnits,
	 @TransInDate,
	 @TransInTime,
	 @TransOutDate,
	 @TransOutTime,
	 @TransPriority)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE  PROCEDURE [I_AB_UDAbstracting]
	(@AbstractID 	[int],
	 @UDDate1 	[datetime],
	 @UDDate2 	[datetime],
	 @UDDate3 	[datetime],
	 @UDDate4 	[datetime],
	 @UDTime1 	[datetime],
	 @UDTime2 	[datetime],
	 @UDTime3 	[datetime],
	 @UDTime4 	[datetime],
	 @UDLookup1 	[int],
	 @UDLookup2 	[int],
	 @UDLookup3 	[int],
	 @UDLookup4 	[int],
	 @UDInteger1 	[varchar](50),
	 @UDInteger2 	[varchar](50),
	 @UDInteger3 	[varchar](50),
	 @UDInteger4 	[varchar](50),
	 @UDText1 	[varchar](255),
	 @UDText2 	[varchar](255),
	 @UDText3 	[varchar](255),
	 @UDText4 	[varchar](255),
	 @UDSmallText1 [varchar](50), 
	 @UDSmallText2 [varchar](50), 
	 @UDSmallText3 [varchar](50), 
	 @UDSmallText4 [varchar](50),
	 @UDDate5 	[datetime], 
	 @UDTime5 	[datetime], 
	 @UDLookup5 	[int], 
	 @UDInteger5 	[varchar](50), 
	 @UDText5 	[varchar](255), 
 	 @UDSmallText5 	[varchar](50))
AS 
INSERT INTO [dbo].[AB_UDAbstracting] 
	 ([AbstractID],
	 [UDDate1],
	 [UDDate2],
	 [UDDate3],
	 [UDDate4],
	 [UDTime1],
	 [UDTime2],
	 [UDTime3],
	 [UDTime4],
	 [UDLookup1],
	 [UDLookup2],
	 [UDLookup3],
	 [UDLookup4],
	 [UDInteger1],
	 [UDInteger2],
	 [UDInteger3],
	 [UDInteger4],
	 [UDText1],
	 [UDText2],
	 [UDText3],
	 [UDText4],
	 [UDSmallText1], 
	 [UDSmallText2], 
	 [UDSmallText3], 
	 [UDSmallText4],
	 [UDDate5], 
	 [UDTime5], 
	 [UDLookup5], 
	 [UDInteger5], 
	 [UDText5], 
 	 [UDSmallText5]) 
VALUES 
	(@AbstractID,
	 @UDDate1,
	 @UDDate2,
	 @UDDate3,
	 @UDDate4,
	 @UDTime1,
	 @UDTime2,
	 @UDTime3,
	 @UDTime4,
	 @UDLookup1,
	 @UDLookup2,
	 @UDLookup3,
	 @UDLookup4,
	 @UDInteger1,
	 @UDInteger2,
	 @UDInteger3,
	 @UDInteger4,
	 @UDText1,
	 @UDText2,
	 @UDText3,
	 @UDText4,
	 @UDSmallText1, 
	 @UDSmallText2, 
	 @UDSmallText3, 
	 @UDSmallText4,
	 @UDDate5, 
	 @UDTime5, 
	 @UDLookup5, 
	 @UDInteger5, 
	 @UDText5, 
 	 @UDSmallText5)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_AB_UDFieldsDate]
	(@AbstractID 	[int],
	 @UDDate6 	[datetime],
	 @UDDate7 	[datetime],
	 @UDDate8 	[datetime],
	 @UDDate9 	[datetime],
	 @UDDate10 	[datetime],
	 @UDDate11 	[datetime],
	 @UDDate12 	[datetime],
	 @UDDate13 	[datetime],
	 @UDDate14 	[datetime],
	 @UDDate15 	[datetime],
	 @UDDate16 	[datetime],
	 @UDDate17 	[datetime],
	 @UDDate18 	[datetime],
	 @UDDate19 	[datetime],
	 @UDDate20 	[datetime],
	 @UDDate21 	[datetime],
	 @UDDate22 	[datetime],
	 @UDDate23 	[datetime],
	 @UDDate24 	[datetime],
	 @UDDate25 	[datetime])
as 
insert into [dbo].[AB_UDFieldsDate] 
	 ([AbstractID],
	 [UDDate6],
	 [UDDate7],
	 [UDDate8],
	 [UDDate9],
	 [UDDate10],
	 [UDDate11],
	 [UDDate12],
	 [UDDate13],
	 [UDDate14],
	 [UDDate15],
	 [UDDate16],
	 [UDDate17],
	 [UDDate18],
	 [UDDate19],
	 [UDDate20],
	 [UDDate21],
	 [UDDate22],
	 [UDDate23],
	 [UDDate24],
	 [UDDate25]) 
values
	(@AbstractID,
	 @UDDate6,
	 @UDDate7,
	 @UDDate8,
	 @UDDate9,
	 @UDDate10,
	 @UDDate11,
	 @UDDate12,
	 @UDDate13,
	 @UDDate14,
	 @UDDate15,
	 @UDDate16,
	 @UDDate17,
	 @UDDate18,
	 @UDDate19,
	 @UDDate20,
	 @UDDate21,
	 @UDDate22,
	 @UDDate23,
	 @UDDate24,
	 @UDDate25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_AB_UDFieldsInteger]
	(@AbstractID 	[int],
	 @UDInteger6 	[varchar](50),
	 @UDInteger7 	[varchar](50),
	 @UDInteger8 	[varchar](50),
	 @UDInteger9 	[varchar](50),
	 @UDInteger10 	[varchar](50),
	 @UDInteger11 	[varchar](50),
	 @UDInteger12 	[varchar](50),
	 @UDInteger13 	[varchar](50),
	 @UDInteger14 	[varchar](50),
	 @UDInteger15 	[varchar](50),
	 @UDInteger16 	[varchar](50),
	 @UDInteger17 	[varchar](50),
	 @UDInteger18 	[varchar](50),
	 @UDInteger19 	[varchar](50),
	 @UDInteger20 	[varchar](50),
	 @UDInteger21 	[varchar](50),
	 @UDInteger22 	[varchar](50),
	 @UDInteger23 	[varchar](50),
	 @UDInteger24 	[varchar](50),
	 @UDInteger25 	[varchar](50))
as 
insert into [dbo].[AB_UDFieldsInteger] 
	 ([AbstractID],
	 [UDInteger6],
	 [UDInteger7],
	 [UDInteger8],
	 [UDInteger9],
	 [UDInteger10],
	 [UDInteger11],
	 [UDInteger12],
	 [UDInteger13],
	 [UDInteger14],
	 [UDInteger15],
	 [UDInteger16],
	 [UDInteger17],
	 [UDInteger18],
	 [UDInteger19],
	 [UDInteger20],
	 [UDInteger21],
	 [UDInteger22],
	 [UDInteger23],
	 [UDInteger24],
	 [UDInteger25]) 
values
	(@AbstractID,
	 @UDInteger6,
	 @UDInteger7,
	 @UDInteger8,
	 @UDInteger9,
	 @UDInteger10,
	 @UDInteger11,
	 @UDInteger12,
	 @UDInteger13,
	 @UDInteger14,
	 @UDInteger15,
	 @UDInteger16,
	 @UDInteger17,
	 @UDInteger18,
	 @UDInteger19,
	 @UDInteger20,
	 @UDInteger21,
	 @UDInteger22,
	 @UDInteger23,
	 @UDInteger24,
	 @UDInteger25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_AB_UDFieldsLookUp]
	(@AbstractID 	[int],
	 @UDLookUp6 	[int],
	 @UDLookUp7 	[int],
	 @UDLookUp8 	[int],
	 @UDLookUp9 	[int],
	 @UDLookUp10 	[int],
	 @UDLookUp11 	[int],
	 @UDLookUp12 	[int],
	 @UDLookUp13 	[int],
	 @UDLookUp14 	[int],
	 @UDLookUp15 	[int],
	 @UDLookUp16 	[int],
	 @UDLookUp17 	[int],
	 @UDLookUp18 	[int],
	 @UDLookUp19 	[int],
	 @UDLookUp20 	[int],
	 @UDLookUp21 	[int],
	 @UDLookUp22 	[int],
	 @UDLookUp23 	[int],
	 @UDLookUp24 	[int],
	 @UDLookUp25 	[int])
as 
insert into [dbo].[AB_UDFieldsLookUp] 
	 ([AbstractID],
	 [UDLookUp6],
	 [UDLookUp7],
	 [UDLookUp8],
	 [UDLookUp9],
	 [UDLookUp10],
	 [UDLookUp11],
	 [UDLookUp12],
	 [UDLookUp13],
	 [UDLookUp14],
	 [UDLookUp15],
	 [UDLookUp16],
	 [UDLookUp17],
	 [UDLookUp18],
	 [UDLookUp19],
	 [UDLookUp20],
	 [UDLookUp21],
	 [UDLookUp22],
	 [UDLookUp23],
	 [UDLookUp24],
	 [UDLookUp25]) 
values
	(@AbstractID,
	 @UDLookUp6,
	 @UDLookUp7,
	 @UDLookUp8,
	 @UDLookUp9,
	 @UDLookUp10,
	 @UDLookUp11,
	 @UDLookUp12,
	 @UDLookUp13,
	 @UDLookUp14,
	 @UDLookUp15,
	 @UDLookUp16,
	 @UDLookUp17,
	 @UDLookUp18,
	 @UDLookUp19,
	 @UDLookUp20,
	 @UDLookUp21,
	 @UDLookUp22,
	 @UDLookUp23,
	 @UDLookUp24,
	 @UDLookUp25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_AB_UDFieldsSmallText]
	(@AbstractID 	[int],
	 @UDSmallText6 	[varchar](50),
	 @UDSmallText7 	[varchar](50),
	 @UDSmallText8 	[varchar](50),
	 @UDSmallText9 	[varchar](50),
	 @UDSmallText10 	[varchar](50),
	 @UDSmallText11 	[varchar](50),
	 @UDSmallText12 	[varchar](50),
	 @UDSmallText13 	[varchar](50),
	 @UDSmallText14 	[varchar](50),
	 @UDSmallText15 	[varchar](50),
	 @UDSmallText16 	[varchar](50),
	 @UDSmallText17 	[varchar](50),
	 @UDSmallText18 	[varchar](50),
	 @UDSmallText19 	[varchar](50),
	 @UDSmallText20 	[varchar](50),
	 @UDSmallText21 	[varchar](50),
	 @UDSmallText22 	[varchar](50),
	 @UDSmallText23 	[varchar](50),
	 @UDSmallText24 	[varchar](50),
	 @UDSmallText25 	[varchar](50))
as 
insert into [dbo].[AB_UDFieldsSmallText] 
	 ([AbstractID],
	 [UDSmallText6],
	 [UDSmallText7],
	 [UDSmallText8],
	 [UDSmallText9],
	 [UDSmallText10],
	 [UDSmallText11],
	 [UDSmallText12],
	 [UDSmallText13],
	 [UDSmallText14],
	 [UDSmallText15],
	 [UDSmallText16],
	 [UDSmallText17],
	 [UDSmallText18],
	 [UDSmallText19],
	 [UDSmallText20],
	 [UDSmallText21],
	 [UDSmallText22],
	 [UDSmallText23],
	 [UDSmallText24],
	 [UDSmallText25]) 
values
	(@AbstractID,
	 @UDSmallText6,
	 @UDSmallText7,
	 @UDSmallText8,
	 @UDSmallText9,
	 @UDSmallText10,
	 @UDSmallText11,
	 @UDSmallText12,
	 @UDSmallText13,
	 @UDSmallText14,
	 @UDSmallText15,
	 @UDSmallText16,
	 @UDSmallText17,
	 @UDSmallText18,
	 @UDSmallText19,
	 @UDSmallText20,
	 @UDSmallText21,
	 @UDSmallText22,
	 @UDSmallText23,
	 @UDSmallText24,
	 @UDSmallText25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_AB_UDFieldsText]
	(@AbstractID 	[int],
	 @UDText6 	[varchar](255),
	 @UDText7 	[varchar](255),
	 @UDText8 	[varchar](255),
	 @UDText9 	[varchar](255),
	 @UDText10 	[varchar](255),
	 @UDText11 	[varchar](255),
	 @UDText12 	[varchar](255),
	 @UDText13 	[varchar](255),
	 @UDText14 	[varchar](255),
	 @UDText15 	[varchar](255),
	 @UDText16 	[varchar](255),
	 @UDText17 	[varchar](255),
	 @UDText18 	[varchar](255),
	 @UDText19 	[varchar](255),
	 @UDText20 	[varchar](255),
	 @UDText21 	[varchar](255),
	 @UDText22 	[varchar](255),
	 @UDText23 	[varchar](255),
	 @UDText24 	[varchar](255),
	 @UDText25 	[varchar](255))
as 
insert into [dbo].[AB_UDFieldsText] 
	 ([AbstractID],
	 [UDText6],
	 [UDText7],
	 [UDText8],
	 [UDText9],
	 [UDText10],
	 [UDText11],
	 [UDText12],
	 [UDText13],
	 [UDText14],
	 [UDText15],
	 [UDText16],
	 [UDText17],
	 [UDText18],
	 [UDText19],
	 [UDText20],
	 [UDText21],
	 [UDText22],
	 [UDText23],
	 [UDText24],
	 [UDText25]) 
values
	(@AbstractID,
	 @UDText6,
	 @UDText7,
	 @UDText8,
	 @UDText9,
	 @UDText10,
	 @UDText11,
	 @UDText12,
	 @UDText13,
	 @UDText14,
	 @UDText15,
	 @UDText16,
	 @UDText17,
	 @UDText18,
	 @UDText19,
	 @UDText20,
	 @UDText21,
	 @UDText22,
	 @UDText23,
	 @UDText24,
	 @UDText25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_AB_UDFieldsTime]
	(@AbstractID 	[int],
	 @UDTime6 	[datetime],
	 @UDTime7 	[datetime],
	 @UDTime8 	[datetime],
	 @UDTime9 	[datetime],
	 @UDTime10 	[datetime],
	 @UDTime11 	[datetime],
	 @UDTime12 	[datetime],
	 @UDTime13 	[datetime],
	 @UDTime14 	[datetime],
	 @UDTime15 	[datetime],
	 @UDTime16 	[datetime],
	 @UDTime17 	[datetime],
	 @UDTime18 	[datetime],
	 @UDTime19 	[datetime],
	 @UDTime20 	[datetime],
	 @UDTime21 	[datetime],
	 @UDTime22 	[datetime],
	 @UDTime23 	[datetime],
	 @UDTime24 	[datetime],
	 @UDTime25 	[datetime])
as 
insert into [dbo].[AB_UDFieldsTime] 
	 ([AbstractID],
	 [UDTime6],
	 [UDTime7],
	 [UDTime8],
	 [UDTime9],
	 [UDTime10],
	 [UDTime11],
	 [UDTime12],
	 [UDTime13],
	 [UDTime14],
	 [UDTime15],
	 [UDTime16],
	 [UDTime17],
	 [UDTime18],
	 [UDTime19],
	 [UDTime20],
	 [UDTime21],
	 [UDTime22],
	 [UDTime23],
	 [UDTime24],
	 [UDTime25]) 
values
	(@AbstractID,
	 @UDTime6,
	 @UDTime7,
	 @UDTime8,
	 @UDTime9,
	 @UDTime10,
	 @UDTime11,
	 @UDTime12,
	 @UDTime13,
	 @UDTime14,
	 @UDTime15,
	 @UDTime16,
	 @UDTime17,
	 @UDTime18,
	 @UDTime19,
	 @UDTime20,
	 @UDTime21,
	 @UDTime22,
	 @UDTime23,
	 @UDTime24,
	 @UDTime25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE   PROCEDURE [I_CC_CancerStageDiag]
	(@AbstractID 	[int],
	 @ClinStageDiag 	[varchar] (50),
	 @ClinStageDiag_T 	[varchar] (50),
	 @ClinStageDiag_N 	[varchar] (50),
	 @ClinStageDiag_M 	[varchar] (50),
	 @PathStageDiag 	[varchar] (50),
	 @PathStageDiag_T 	[varchar] (50),
	 @PathStageDiag_N 	[varchar] (50),
	 @PathStageDiag_M 	[varchar] (50),
	 @ExtentDisease_cTNM 	[varchar] (50),
	 @ExtentDisease_cT 	[varchar] (50),
	 @ExtentDisease_cN 	[varchar] (50),
	 @ExtentDisease_cM 	[varchar] (50),
	 @ExtentDisease_pTNM 	[varchar] (50),
	 @ExtentDisease_pT 	[varchar] (50),
	 @ExtentDisease_pN 	[varchar] (50),
	 @ExtentDisease_pM 	[varchar] (50),
	 @StagingVersion 	[int],
	 @Laterality 	[int],
	 @StagingComplete	[int],			--- New Fields 03/13/2008
	 @SourceOfInfo		[int],
	 @PhysicianCompletedForm	[int],
     @ClinStageDiag_T_S	[int],
     @ClinStageDiag_N_S	[int],
     @PathStageDiag_T_S	[int],
     @PathStageDiag_N_S	[int],
     @PostTherapyStage	[int],
     @PostTherapyStage_T 	[varchar] (50),
     @PostTherapyStage_T_S	[int],
     @PostTherapyStage_N 	[varchar] (50),
     @PostTherapyStage_N_S	[int],
     @PostTherapyStage_M 	[varchar] (50)
)

AS 
INSERT INTO [dbo].[CC_CancerStageDiag] 
	 ([AbstractID],
	 [ClinStageDiag],
	 [ClinStageDiag_T],
	 [ClinStageDiag_N],
	 [ClinStageDiag_M],
	 [PathStageDiag],
	 [PathStageDiag_T],
	 [PathStageDiag_N],
	 [PathStageDiag_M],
	 [ExtentDisease_cTNM],
	 [ExtentDisease_cT],
	 [ExtentDisease_cN],
	 [ExtentDisease_cM],
	 [ExtentDisease_pTNM],
	 [ExtentDisease_pT],
	 [ExtentDisease_pN],
	 [ExtentDisease_pM],
	 [StagingVersion],
	 [Laterality],
	 [StagingComplete],			--- New Fields 03/13/2008
	 [SourceOfInfo],
	 [PhysicianCompletedForm],
     [ClinStageDiag_T_S],
	 [ClinStageDiag_N_S],
	 [PathStageDiag_T_S],
	 [PathStageDiag_N_S],
	 [PostTherapyStage],
	 [PostTherapyStage_T],
	 [PostTherapyStage_T_S],
	 [PostTherapyStage_N],
	 [PostTherapyStage_N_S],
	 [PostTherapyStage_M]) 
 
VALUES 
	(@AbstractID,
	 @ClinStageDiag,
	 @ClinStageDiag_T,
	 @ClinStageDiag_N,
	 @ClinStageDiag_M,
	 @PathStageDiag,
	 @PathStageDiag_T,
	 @PathStageDiag_N,
	 @PathStageDiag_M,
	 @ExtentDisease_cTNM,
	 @ExtentDisease_cT,
	 @ExtentDisease_cN,
	 @ExtentDisease_cM,
	 @ExtentDisease_pTNM,
	 @ExtentDisease_pT,
	 @ExtentDisease_pN,
	 @ExtentDisease_pM,
	 @StagingVersion,
	 @Laterality,
	 @StagingComplete,			--- New Fields 03/13/2008
	 @SourceOfInfo,
	 @PhysicianCompletedForm,
     @ClinStageDiag_T_S,
     @ClinStageDiag_N_S,
     @PathStageDiag_T_S,
     @PathStageDiag_N_S,
     @PostTherapyStage,
     @PostTherapyStage_T,
     @PostTherapyStage_T_S,
     @PostTherapyStage_N,
     @PostTherapyStage_N_S,
     @PostTherapyStage_M 
 )



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE    PROCEDURE [I_CC_CollaborateStageDiag]
	(@AbstractID 	[int],
	 @Version 	[varchar] (50),
	 @TumourSize 	[int],
	 @Extension 	[varchar] (50),  -- [int], PR - 03314
	 @TumourExtensionEval 	[varchar] (50), -- [int],PR - 03314
	 @LymphNodes 	[int],
	 @RegionNodeEval 	[int],
	 @RegionNodePositive 	[int],
	 @RegionNodeExamined	[int],
	 @MetastasesDiag 	[varchar] (50), --[int],PR - 03314
	 @MetastasesEval 	[varchar] (50), --[int],PR - 03314
	 @SiteSpecFactor1 	[varchar] (50), --[int],PR - 03314
	 @SiteSpecFactor2 	[varchar] (50), --[int],PR - 03314
	 @SiteSpecFactor3 	[varchar] (50), --[int],PR - 03314
	 @SiteSpecFactor4 	[varchar] (50), --[int],PR - 03314
	 @SiteSpecFactor5 	[varchar] (50), --[int],PR - 03314
	 @SiteSpecFactor6 	[varchar] (50)) --[int])PR - 03314

AS 
INSERT INTO [dbo].[CC_CollaborateStageDiag] 
	 ([AbstractID],
	 [Version],
	 [TumourSize],
	 [Extension],
	 [TumourExtensionEval],
	 [LymphNodes],
	 [RegionNodeEval],
	 [RegionNodePositive],
	 [RegionNodeExamined],
	 [MetastasesDiag],
	 [MetastasesEval],
	 [SiteSpecFactor1],
	 [SiteSpecFactor2],
	 [SiteSpecFactor3],
	 [SiteSpecFactor4],
	 [SiteSpecFactor5],
	 [SiteSpecFactor6]) 
 
VALUES 
	(@AbstractID,
	 @Version,
	 @TumourSize,
	 @Extension,
	 @TumourExtensionEval,
	 @LymphNodes,
	 @RegionNodeEval,
	 @RegionNodePositive,
	 @RegionNodeExamined,
	 @MetastasesDiag,
	 @MetastasesEval,
	 @SiteSpecFactor1,
	 @SiteSpecFactor2,
	 @SiteSpecFactor3,
	 @SiteSpecFactor4,
	 @SiteSpecFactor5,
	 @SiteSpecFactor6)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_CC_Demographic]
	(@AbstractID 	[int],
	 @LinkID 	[int],
	 @AppID 	[int],
	 @HospitalID 	[int],
	 @ProvinceNumber 	[int],
	 @InstitutionNumber	[int],
	 @ChartNumber 	[varchar](50),
	 @LastName 	[varchar](50),
	 @FirstName 	[varchar](50),
	 @MiddleName 	[varchar](50),
	 @MaidenName 	[varchar](50),
	 @Gender 	[int],
	 @BirthDate 	[datetime],
	 @PostalCode 	[varchar](50),
	 @ResidenceCode 	[int],
	 @DeathIndicator 	[int],
	 @DeathDate 	[datetime],
	 @HealthCareNumber 	[varchar](50),
	 @HCNVersion 	[varchar](50),
	 @HCNProvince 	[int],
	 @ResponsiblePayment 	[int],
--	 @HostChartNumber 	[varchar](50),   PR - 03282
	 @City  	[varchar] (32), 	--PR - 03332 New fields added
	 @Province	[int],
	 @Country	[int],
	 @FixedChartNumber [varchar](50),
	 @UniversalEpisodeIdentifier [varchar](50),
	 @HospitalAccountRecord [varchar](50)
     )

AS 

select @AbstractID = (select isnull(max(AbstractID), 0) from CC_Demographic) + 1
if isnull(@LinkID, 0) = 0 set @LinkID = @AbstractID   

INSERT INTO [dbo].[CC_Demographic] 
	 ([AbstractID],
	 [LinkID],
	 [AppID],
	 [IsCurrent],
	 [HospitalID],
	 [ProvinceNumber],
	 [InstitutionNumber],
	 [ChartNumber],
	 [LastName],
	 [FirstName],
	 [MiddleName],
	 [MaidenName],
	 [Gender],
	 [BirthDate],
	 [PostalCode],
	 [ResidenceCode],
	 [DeathIndicator],
	 [DeathDate],
	 [HealthCareNumber],
	 [HCNVersion],
	 [HCNProvince],
	 [ResponsiblePayment],
--	 [HostChartNumber],  	 PR - 03282
	 [City],  		--PR - 03332 New fields added
	 [Province],
	 [Country],
	 [FixedChartNumber],
     [UniversalEpisodeIdentifier],
	 [HospitalAccountRecord] )
 
VALUES 
	(@AbstractID,
	 @LinkID,
	 @AppID,
	 1,
	 @HospitalID,
	 @ProvinceNumber,
	 @InstitutionNumber,
	 @ChartNumber,
	 @LastName,
	 @FirstName,
	 @MiddleName,
	 @MaidenName,
	 @Gender,
	 @BirthDate,
	 @PostalCode,
	 @ResidenceCode,
	 @DeathIndicator,
	 @DeathDate,
	 @HealthCareNumber,
	 @HCNVersion,
	 @HCNProvince,
	 @ResponsiblePayment,
--	 @HostChartNumber,	 PR - 03282
	 @City,  		 --PR - 03332 New fields added
	 @Province,
	 @Country,
	 @FixedChartNumber,
     @UniversalEpisodeIdentifier,
	 @HospitalAccountRecord )

	return @AbstractID
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE   PROCEDURE [I_CC_DischargeInfo]
	(@AbstractID 		[int],
	 @DispositionCode 	[int],
	 @DischargeDate 	[datetime],
	 @DischargeAge	 	[int],
	 @DischargeAgeCode 	[int],
	 @DurationInMonths 	[int]
)

AS 
INSERT INTO [dbo].[CC_DischargeInfo] 
	 ([AbstractID],
	 [DispositionCode],
	 [DischargeDate],
	 [DischargeAge],
	 [DischargeAgeCode],
	 [DurationInMonths]
	 ) 
 
VALUES 
	(@AbstractID,
 	 @DispositionCode,
	 @DischargeDate,
	 @DischargeAge,
	 @DischargeAgeCode,
	 @DurationInMonths) 
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE    PROCEDURE [I_CC_DiseaseRegister]
	(@AbstractID 	[int],
	 @RegisterDate 	[datetime],
	 --@HospitalNumber 	[int],
	 @DiseaseSequenceNum 	[int],
	 @CoderNumber 	[int],
	 @DiagHospitalNum 	[int],
	 @DiagHospitalChartNum 	[varchar](50),
	 @InitalDiagDate 	[datetime],
	 @BasisDiag 	[int],
	 @FirstSurgTreatFlag 	[int],
	 @FirstSurgTreatDate 	[datetime],
	 @DiagnosisCode 	[int],
	 --@DiagnosisVersion 	[int],
	 @TopographyCode 	[int],
	 @MorphologyCodeO2 	[int],
	 @MorphologyCodeO3 	[int],
	 @TopoMorphVersion 	[int],
	 @DiagAgeCode	[int] ,
	 @DiagAgeNumber	[int] ,
	 @DurationInitDiag	[int] , 
	 @DurationDiseaseReg 	[int],
	 @AnalyticFlag		[int],  --ED - 01576
	 @ReportingMonth	[int]   --New Field 03/13/2008
)

AS 
INSERT INTO [dbo].[CC_DiseaseRegister] 
	 ([AbstractID],
	 [RegisterDate],
	 --[HospitalNumber],
	 [DiseaseSequenceNum],
	 [CoderNumber],
	 [DiagHospitalNum],
	 [DiagHospitalChartNum],
	 [InitalDiagDate],
	 [DiagAgeCode],
	 [DiagAgeNumber],
	 [DurationInitDiag], 
	 [BasisDiag],
	 [FirstSurgTreatFlag],
	 [FirstSurgTreatDate],
	 [DurationDiseaseReg], 
	 [DiagnosisCode],
	 [DiagnosisVersion],
	 [TopographyCode],
	 [MorphologyCodeO2],
	 [MorphologyCodeO3],
	 [TopoMorphVersion], 
	 [AnalyticFlag], 
	 [ReportingMonth]) 
 
VALUES 
	(@AbstractID,
	 @RegisterDate,
	 --@HospitalNumber,
	 @DiseaseSequenceNum,
	 @CoderNumber,
	 @DiagHospitalNum,
	 @DiagHospitalChartNum,
	 @InitalDiagDate,
	 @DiagAgeCode,
	 @DiagAgeNumber,
	 @DurationInitDiag, 
	 @BasisDiag,
	 @FirstSurgTreatFlag,
	 @FirstSurgTreatDate,
	 @DurationDiseaseReg, 
	 @DiagnosisCode,
	 '10', --@DiagnosisVersion,
	 @TopographyCode,
	 @MorphologyCodeO2,
	 @MorphologyCodeO3,
	 @TopoMorphVersion,
	 @AnalyticFlag,
	 @ReportingMonth)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [I_CC_HealthCareProf]
	(@AbstractID 	[int],
	 @Occurrence 	[int],
	 @ProgramCode 	[int],
	 @HCPNumber 	[int],
	 @SurName 	[varchar](50),
	 @FirstName 	[varchar](50),
	 @SpecialtyCode 	[int],
	 @Status 	[int],
	 @HostHCPNumber 	[int])

AS 
INSERT INTO [dbo].[CC_HealthCareProf] 
	 ([AbstractID],
	 [Occurrence],
	 [ProgramCode],
	 [HCPNumber],
	 [SurName],
	 [FirstName],
	 [SpecialtyCode],
	 [Status],
	 [HostHCPNumber]) 
 
VALUES 
	(@AbstractID,
	 @Occurrence,
	 @ProgramCode,
	 @HCPNumber,
	 @SurName,
	 @FirstName,
	 @SpecialtyCode,
	 @Status,
	 @HostHCPNumber)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [I_CC_NDFP]
	(@AbstractID	 	[int],
	 @VisitHospitalNum 	[int],
	 @NDFPNumber 	[varchar](50),
	 @NDFPVersion 	[varchar](50),
	 @FirstTreatDate 	[datetime],
	 @Height	 	[varchar](50),
	 @Weight		[varchar](50),
	 @BodySurfaceArea 	[varchar](50),
	 @EligAnswr1	 	[varchar](50),
	 @EligAnswr2	 	[varchar](50),
	 @EligAnswr3	 	[varchar](50),
	 @EligAnswr4	 	[varchar](50),
	 @EligAnswr5	 	[varchar](50),
	 @EligAnswr6	 	[varchar](50),
	 @EligAnswr7	 	[varchar](50),
	 @EligAnswr8	 	[varchar](50),
	 @EligAnswr9	 	[varchar](50),
	 @EligAnswr10	 	[varchar](50),
	 @EligAnswr11	 	[varchar](50),
	 @EligAnswr12	 	[varchar](50),
	 @EligAnswr13	 	[varchar](50),
	 @EligAnswr14	 	[varchar](50),
	 @EligAnswr15	 	[varchar](50),
	 @EligAnswr16	 	[varchar](50),
	 @EligAnswr17	 	[varchar](50),
	 @EligAnswr18	 	[varchar](50),
	 @EligAnswr19	 	[varchar](50),
	 @EligAnswr20	 	[varchar](50),
	 @EligAnswr21	 	[varchar](50),
	 @EligAnswr22	 	[varchar](50),
	 @EligAnswr23	 	[varchar](50),
	 @EligAnswr24	 	[varchar](50),
	 @EligAnswr25	 	[varchar](50),
	 @EligAnswr26	 	[varchar](50),
	 @EligAnswr27	 	[varchar](50),
	 @EligAnswr28	 	[varchar](50),
	 @EligAnswr29	 	[varchar](50),
	 @EligAnswr30	 	[varchar](50),
	 @Intent		    [int] )

AS 
INSERT INTO [dbo].[CC_NDFP] 
	 ( [AbstractID],
	 [VisitHospitalNum],
	 [NDFPNumber],
	 [NDFPVersion],
	 [FirstTreatDate],
	 [Height],
	 [Weight],
	 [BodySurfaceArea],
	 [EligAnswr1],
	 [EligAnswr2],
	 [EligAnswr3],
	 [EligAnswr4],
	 [EligAnswr5],
	 [EligAnswr6],
	 [EligAnswr7],
	 [EligAnswr8],
	 [EligAnswr9],
	 [EligAnswr10],
	 [EligAnswr11],
	 [EligAnswr12],
	 [EligAnswr13],
	 [EligAnswr14],
	 [EligAnswr15],
	 [EligAnswr16],
	 [EligAnswr17],
	 [EligAnswr18],
	 [EligAnswr19],
	 [EligAnswr20],
	 [EligAnswr21],
	 [EligAnswr22],
	 [EligAnswr23],
	 [EligAnswr24],
	 [EligAnswr25],
	 [EligAnswr26],
	 [EligAnswr27],
	 [EligAnswr28],
	 [EligAnswr29],
	 [EligAnswr30],
	 [Intent]) 
 
VALUES 
	( @AbstractID,
	 @VisitHospitalNum,
	 @NDFPNumber,
	 @NDFPVersion,
	 @FirstTreatDate,
	 @Height,
	 @Weight,
	 @BodySurfaceArea,
	 @EligAnswr1,
	 @EligAnswr2,
	 @EligAnswr3,
	 @EligAnswr4,
	 @EligAnswr5,
	 @EligAnswr6,
	 @EligAnswr7,
	 @EligAnswr8,
	 @EligAnswr9,
	 @EligAnswr10,
	 @EligAnswr11,
	 @EligAnswr12,
	 @EligAnswr13,
	 @EligAnswr14,
	 @EligAnswr15,
	 @EligAnswr16,
	 @EligAnswr17,
	 @EligAnswr18,
	 @EligAnswr19,
	 @EligAnswr20,
	 @EligAnswr21,
	 @EligAnswr22,
	 @EligAnswr23,
	 @EligAnswr24,
	 @EligAnswr25,
	 @EligAnswr26,
	 @EligAnswr27,
	 @EligAnswr28,
	 @EligAnswr29,
	 @EligAnswr30,
	 @Intent)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [I_CC_RecordInfo]
	(@AbstractID 	[int],
	 @IsSubmited 	[int],
	 @IsCorrected	[int], 
	 @IsValidated 	[int],
	 @IsCompleted 	[int],
	 @CompleteRecord 	[int],
	 @InputDate 	[datetime],
	 @InputTime 	[datetime],
	 @CCRegFileDate 	[datetime],
	 @CCRegFileCoder 	[int])

AS 

If isnull(@IsCorrected, 0) = 0 set @IsCorrected = 1 -- PR - 03723
If isnull(@IsSubmited, 0) = 0 set @IsSubmited = 2   -- PR - 03723

INSERT INTO [dbo].[CC_RecordInfo] 
	 ([AbstractID],
	 [IsDeleted],
	 [IsSubmited],
	 [IsCorrected], 
	 [IsValidated],
	 [IsCompleted],
	 [CompleteRecord],
	 [InputDate],
	 [InputTime],
	 [CCRegFileDate],
	 [CCRegFileCoder]) 
 
VALUES 
	(@AbstractID,
	2,
	 @IsSubmited,
	 @IsCorrected, 
	 @IsValidated,
	 @IsCompleted,
	 @CompleteRecord,
	 @InputDate,
	 @InputTime,
	 @CCRegFileDate,
	 @CCRegFileCoder)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [I_CC_ReferralDate]
	(@AbstractID 	[int],
	 @MedicalOncologistRefDate 	    [datetime],
	 @RadiationOncologistRefDate 	[datetime],
	 @SurgicalOncologistRefDate 	[datetime],
	 @SupportCareRefDate 		    [datetime],
	 @DurationMedicalOncologist 	[int],
	 @DurationRadiationOncologist 	[int],
	 @DurationSurgicalOncologist 	[int],
	 @DurationSupportCare 		[int],
	 @PalliativeRefDate         [datetime],
	 @DurationPalliativeCare    [int],
	 @SocialWorkCareRefDate     [datetime], 
	 @DurationSocialWorkCare 	[int], 
	 @NutritionalRefDate    [datetime], 
	 @DurationNutritional 	[int], 
	 @PhysiotherapyRefDate  [datetime], 
	 @DurationPhysiotherapy [int], 
	 @PsychiatryRefDate     [datetime], 
	 @DurationPsychiatry 	[int], 
	 @PsychologyRefDate     [datetime], 
	 @DurationPsychology 	[int], 
	 @OccupationalRefDate   [datetime], 
	 @DurationOccupational 	[int], 
	 @SpeechRefDate         [datetime], 
	 @DurationSpeech 		[int]
)

AS 
INSERT INTO [dbo].[CC_ReferralDate] 
	 ([AbstractID],
	 [MedicalOncologistRefDate],
	 [DurationMedicalOncologist],
	 [RadiationOncologistRefDate],
	 [DurationRadiationOncologist],
	 [SurgicalOncologistRefDate],
	 [DurationSurgicalOncologist],
	 [SupportCareRefDate],
	 [DurationSupportCare],
	 [PalliativeRefDate],
	 [DurationPalliativeCare],
	 [SocialWorkCareRefDate], 
	 [DurationSocialWorkCare], 
	 [NutritionalRefDate], 
	 [DurationNutritional], 
	 [PhysiotherapyRefDate], 
	 [DurationPhysiotherapy], 
	 [PsychiatryRefDate], 
	 [DurationPsychiatry], 
	 [PsychologyRefDate], 
	 [DurationPsychology], 
	 [OccupationalRefDate], 
	 [DurationOccupational], 
	 [SpeechRefDate], 
	 [DurationSpeech]
) 
 
VALUES 
	(@AbstractID,
	 @MedicalOncologistRefDate,
	 @DurationMedicalOncologist,
	 @RadiationOncologistRefDate,
	 @DurationRadiationOncologist,
	 @SurgicalOncologistRefDate,
	 @DurationSurgicalOncologist,
	 @SupportCareRefDate,
	 @DurationSupportCare,
	 @PalliativeRefDate,
	 @DurationPalliativeCare,
	 @SocialWorkCareRefDate, 
	 @DurationSocialWorkCare, 
	 @NutritionalRefDate, 
	 @DurationNutritional, 
	 @PhysiotherapyRefDate, 
	 @DurationPhysiotherapy, 
	 @PsychiatryRefDate, 
	 @DurationPsychiatry, 
	 @PsychologyRefDate, 
	 @DurationPsychology, 
	 @OccupationalRefDate, 
	 @DurationOccupational, 
	 @SpeechRefDate, 
	 @DurationSpeech
)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CC_UDFieldsDate]
	(@AbstractID 	[int],
	 @UDDate6 	[datetime],
	 @UDDate7 	[datetime],
	 @UDDate8 	[datetime],
	 @UDDate9 	[datetime],
	 @UDDate10 	[datetime],
	 @UDDate11 	[datetime],
	 @UDDate12 	[datetime],
	 @UDDate13 	[datetime],
	 @UDDate14 	[datetime],
	 @UDDate15 	[datetime],
	 @UDDate16 	[datetime],
	 @UDDate17 	[datetime],
	 @UDDate18 	[datetime],
	 @UDDate19 	[datetime],
	 @UDDate20 	[datetime],
	 @UDDate21 	[datetime],
	 @UDDate22 	[datetime],
	 @UDDate23 	[datetime],
	 @UDDate24 	[datetime],
	 @UDDate25 	[datetime])
as 
insert into [dbo].[CC_UDFieldsDate] 
	 ([AbstractID],
	 [UDDate6],
	 [UDDate7],
	 [UDDate8],
	 [UDDate9],
	 [UDDate10],
	 [UDDate11],
	 [UDDate12],
	 [UDDate13],
	 [UDDate14],
	 [UDDate15],
	 [UDDate16],
	 [UDDate17],
	 [UDDate18],
	 [UDDate19],
	 [UDDate20],
	 [UDDate21],
	 [UDDate22],
	 [UDDate23],
	 [UDDate24],
	 [UDDate25]) 
values
	(@AbstractID,
	 @UDDate6,
	 @UDDate7,
	 @UDDate8,
	 @UDDate9,
	 @UDDate10,
	 @UDDate11,
	 @UDDate12,
	 @UDDate13,
	 @UDDate14,
	 @UDDate15,
	 @UDDate16,
	 @UDDate17,
	 @UDDate18,
	 @UDDate19,
	 @UDDate20,
	 @UDDate21,
	 @UDDate22,
	 @UDDate23,
	 @UDDate24,
	 @UDDate25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CC_UDFieldsInteger]
	(@AbstractID 	[int],
	 @UDInteger6 	[varchar](50),
	 @UDInteger7 	[varchar](50),
	 @UDInteger8 	[varchar](50),
	 @UDInteger9 	[varchar](50),
	 @UDInteger10 	[varchar](50),
	 @UDInteger11 	[varchar](50),
	 @UDInteger12 	[varchar](50),
	 @UDInteger13 	[varchar](50),
	 @UDInteger14 	[varchar](50),
	 @UDInteger15 	[varchar](50),
	 @UDInteger16 	[varchar](50),
	 @UDInteger17 	[varchar](50),
	 @UDInteger18 	[varchar](50),
	 @UDInteger19 	[varchar](50),
	 @UDInteger20 	[varchar](50),
	 @UDInteger21 	[varchar](50),
	 @UDInteger22 	[varchar](50),
	 @UDInteger23 	[varchar](50),
	 @UDInteger24 	[varchar](50),
	 @UDInteger25 	[varchar](50))
as 
insert into [dbo].[CC_UDFieldsInteger] 
	 ([AbstractID],
	 [UDInteger6],
	 [UDInteger7],
	 [UDInteger8],
	 [UDInteger9],
	 [UDInteger10],
	 [UDInteger11],
	 [UDInteger12],
	 [UDInteger13],
	 [UDInteger14],
	 [UDInteger15],
	 [UDInteger16],
	 [UDInteger17],
	 [UDInteger18],
	 [UDInteger19],
	 [UDInteger20],
	 [UDInteger21],
	 [UDInteger22],
	 [UDInteger23],
	 [UDInteger24],
	 [UDInteger25]) 
values
	(@AbstractID,
	 @UDInteger6,
	 @UDInteger7,
	 @UDInteger8,
	 @UDInteger9,
	 @UDInteger10,
	 @UDInteger11,
	 @UDInteger12,
	 @UDInteger13,
	 @UDInteger14,
	 @UDInteger15,
	 @UDInteger16,
	 @UDInteger17,
	 @UDInteger18,
	 @UDInteger19,
	 @UDInteger20,
	 @UDInteger21,
	 @UDInteger22,
	 @UDInteger23,
	 @UDInteger24,
	 @UDInteger25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CC_UDFieldsLookUp]
	(@AbstractID 	[int],
	 @UDLookUp6 	[int],
	 @UDLookUp7 	[int],
	 @UDLookUp8 	[int],
	 @UDLookUp9 	[int],
	 @UDLookUp10 	[int],
	 @UDLookUp11 	[int],
	 @UDLookUp12 	[int],
	 @UDLookUp13 	[int],
	 @UDLookUp14 	[int],
	 @UDLookUp15 	[int],
	 @UDLookUp16 	[int],
	 @UDLookUp17 	[int],
	 @UDLookUp18 	[int],
	 @UDLookUp19 	[int],
	 @UDLookUp20 	[int],
	 @UDLookUp21 	[int],
	 @UDLookUp22 	[int],
	 @UDLookUp23 	[int],
	 @UDLookUp24 	[int],
	 @UDLookUp25 	[int])
as 
insert into [dbo].[CC_UDFieldsLookUp] 
	 ([AbstractID],
	 [UDLookUp6],
	 [UDLookUp7],
	 [UDLookUp8],
	 [UDLookUp9],
	 [UDLookUp10],
	 [UDLookUp11],
	 [UDLookUp12],
	 [UDLookUp13],
	 [UDLookUp14],
	 [UDLookUp15],
	 [UDLookUp16],
	 [UDLookUp17],
	 [UDLookUp18],
	 [UDLookUp19],
	 [UDLookUp20],
	 [UDLookUp21],
	 [UDLookUp22],
	 [UDLookUp23],
	 [UDLookUp24],
	 [UDLookUp25]) 
values
	(@AbstractID,
	 @UDLookUp6,
	 @UDLookUp7,
	 @UDLookUp8,
	 @UDLookUp9,
	 @UDLookUp10,
	 @UDLookUp11,
	 @UDLookUp12,
	 @UDLookUp13,
	 @UDLookUp14,
	 @UDLookUp15,
	 @UDLookUp16,
	 @UDLookUp17,
	 @UDLookUp18,
	 @UDLookUp19,
	 @UDLookUp20,
	 @UDLookUp21,
	 @UDLookUp22,
	 @UDLookUp23,
	 @UDLookUp24,
	 @UDLookUp25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CC_UDFieldsSmallText]
	(@AbstractID 	[int],
	 @UDSmallText6 	[varchar](50),
	 @UDSmallText7 	[varchar](50),
	 @UDSmallText8 	[varchar](50),
	 @UDSmallText9 	[varchar](50),
	 @UDSmallText10 	[varchar](50),
	 @UDSmallText11 	[varchar](50),
	 @UDSmallText12 	[varchar](50),
	 @UDSmallText13 	[varchar](50),
	 @UDSmallText14 	[varchar](50),
	 @UDSmallText15 	[varchar](50),
	 @UDSmallText16 	[varchar](50),
	 @UDSmallText17 	[varchar](50),
	 @UDSmallText18 	[varchar](50),
	 @UDSmallText19 	[varchar](50),
	 @UDSmallText20 	[varchar](50),
	 @UDSmallText21 	[varchar](50),
	 @UDSmallText22 	[varchar](50),
	 @UDSmallText23 	[varchar](50),
	 @UDSmallText24 	[varchar](50),
	 @UDSmallText25 	[varchar](50))
as 
insert into [dbo].[CC_UDFieldsSmallText] 
	 ([AbstractID],
	 [UDSmallText6],
	 [UDSmallText7],
	 [UDSmallText8],
	 [UDSmallText9],
	 [UDSmallText10],
	 [UDSmallText11],
	 [UDSmallText12],
	 [UDSmallText13],
	 [UDSmallText14],
	 [UDSmallText15],
	 [UDSmallText16],
	 [UDSmallText17],
	 [UDSmallText18],
	 [UDSmallText19],
	 [UDSmallText20],
	 [UDSmallText21],
	 [UDSmallText22],
	 [UDSmallText23],
	 [UDSmallText24],
	 [UDSmallText25]) 
values
	(@AbstractID,
	 @UDSmallText6,
	 @UDSmallText7,
	 @UDSmallText8,
	 @UDSmallText9,
	 @UDSmallText10,
	 @UDSmallText11,
	 @UDSmallText12,
	 @UDSmallText13,
	 @UDSmallText14,
	 @UDSmallText15,
	 @UDSmallText16,
	 @UDSmallText17,
	 @UDSmallText18,
	 @UDSmallText19,
	 @UDSmallText20,
	 @UDSmallText21,
	 @UDSmallText22,
	 @UDSmallText23,
	 @UDSmallText24,
	 @UDSmallText25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CC_UDFieldsText]
	(@AbstractID 	[int],
	 @UDText6 	[varchar](255),
	 @UDText7 	[varchar](255),
	 @UDText8 	[varchar](255),
	 @UDText9 	[varchar](255),
	 @UDText10 	[varchar](255),
	 @UDText11 	[varchar](255),
	 @UDText12 	[varchar](255),
	 @UDText13 	[varchar](255),
	 @UDText14 	[varchar](255),
	 @UDText15 	[varchar](255),
	 @UDText16 	[varchar](255),
	 @UDText17 	[varchar](255),
	 @UDText18 	[varchar](255),
	 @UDText19 	[varchar](255),
	 @UDText20 	[varchar](255),
	 @UDText21 	[varchar](255),
	 @UDText22 	[varchar](255),
	 @UDText23 	[varchar](255),
	 @UDText24 	[varchar](255),
	 @UDText25 	[varchar](255))
as 
insert into [dbo].[CC_UDFieldsText] 
	 ([AbstractID],
	 [UDText6],
	 [UDText7],
	 [UDText8],
	 [UDText9],
	 [UDText10],
	 [UDText11],
	 [UDText12],
	 [UDText13],
	 [UDText14],
	 [UDText15],
	 [UDText16],
	 [UDText17],
	 [UDText18],
	 [UDText19],
	 [UDText20],
	 [UDText21],
	 [UDText22],
	 [UDText23],
	 [UDText24],
	 [UDText25]) 
values
	(@AbstractID,
	 @UDText6,
	 @UDText7,
	 @UDText8,
	 @UDText9,
	 @UDText10,
	 @UDText11,
	 @UDText12,
	 @UDText13,
	 @UDText14,
	 @UDText15,
	 @UDText16,
	 @UDText17,
	 @UDText18,
	 @UDText19,
	 @UDText20,
	 @UDText21,
	 @UDText22,
	 @UDText23,
	 @UDText24,
	 @UDText25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CC_UDFieldsTime]
	(@AbstractID 	[int],
	 @UDTime6 	[datetime],
	 @UDTime7 	[datetime],
	 @UDTime8 	[datetime],
	 @UDTime9 	[datetime],
	 @UDTime10 	[datetime],
	 @UDTime11 	[datetime],
	 @UDTime12 	[datetime],
	 @UDTime13 	[datetime],
	 @UDTime14 	[datetime],
	 @UDTime15 	[datetime],
	 @UDTime16 	[datetime],
	 @UDTime17 	[datetime],
	 @UDTime18 	[datetime],
	 @UDTime19 	[datetime],
	 @UDTime20 	[datetime],
	 @UDTime21 	[datetime],
	 @UDTime22 	[datetime],
	 @UDTime23 	[datetime],
	 @UDTime24 	[datetime],
	 @UDTime25 	[datetime])
as 
insert into [dbo].[CC_UDFieldsTime] 
	 ([AbstractID],
	 [UDTime6],
	 [UDTime7],
	 [UDTime8],
	 [UDTime9],
	 [UDTime10],
	 [UDTime11],
	 [UDTime12],
	 [UDTime13],
	 [UDTime14],
	 [UDTime15],
	 [UDTime16],
	 [UDTime17],
	 [UDTime18],
	 [UDTime19],
	 [UDTime20],
	 [UDTime21],
	 [UDTime22],
	 [UDTime23],
	 [UDTime24],
	 [UDTime25]) 
values
	(@AbstractID,
	 @UDTime6,
	 @UDTime7,
	 @UDTime8,
	 @UDTime9,
	 @UDTime10,
	 @UDTime11,
	 @UDTime12,
	 @UDTime13,
	 @UDTime14,
	 @UDTime15,
	 @UDTime16,
	 @UDTime17,
	 @UDTime18,
	 @UDTime19,
	 @UDTime20,
	 @UDTime21,
	 @UDTime22,
	 @UDTime23,
	 @UDTime24,
	 @UDTime25)
	 
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE  PROCEDURE [I_CC_UpdateHistory] 
	@AbstractID as int,
	@Coder as int, 
    	@UpdateType as varchar(10)
AS 

declare @HID as int --NP-00025
select @HID = HospitalID from U_Users where Code = @Coder

insert into CC_UpdateHistory (AbstractID, HospitalID, Coder, Updated, UpdateType) 
values (@AbstractID, @HID, @Coder, GetDate(), @UpdateType)
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE  PROCEDURE [I_CC_UserDefined]
	(@AbstractID 	[int],
	 @UDDate1 	[datetime],
	 @UDDate2 	[datetime],
	 @UDDate3 	[datetime],
	 @UDDate4 	[datetime],
	 @UDTime1 	[datetime],
	 @UDTime2 	[datetime],
	 @UDTime3 	[datetime],
	 @UDTime4 	[datetime],
	 @UDLookup1 	[int],
	 @UDLookup2 	[int],
	 @UDLookup3 	[int],
	 @UDLookup4 	[int],
	 @UDInteger1 	[int],
	 @UDInteger2 	[int],
	 @UDInteger3 	[int],
	 @UDInteger4 	[int],
	 @UDText1 	[varchar](255),
	 @UDText2 	[varchar](255),
	 @UDText3 	[varchar](255),
	 @UDText4 	[varchar](255),
	 @UDSmallText1 [varchar](50), 
	 @UDSmallText2 [varchar](50), 
	 @UDSmallText3 [varchar](50), 
	 @UDSmallText4 [varchar](50),
	 @UDDate5 	[datetime], 
	 @UDTime5 	[datetime], 
	 @UDLookup5 	[int], 
	 @UDInteger5 	[varchar](50), 
	 @UDText5 	[varchar](255), 
 	 @UDSmallText5 	[varchar](50))
AS 
INSERT INTO [dbo].[CC_UserDefined] 
	 ([AbstractID],
	 [UDDate1],
	 [UDDate2],
	 [UDDate3],
	 [UDDate4],
	 [UDTime1],
	 [UDTime2],
	 [UDTime3],
	 [UDTime4],
	 [UDLookup1],
	 [UDLookup2],
	 [UDLookup3],
	 [UDLookup4],
	 [UDInteger1],
	 [UDInteger2],
	 [UDInteger3],
	 [UDInteger4],
	 [UDText1],
	 [UDText2],
	 [UDText3],
	 [UDText4],
	 [UDSmallText1], 
	 [UDSmallText2], 
	 [UDSmallText3], 
	 [UDSmallText4],
	 [UDDate5], 
	 [UDTime5], 
	 [UDLookup5], 
	 [UDInteger5], 
	 [UDText5], 
 	 [UDSmallText5]) 
VALUES 
	(@AbstractID,
	 @UDDate1,
	 @UDDate2,
	 @UDDate3,
	 @UDDate4,
	 @UDTime1,
	 @UDTime2,
	 @UDTime3,
	 @UDTime4,
	 @UDLookup1,
	 @UDLookup2,
	 @UDLookup3,
	 @UDLookup4,
	 @UDInteger1,
	 @UDInteger2,
	 @UDInteger3,
	 @UDInteger4,
	 @UDText1,
	 @UDText2,
	 @UDText3,
	 @UDText4,
	 @UDSmallText1, 
	 @UDSmallText2, 
	 @UDSmallText3, 
	 @UDSmallText4,
	 @UDDate5, 
	 @UDTime5, 
	 @UDLookup5, 
	 @UDInteger5, 
	 @UDText5, 
 	 @UDSmallText5)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE  PROCEDURE [I_CCRS_UpdateHistory] 
	@AbstractID as int,
	@Coder as int, 
    @UpdateType as varchar(10)
AS 

declare @HID as int --NP-00025
select @HID = HospitalID from U_Users where Code = @Coder

insert into CRS_UpdateHistory (AbstractID, HospitalID, Coder, Updated, UpdateType) 
values (@AbstractID, @HID, @Coder, GetDate(), @UpdateType)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EN-00183
CREATE   PROCEDURE [I_ChartLoanToRequest]
--Create a chart request for an existing Loan
	@VolumeID as int, --@ActivityID as int, --PR - 03986
    @HospitalID as int,
	@Coder as int,
	@DateOut as DateTime,
	@TimeOut as DateTime,
    @Borrower as int,
    @RequestLocation as int,
    @ActivityExpectedReturn as datetime,
    @CLRequestPriority as int,
    @LoanReason as varchar(250)
AS 
	Declare @UniqueID as int
    --Declare @VolumeID as int
    --If the request exists, it will only update coder and priority. 
    --PR - 03986
    if exists(select * from dbo.CL_Activity Where VolumeID = @VolumeID and ActivityType = 4 and ActivityBorrower = @Borrower and ActivityLocation = @RequestLocation)
        Update CL_Activity 
        set ActivityCoderOut = @Coder,
            CLRequestPriority = @CLRequestPriority,
            LoanReason  = @LoanReason
        Where VolumeID = VolumeID and ActivityType = 4 and ActivityBorrower = @Borrower and ActivityLocation = @RequestLocation
    else
    begin
        --set @VolumeID = (select top 1 VolumeID from dbo.CL_Activity Where CLActivityID = @ActivityID)

    	set @UniqueID = (select max(clActivityID) from CL_Activity) + 1

    	Insert Into CL_Activity (CLActivityID, HospitalID, VolumeID, ActivityType, ActivityDateOut, 
            ActivityTimeOut, ActivityCoderOut, ActivityBorrower, ActivityLocation, 
        	ActivityExpectedReturn, CLRequestPriority, LoanReason) 
        SELECT @UniqueID, @HospitalID, @VolumeID, 4, @DateOut, @TimeOut, @Coder, @Borrower, @RequestLocation, 
    	    @ActivityExpectedReturn, @CLRequestPriority, @LoanReason
        --FROM dbo.CL_Activity Where CLActivityID = @ActivityID
    end
	Return 0





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_CJRR_Abstract]
	(@RecordID                   [int]
	,@AppID                      [int]	
	,@HospitalID                 [int]
	,@LinkID					 [int]
	,@InterventionCIHI			 [varchar] (50)
	,@ChartNumber                [varchar] (50) 
	--,@VolumeID                   [int]
	,@RecordType                 [int]
	,@FiscalSurgeryYear			 [int] 
	,@HospitalProvinceCode		 [int]
	,@RecordSubmitObjective      [int]
	,@InstitutionNumber			 [int]
	,@SurgeryDate                [datetime] 
	,@ProviderNumber			 [int] 
	,@SurgeonID		             [varchar] (50)
	,@SurgeonLastName            [varchar] (50)
	,@SurgeonFirstName           [varchar] (50)
	,@HealthCareNumber           [varchar] (50)
	,@HCNVersion                 [varchar] (50)
	,@HCNProvince                [int] 
	,@Gender                     [int] 
	,@BirthDate                  [datetime] 
	,@MaidenName                 [varchar]  (50)
	,@LastName                   [varchar]  (50)
	,@MiddleName                 [varchar]  (50)
	,@FirstName                  [varchar]  (50)
	,@PostalCode                 [varchar] (50)
	,@SideLocation               [int]
	,@ReplacementType            [int]
	,@PrimaryProcedureType		 [int]
	,@DiagnosisGrouping			 [int]
	,@RevisionReason			 [int]
	,@CoderNumber                [int] 
	--,@IsDeleted                  [int] 
	,@IsValidated                [int] 
	,@IsCompleted                [int] 
	--,@IsSubmited                 [int] 
	,@IsCorrected                [int] 
	--,@CIHIDateSent			   [datetime] 
	,@MainDiagnosisCode          [int] 
    ,@InterventionCode           [int] 
    ,@AbstractInstNumber		 [int] 
	,@AdmitDate					 [datetime]
	,@AdmitTime					 [datetime]
	,@DischargeDate				 [datetime]
	,@DischargeTime				 [datetime]
	,@FixedChartNumber			 [varchar](50)
	,@IsCustomValidated			 [int]    
	)
AS 
set @LastName = replace(@LastName, '''''', '''')
select @RecordID = (select isnull(max(RecordID), 0) from CJRR_Abstract) + 1

--If isnull(@IsDeleted, 0) = 0   set @IsDeleted = 2   
If isnull(@IsCorrected, 0) = 0 set @IsCorrected = 1 
--If isnull(@IsSubmited, 0) = 0 set @IsSubmited = 2 

insert into [CJRR_Abstract] 
	([RecordID]
	,[AppID]	
	,[HospitalID]
	,[LinkID]
	,[MainDiagnosisCode]
	,[InterventionCode]
	,[InterventionCIHI]
	,[ChartNumber]
	--,[VolumeID]
	,[RecordType]
	,[FiscalSurgeryYear]
	,[HospitalProvinceCode]
	,[RecordSubmitObjective]
    ,[AbstractInstNumber]	
	,[InstitutionNumber]
	,[AdmitDate]
	,[AdmitTime]
	,[DischargeDate]
	,[DischargeTime]	
	,[SurgeryDate]
	,[ProviderNumber]
	,[SurgeonID]
	,[SurgeonLastName]
	,[SurgeonFirstName]
	,[HealthCareNumber]
	,[HCNVersion]
	,[HCNProvince]
	,[Gender]
	,[BirthDate]
	,[MaidenName]
	,[LastName]
	,[MiddleName]
	,[FirstName]
	,[PostalCode]
	,[SideLocation]
	,[ReplacementType]
	,[PrimaryProcedureType]
	,[DiagnosisGrouping]
	,[RevisionReason]
	,[CoderNumber]
	,[IsDeleted]
	,[IsValidated]
	,[IsCompleted]
	,[IsSubmited]
	,[IsCorrected]
	,[FixedChartNumber]
	,[IsCustomValidated]
	--,[CIHIDateSent]
) 
values 
	(@RecordID
	,@AppID	
	,@HospitalID
	,@LinkID
	,@MainDiagnosisCode
	,@InterventionCode
    ,@InterventionCIHI	
	,@ChartNumber
	--,@VolumeID
	,@RecordType
	,@FiscalSurgeryYear
	,@HospitalProvinceCode
	,@RecordSubmitObjective
    ,@AbstractInstNumber	
	,@InstitutionNumber
	,@AdmitDate
	,@AdmitTime
	,@DischargeDate
	,@DischargeTime
	,@SurgeryDate
	,@ProviderNumber
	,@SurgeonID
	,@SurgeonLastName
	,@SurgeonFirstName
	,@HealthCareNumber
	,@HCNVersion
	,@HCNProvince
	,@Gender
	,@BirthDate
	,@MaidenName
	,@LastName
	,@MiddleName
	,@FirstName
	,@PostalCode
	,@SideLocation
	,@ReplacementType
	,@PrimaryProcedureType
	,@DiagnosisGrouping
	,@RevisionReason
	,@CoderNumber
	,2 --,@IsDeleted
	,@IsValidated
	,@IsCompleted
	,2 --,@IsSubmited
	,@IsCorrected
	,@FixedChartNumber 
	,@IsCustomValidated
	--,@CIHIDateSent
)

--declare @P as int 
--declare @V as int
--select top 1 @P = PatientID from CM_CPI where ChartNumber = @ChartNumber and (isnull(HospitalID, 0) = 0 or @HospitalID = case @HospitalID when 0 then 0 else isnull(HospitalID, 0) end) --PR-04125
--select top 1 @V = isnull(VolumeID, 0) from CM_CPI_Volume where PatientID = @P and (([VolumeDatefrom] <= @SurgeryDate) and (@SurgeryDate <= [VolumenDateTo])) order by VolumeNumber desc, VolumeID desc
--if isnull(@V, 0) = 0 
--    select top 1 @V = isnull(VolumeID, 0) from CM_CPI_Volume where PatientID = @P order by VolumenDateTo desc, VolumeID desc
 
--exec P_UpdateAbstractVolume @V, 0, @RecordID 
return @RecordID
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_CJRR_AcetabularComponent]
	(@RecordID				[int]
	,@Occurrence			[int]
	,@StickerCode			[int]
	,@Manufacturer			[int]
	,@OtherManufacturer		[varchar] (100)
	,@CatalogueNumber		[varchar] (60)
	,@LotNumber				[varchar] (60)
	)
AS 
INSERT INTO [CJRR_AcetabularComponent] 
	([RecordID]
	,[Occurrence]
	,[StickerCode]
	,[Manufacturer]
	,[OtherManufacturer]
	,[CatalogueNumber]
	,[LotNumber]
	) 
VALUES 
	(@RecordID
	,@Occurrence
	,@StickerCode
	,@Manufacturer
	,@OtherManufacturer
	,@CatalogueNumber
	,@LotNumber
	)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_CJRR_AcetabularInsert]
	(@RecordID				[int]
	,@Occurrence			[int]
	,@StickerCode			[int]
	,@Manufacturer			[int]
	,@OtherManufacturer		[varchar] (100)
	,@CatalogueNumber		[varchar] (60)
	,@LotNumber				[varchar] (60)
	)
AS 
INSERT INTO [CJRR_AcetabularInsert] 
	([RecordID]
	,[Occurrence]
	,[StickerCode]
	,[Manufacturer]
	,[OtherManufacturer]
	,[CatalogueNumber]
	,[LotNumber]
	) 
VALUES 
	(@RecordID
	,@Occurrence
	,@StickerCode
	,@Manufacturer
	,@OtherManufacturer
	,@CatalogueNumber
	,@LotNumber
	)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_CJRR_Cement]
	(@RecordID				[int]
	,@Occurrence			[int]
	,@StickerCode			[int]
	,@Name					[int]
	,@OtherName				[varchar] (100)
	,@CatalogueNumber		[varchar] (60)
	,@LotNumber				[varchar] (60)
	)
AS 
INSERT INTO [CJRR_Cement] 
	([RecordID]
	,[Occurrence]
	,[StickerCode]
	,[Name]
	,[OtherName]
	,[CatalogueNumber]
	,[LotNumber]
	) 
VALUES 
	(@RecordID
	,@Occurrence
	,@StickerCode
	,@Name
	,@OtherName
	,@CatalogueNumber
	,@LotNumber
	)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_CJRR_FemoralComponent]
	(@RecordID				[int]
	,@Occurrence			[int]
	,@StickerCode			[int]
	,@Manufacturer			[int]
	,@OtherManufacturer		[varchar] (100)
	,@CatalogueNumber		[varchar] (60)
	,@LotNumber				[varchar] (60)
	)
AS 
INSERT INTO [CJRR_FemoralComponent] 
	([RecordID]
	,[Occurrence]
	,[StickerCode]
	,[Manufacturer]
	,[OtherManufacturer]
	,[CatalogueNumber]
	,[LotNumber]
	) 
VALUES 
	(@RecordID
	,@Occurrence
	,@StickerCode
	,@Manufacturer
	,@OtherManufacturer
	,@CatalogueNumber
	,@LotNumber
	)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_CJRR_FemoralHead]
	(@RecordID				[int]
	,@Occurrence			[int]
	,@StickerCode			[int]
	,@Manufacturer			[int]
	,@OtherManufacturer		[varchar] (100)
	,@CatalogueNumber		[varchar] (60)
	,@LotNumber				[varchar] (60)
	)
AS 
INSERT INTO [CJRR_FemoralHead] 
	([RecordID]
	,[Occurrence]
	,[StickerCode]
	,[Manufacturer]
	,[OtherManufacturer]
	,[CatalogueNumber]
	,[LotNumber]
	) 
VALUES 
	(@RecordID
	,@Occurrence
	,@StickerCode
	,@Manufacturer
	,@OtherManufacturer
	,@CatalogueNumber
	,@LotNumber
	)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_CJRR_PatellarComponent]
	(@RecordID				[int]
	,@Occurrence			[int]
	,@StickerCode			[int]
	,@Manufacturer			[int]
	,@OtherManufacturer		[varchar] (100)
	,@CatalogueNumber		[varchar] (60)
	,@LotNumber				[varchar] (60)
	)
AS 
INSERT INTO [CJRR_PatellarComponent] 
	([RecordID]
	,[Occurrence]
	,[StickerCode]
	,[Manufacturer]
	,[OtherManufacturer]
	,[CatalogueNumber]
	,[LotNumber]
	) 
VALUES 
	(@RecordID
	,@Occurrence
	,@StickerCode
	,@Manufacturer
	,@OtherManufacturer
	,@CatalogueNumber
	,@LotNumber
	)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_CJRR_TibialComponent]
	(@RecordID				[int]
	,@Occurrence			[int]
	,@StickerCode			[int]
	,@Manufacturer			[int]
	,@OtherManufacturer		[varchar] (100)
	,@CatalogueNumber		[varchar] (60)
	,@LotNumber				[varchar] (60)
	)
AS 
INSERT INTO [CJRR_TibialComponent] 
	([RecordID]
	,[Occurrence]
	,[StickerCode]
	,[Manufacturer]
	,[OtherManufacturer]
	,[CatalogueNumber]
	,[LotNumber]
	) 
VALUES 
	(@RecordID
	,@Occurrence
	,@StickerCode
	,@Manufacturer
	,@OtherManufacturer
	,@CatalogueNumber
	,@LotNumber
	)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_CJRR_TibialInsert]
	(@RecordID				[int]
	,@Occurrence			[int]
	,@StickerCode			[int]
	,@Manufacturer			[int]
	,@OtherManufacturer		[varchar] (100)
	,@CatalogueNumber		[varchar] (60)
	,@LotNumber				[varchar] (60)
	)
AS 
INSERT INTO [CJRR_TibialInsert] 
	([RecordID]
	,[Occurrence]
	,[StickerCode]
	,[Manufacturer]
	,[OtherManufacturer]
	,[CatalogueNumber]
	,[LotNumber]
	) 
VALUES 
	(@RecordID
	,@Occurrence
	,@StickerCode
	,@Manufacturer
	,@OtherManufacturer
	,@CatalogueNumber
	,@LotNumber
	)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CJRR_UDFieldsDate]
	(@RecordID 	[int],
	 @UDDate1 	[datetime],
	 @UDDate2 	[datetime],
	 @UDDate3 	[datetime],
	 @UDDate4 	[datetime],
	 @UDDate5 	[datetime],	 	 	 	 
	 @UDDate6 	[datetime],
	 @UDDate7 	[datetime],
	 @UDDate8 	[datetime],
	 @UDDate9 	[datetime],
	 @UDDate10 	[datetime],
	 @UDDate11 	[datetime],
	 @UDDate12 	[datetime],
	 @UDDate13 	[datetime],
	 @UDDate14 	[datetime],
	 @UDDate15 	[datetime],
	 @UDDate16 	[datetime],
	 @UDDate17 	[datetime],
	 @UDDate18 	[datetime],
	 @UDDate19 	[datetime],
	 @UDDate20 	[datetime],
	 @UDDate21 	[datetime],
	 @UDDate22 	[datetime],
	 @UDDate23 	[datetime],
	 @UDDate24 	[datetime],
	 @UDDate25 	[datetime])
as 
insert into [dbo].[CJRR_UDFieldsDate] 
	 ([RecordID],
	 [UDDate1],
	 [UDDate2],
	 [UDDate3],
	 [UDDate4],
	 [UDDate5],
	 [UDDate6],
	 [UDDate7],
	 [UDDate8],
	 [UDDate9],
	 [UDDate10],
	 [UDDate11],
	 [UDDate12],
	 [UDDate13],
	 [UDDate14],
	 [UDDate15],
	 [UDDate16],
	 [UDDate17],
	 [UDDate18],
	 [UDDate19],
	 [UDDate20],
	 [UDDate21],
	 [UDDate22],
	 [UDDate23],
	 [UDDate24],
	 [UDDate25]) 
values
	(@RecordID,
	 @UDDate1,
	 @UDDate2,
	 @UDDate3,
	 @UDDate4,
	 @UDDate5,
	 @UDDate6,
	 @UDDate7,
	 @UDDate8,
	 @UDDate9,
	 @UDDate10,
	 @UDDate11,
	 @UDDate12,
	 @UDDate13,
	 @UDDate14,
	 @UDDate15,
	 @UDDate16,
	 @UDDate17,
	 @UDDate18,
	 @UDDate19,
	 @UDDate20,
	 @UDDate21,
	 @UDDate22,
	 @UDDate23,
	 @UDDate24,
	 @UDDate25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CJRR_UDFieldsInteger]
	(@RecordID 	[int],
	 @UDInteger1 	[varchar](50),	
	 @UDInteger2 	[varchar](50),	
	 @UDInteger3 	[varchar](50),	
	 @UDInteger4 	[varchar](50),	
	 @UDInteger5 	[varchar](50),		 	 	 	 
	 @UDInteger6 	[varchar](50),
	 @UDInteger7 	[varchar](50),
	 @UDInteger8 	[varchar](50),
	 @UDInteger9 	[varchar](50),
	 @UDInteger10 	[varchar](50),
	 @UDInteger11 	[varchar](50),
	 @UDInteger12 	[varchar](50),
	 @UDInteger13 	[varchar](50),
	 @UDInteger14 	[varchar](50),
	 @UDInteger15 	[varchar](50),
	 @UDInteger16 	[varchar](50),
	 @UDInteger17 	[varchar](50),
	 @UDInteger18 	[varchar](50),
	 @UDInteger19 	[varchar](50),
	 @UDInteger20 	[varchar](50),
	 @UDInteger21 	[varchar](50),
	 @UDInteger22 	[varchar](50),
	 @UDInteger23 	[varchar](50),
	 @UDInteger24 	[varchar](50),
	 @UDInteger25 	[varchar](50))
as 
insert into [dbo].[CJRR_UDFieldsInteger] 
	 ([RecordID],
	 [UDInteger1],	
	 [UDInteger2],	
	 [UDInteger3],	
	 [UDInteger4],	
	 [UDInteger5],		 	 	 	 
	 [UDInteger6],
	 [UDInteger7],
	 [UDInteger8],
	 [UDInteger9],
	 [UDInteger10],
	 [UDInteger11],
	 [UDInteger12],
	 [UDInteger13],
	 [UDInteger14],
	 [UDInteger15],
	 [UDInteger16],
	 [UDInteger17],
	 [UDInteger18],
	 [UDInteger19],
	 [UDInteger20],
	 [UDInteger21],
	 [UDInteger22],
	 [UDInteger23],
	 [UDInteger24],
	 [UDInteger25]) 
values
	(@RecordID,
	 @UDInteger1,	
	 @UDInteger2,	
	 @UDInteger3,	
	 @UDInteger4,	
	 @UDInteger5,		 	 	 	 	
	 @UDInteger6,
	 @UDInteger7,
	 @UDInteger8,
	 @UDInteger9,
	 @UDInteger10,
	 @UDInteger11,
	 @UDInteger12,
	 @UDInteger13,
	 @UDInteger14,
	 @UDInteger15,
	 @UDInteger16,
	 @UDInteger17,
	 @UDInteger18,
	 @UDInteger19,
	 @UDInteger20,
	 @UDInteger21,
	 @UDInteger22,
	 @UDInteger23,
	 @UDInteger24,
	 @UDInteger25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CJRR_UDFieldsLookUp]
	(@RecordID 	[int],
	 @UDLookUp1 	[int],	
	 @UDLookUp2 	[int],	
	 @UDLookUp3 	[int],	
	 @UDLookUp4 	[int],	
	 @UDLookUp5 	[int],		 	 	 	 
	 @UDLookUp6 	[int],
	 @UDLookUp7 	[int],
	 @UDLookUp8 	[int],
	 @UDLookUp9 	[int],
	 @UDLookUp10 	[int],
	 @UDLookUp11 	[int],
	 @UDLookUp12 	[int],
	 @UDLookUp13 	[int],
	 @UDLookUp14 	[int],
	 @UDLookUp15 	[int],
	 @UDLookUp16 	[int],
	 @UDLookUp17 	[int],
	 @UDLookUp18 	[int],
	 @UDLookUp19 	[int],
	 @UDLookUp20 	[int],
	 @UDLookUp21 	[int],
	 @UDLookUp22 	[int],
	 @UDLookUp23 	[int],
	 @UDLookUp24 	[int],
	 @UDLookUp25 	[int])
as 
insert into [dbo].[CJRR_UDFieldsLookUp] 
	 ([RecordID],
	 [UDLookUp1],	
	 [UDLookUp2],	
	 [UDLookUp3],	
	 [UDLookUp4],	
	 [UDLookUp5],
	 [UDLookUp6],
	 [UDLookUp7],
	 [UDLookUp8],
	 [UDLookUp9],
	 [UDLookUp10],
	 [UDLookUp11],
	 [UDLookUp12],
	 [UDLookUp13],
	 [UDLookUp14],
	 [UDLookUp15],
	 [UDLookUp16],
	 [UDLookUp17],
	 [UDLookUp18],
	 [UDLookUp19],
	 [UDLookUp20],
	 [UDLookUp21],
	 [UDLookUp22],
	 [UDLookUp23],
	 [UDLookUp24],
	 [UDLookUp25]) 
values
	(@RecordID,
	 @UDLookUp1,	
	 @UDLookUp2,	
	 @UDLookUp3,	
	 @UDLookUp4,	
	 @UDLookUp5,		 	 	 	 	
	 @UDLookUp6,
	 @UDLookUp7,
	 @UDLookUp8,
	 @UDLookUp9,
	 @UDLookUp10,
	 @UDLookUp11,
	 @UDLookUp12,
	 @UDLookUp13,
	 @UDLookUp14,
	 @UDLookUp15,
	 @UDLookUp16,
	 @UDLookUp17,
	 @UDLookUp18,
	 @UDLookUp19,
	 @UDLookUp20,
	 @UDLookUp21,
	 @UDLookUp22,
	 @UDLookUp23,
	 @UDLookUp24,
	 @UDLookUp25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CJRR_UDFieldsSmallText]
	(@RecordID 	[int],
	 @UDSmallText1 	[varchar](50),
	 @UDSmallText2 	[varchar](50),
	 @UDSmallText3 	[varchar](50),
	 @UDSmallText4 	[varchar](50),
	 @UDSmallText5 	[varchar](50),	 	 	 	 
	 @UDSmallText6 	[varchar](50),
	 @UDSmallText7 	[varchar](50),
	 @UDSmallText8 	[varchar](50),
	 @UDSmallText9 	[varchar](50),
	 @UDSmallText10 	[varchar](50),
	 @UDSmallText11 	[varchar](50),
	 @UDSmallText12 	[varchar](50),
	 @UDSmallText13 	[varchar](50),
	 @UDSmallText14 	[varchar](50),
	 @UDSmallText15 	[varchar](50),
	 @UDSmallText16 	[varchar](50),
	 @UDSmallText17 	[varchar](50),
	 @UDSmallText18 	[varchar](50),
	 @UDSmallText19 	[varchar](50),
	 @UDSmallText20 	[varchar](50),
	 @UDSmallText21 	[varchar](50),
	 @UDSmallText22 	[varchar](50),
	 @UDSmallText23 	[varchar](50),
	 @UDSmallText24 	[varchar](50),
	 @UDSmallText25 	[varchar](50))
as 
insert into [dbo].[CJRR_UDFieldsSmallText] 
	 ([RecordID],
	 [UDSmallText1],
	 [UDSmallText2],
	 [UDSmallText3],
	 [UDSmallText4],
	 [UDSmallText5],	 
	 [UDSmallText6],
	 [UDSmallText7],
	 [UDSmallText8],
	 [UDSmallText9],
	 [UDSmallText10],
	 [UDSmallText11],
	 [UDSmallText12],
	 [UDSmallText13],
	 [UDSmallText14],
	 [UDSmallText15],
	 [UDSmallText16],
	 [UDSmallText17],
	 [UDSmallText18],
	 [UDSmallText19],
	 [UDSmallText20],
	 [UDSmallText21],
	 [UDSmallText22],
	 [UDSmallText23],
	 [UDSmallText24],
	 [UDSmallText25]) 
values
	(@RecordID,
	 @UDSmallText1,
	 @UDSmallText2,
	 @UDSmallText3,
	 @UDSmallText4,
	 @UDSmallText5,	
	 @UDSmallText6,
	 @UDSmallText7,
	 @UDSmallText8,
	 @UDSmallText9,
	 @UDSmallText10,
	 @UDSmallText11,
	 @UDSmallText12,
	 @UDSmallText13,
	 @UDSmallText14,
	 @UDSmallText15,
	 @UDSmallText16,
	 @UDSmallText17,
	 @UDSmallText18,
	 @UDSmallText19,
	 @UDSmallText20,
	 @UDSmallText21,
	 @UDSmallText22,
	 @UDSmallText23,
	 @UDSmallText24,
	 @UDSmallText25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CJRR_UDFieldsText]
	(@RecordID 	[int],
	 @UDText1 	[varchar](255),	
	 @UDText2 	[varchar](255),	
	 @UDText3 	[varchar](255),	
	 @UDText4 	[varchar](255),	
	 @UDText5 	[varchar](255),		 	 	 	 
	 @UDText6 	[varchar](255),
	 @UDText7 	[varchar](255),
	 @UDText8 	[varchar](255),
	 @UDText9 	[varchar](255),
	 @UDText10 	[varchar](255),
	 @UDText11 	[varchar](255),
	 @UDText12 	[varchar](255),
	 @UDText13 	[varchar](255),
	 @UDText14 	[varchar](255),
	 @UDText15 	[varchar](255),
	 @UDText16 	[varchar](255),
	 @UDText17 	[varchar](255),
	 @UDText18 	[varchar](255),
	 @UDText19 	[varchar](255),
	 @UDText20 	[varchar](255),
	 @UDText21 	[varchar](255),
	 @UDText22 	[varchar](255),
	 @UDText23 	[varchar](255),
	 @UDText24 	[varchar](255),
	 @UDText25 	[varchar](255))
as 
insert into [dbo].[CJRR_UDFieldsText] 
	 ([RecordID],
	 [UDText1],	
	 [UDText2],	
	 [UDText3],	
	 [UDText4],	
	 [UDText5],	 
	 [UDText6],
	 [UDText7],
	 [UDText8],
	 [UDText9],
	 [UDText10],
	 [UDText11],
	 [UDText12],
	 [UDText13],
	 [UDText14],
	 [UDText15],
	 [UDText16],
	 [UDText17],
	 [UDText18],
	 [UDText19],
	 [UDText20],
	 [UDText21],
	 [UDText22],
	 [UDText23],
	 [UDText24],
	 [UDText25]) 
values
	(@RecordID,
	 @UDText1,	
	 @UDText2,	
	 @UDText3,	
	 @UDText4,	
	 @UDText5,	
	 @UDText6,
	 @UDText7,
	 @UDText8,
	 @UDText9,
	 @UDText10,
	 @UDText11,
	 @UDText12,
	 @UDText13,
	 @UDText14,
	 @UDText15,
	 @UDText16,
	 @UDText17,
	 @UDText18,
	 @UDText19,
	 @UDText20,
	 @UDText21,
	 @UDText22,
	 @UDText23,
	 @UDText24,
	 @UDText25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CJRR_UDFieldsTime]
	(@RecordID 	[int],
	 @UDTime1 	[datetime],	
	 @UDTime2 	[datetime],	
	 @UDTime3 	[datetime],	
	 @UDTime4 	[datetime],	
	 @UDTime5 	[datetime],		 	 	 	 
	 @UDTime6 	[datetime],
	 @UDTime7 	[datetime],
	 @UDTime8 	[datetime],
	 @UDTime9 	[datetime],
	 @UDTime10 	[datetime],
	 @UDTime11 	[datetime],
	 @UDTime12 	[datetime],
	 @UDTime13 	[datetime],
	 @UDTime14 	[datetime],
	 @UDTime15 	[datetime],
	 @UDTime16 	[datetime],
	 @UDTime17 	[datetime],
	 @UDTime18 	[datetime],
	 @UDTime19 	[datetime],
	 @UDTime20 	[datetime],
	 @UDTime21 	[datetime],
	 @UDTime22 	[datetime],
	 @UDTime23 	[datetime],
	 @UDTime24 	[datetime],
	 @UDTime25 	[datetime])
as 
insert into [dbo].[CJRR_UDFieldsTime] 
	 ([RecordID],
	 [UDTime1],	
	 [UDTime2],	
	 [UDTime3],	
	 [UDTime4],	
	 [UDTime5],		 
	 [UDTime6],
	 [UDTime7],
	 [UDTime8],
	 [UDTime9],
	 [UDTime10],
	 [UDTime11],
	 [UDTime12],
	 [UDTime13],
	 [UDTime14],
	 [UDTime15],
	 [UDTime16],
	 [UDTime17],
	 [UDTime18],
	 [UDTime19],
	 [UDTime20],
	 [UDTime21],
	 [UDTime22],
	 [UDTime23],
	 [UDTime24],
	 [UDTime25]) 
values
	(@RecordID,
	 @UDTime1,	
	 @UDTime2,	
	 @UDTime3,	
	 @UDTime4,	
	 @UDTime5,		
	 @UDTime6,
	 @UDTime7,
	 @UDTime8,
	 @UDTime9,
	 @UDTime10,
	 @UDTime11,
	 @UDTime12,
	 @UDTime13,
	 @UDTime14,
	 @UDTime15,
	 @UDTime16,
	 @UDTime17,
	 @UDTime18,
	 @UDTime19,
	 @UDTime20,
	 @UDTime21,
	 @UDTime22,
	 @UDTime23,
	 @UDTime24,
	 @UDTime25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [I_CJRR_UpdateHistory] 
	@RecordID as int,
	@Coder as int,
	@UpdateType as varchar(10) = 'Saved'
AS 

declare @HID as int --NP-00025
select @HID = HospitalID from U_Users where Code = @Coder

insert into CJRR_UpdateHistory (RecordID, HospitalID, Coder, Updated, UpdateType) 
values (@RecordID, @HID, @Coder, GetDate(), @UpdateType)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EN-00183: @LoanReason 
CREATE  PROCEDURE [I_CL_Activity]
	(
     @HospitalID 		[int],
     @VolumeID 		    [int],
	 @ActivityType 		[int],
	 @ActivityDateOut 	[datetime],
	 @ActivityTimeOut 	[datetime],
	 @ActivityCoderOut	[int],
	 @ActivityBorrower 	[int],
	 @ActivityLocation 	[int],
	 @ActivityExpectReturn	[datetime],
	 @ActivityNotes		VarChar(255),
     @RequestPriority   int,
     @BoxNumber         varchar(250), 
     @NewPermLocation   int,
     @LoanReason        varchar(250),
	 @PullID		    int = Null)
AS 

	Declare @UniqueID as int
	Declare @CurrLocation as int
    Declare @CLPullDate datetime, @CLPullTime datetime
    Declare @CLPullOutDate datetime, @CLPullOutTime datetime
    Declare @PreviousID int
    declare @PreActivityID int
    --PR-00730
    declare @PrePreActivityID int

    declare @PrePullID int
    --PR-00729
    declare @PrevBorrower int
    declare @PermLocation int
    declare @PrevLocation int
    declare @PreType      int
    declare @ActivityDateIn datetime
    -- PR-01514
    declare @ReturnID     int
    -- PR - 01663
    declare @InHealthDepart varchar(12)

    if isnull(@HospitalID, 0) = 0
        set @HospitalID = isnull((select top 1 v.HospitalID from LoanLU_Location v where code = @ActivityLocation), 0)
    
--        set @HospitalID = isnull((select top 1 v.HospitalID from CM_CPI C inner join CM_CPI_Volume v on C.PatientID = v.PatientID where VolumeID = @VolumeID), 0)
    
    --EN-00183 & PR-00729
    select top 1 
        @PreviousID   = CLActivityID, 
        @CurrLocation = isnull(CLCurrentLocation, 0),
        @PrevLocation = isnull(CLPreviousLocation, 0),
        @PermLocation = isnull(PermLocation, 0),
        @PreType      = isnull(ActivityType, 0)
    from CM_CPI_Volume 
    where VolumeID = @VolumeID

    if isnull(@PreviousID, 0) = 0
        set @PreviousID = (select top 1 CLActivityID from cl_activity      
            where VolumeID = @VolumeID and activitytype <> 4 --and CLActivityID < @PreviousID
            order by ActivityDateOut desc, ActivityTimeOut Desc, CLActivityID Desc)

    if @ActivityType = 7
    begin
        if isnull(@PreviousID, 0) = 0
            set @ActivityLocation = (select top 1 PermLocation from dbo.CM_CPI_Volume where VolumeID = @VolumeID)
        else
        begin
            --PR - 00730
            select top 1 @PreActivityID = CLPreActivityID, @PrevLocation = ActivityPrevLocation from dbo.CL_Activity where CLActivityID = @PreviousID and VolumeID = @VolumeID  --PR - 05318 add to check volume
            if isnull(@PreActivityID, 0) = 0 
            begin
                set @ActivityLocation = @PrevLocation
                set @PrevLocation = 0
            end
            else
            begin
                select 
                    @ActivityLocation = ActivityLocation,
                    @ActivityBorrower = ActivityBorrower,
                    @ActivityExpectReturn = ActivityExpectedReturn,
                    @ActivityNotes = ActivityNotes,
                    @CurrLocation = ActivityPrevLocation,   
                    @PrevLocation = ActivityPrevLocation, 
                    @CLPullDate = CLPullDate, 
                    @CLPullTime = CLPullTime, 
                    @CLPullOutDate = CLPullOutDate, 
                    @CLPullOutTime = CLPullOutTime,
                    @PrePullID = PullID,
                    @PreType = ActivityType,
                    @ActivityDateIn = ActivityDateIn,
                    @PrePreActivityID = @PreActivityID
                from cl_activity
                where CLActivityID = @PreActivityID and VolumeID = @VolumeID   --PR - 05318 add to check volumeid  --@PreviousID 
    
                if @PreType = 7    
                begin
                    set @PreActivityID = @PrePreActivityID
    
                    select top 1 @PrePreActivityID = CLPreActivityID
                    from cl_activity
                    where clactivityid = @PrePreActivityID and VolumeID = @VolumeID
    
                    while (isnull(@PreType, 0) = 7 and @PrePreActivityID > 0)
                    begin
                        select top 1 @PrePreActivityID = CLPreActivityID
                        from cl_activity
                        where clactivityid = @PrePreActivityID and VolumeID = @VolumeID --PR - 05318 add to check volumeID
    
                        set @PreActivityID = @PrePreActivityID
    
                        select top 1 @PreType = ActivityType, @PrePreActivityID = CLPreActivityID, 
                            @ActivityDateIn = ActivityDateIn
                        from cl_activity
                        where clactivityid = @PrePreActivityID and VolumeID = @VolumeID --PR - 05318 add to check volumeID
                    end
                end
    
                if @PreType = 1 and @ActivityDateIn is not null   
                begin
                    Update cl_activity 
                    set Activitydatein  = null, 
                        ActivityTimeIn  = null,
            			ActivityCoderIn = null 
            		where clactivityid = @PreActivityID and activitytype = 1 and VolumeID = @VolumeID --PR - 05318 add to check volumeID
    
                    if @PrePullID > 0
                        update CL_PullList set IsReturned = 0 where PullID = @PrePullID
                end
            end
            -- PR - 02196 Add return date for canceled loan.
            update cl_activity 
            set ActivityNotes = left(isnull(ActivityNotes, '') + ' -- This transaction has been canceled on ' + convert(varchar(10), @ActivityDateOut, 111), 250),
                Activitydatein  = (case when activitytype = 1 then @ActivityDateOut else Activitydatein end), 
                ActivityTimeIn  = (case when activitytype = 1 then @ActivityTimeOut else ActivityTimeIn end),
        		ActivityCoderIn = (case when activitytype = 1 then @ActivityCoderOut else ActivityCoderIn end)
            where CLActivityID = @PreviousID and VolumeID = @VolumeID --PR - 05318 add to check volumeID
    
        end
    end

	If @ActivityType <> 4
	Begin
		if @ActivityType not in (7)
        begin
    
            if isnull(@CurrLocation, 0) = 0
                set @CurrLocation = (select top 1 isnull(ActivityLocation, 0) from cl_activity where CLActivityID = @PreviousID and VolumeID = @VolumeID) --PR - 05318 add check volumeid

            -- This will only affect Loan Transaction
            -- PR - 01663
            if @ActivityType in (5, 1) --Return transaction will fill in laon activitydatein
            begin
                --PR - 00730
                --if @PreType = 1
                if @PreType = 1 and isnull((select top 1 Activitytype from cl_activity where clactivityid = @PreviousID and volumeID = @VolumeID), 0) = 1 --PR - 05318 add to check volumeID
                begin
            		Update cl_activity 
                    set Activitydatein = @ActivityDateOut, 
                        ActivityTimeIn = @ActivityTimeOut,
            			ActivityCoderIn = @ActivityCoderOut 
            		where clactivityid = @PreviousID and VolumeID = @VolumeID --PR - 05318 add check volmeid --and Activitytype = 1
    
                    set @PrePullID = (select top 1 PullID from cl_activity where clactivityid = @PreviousID and Activitytype = 1 and VolumeID = @VolumeID) --PR - 05318 add to check volumeID
                end
                else 
                begin
                    set @InHealthDepart = isnull((select top 1 YN.CIHIValue from LoanLu_Location l inner join
                                        LU_YesNoSystem YN on l.InHospital = YN.Code where l.code = @ActivityLocation), '0' )
                    if @InHealthDepart in ('1', 'Y') or @ActivityType = 1 or @PermLocation = @ActivityLocation
                    begin
                        select top 1 @PreActivityID = CLActivityid,  @PrePullID = PullID
                        from cl_activity 
                		where VolumeID = @VolumeID and activitytype = 1 and Activitydatein is null
                        order by CLActivityid desc
        
                		Update cl_activity 
                        set Activitydatein = @ActivityDateOut, 
                            ActivityTimeIn = @ActivityTimeOut,
                			ActivityCoderIn = @ActivityCoderOut 
                		where clactivityid = @PreActivityID and Activitytype = 1 and VolumeID = @VolumeID --PR - 05318 check volume also
                    end
                end
            end

            if @PrePullID > 0 
                update CL_PullList set IsReturned = 1 where PullID = @PrePullID

            --PR - 00729 to carry return previous borrower
            if @ActivityType = 5 
            begin
                set @ActivityBorrower = 0  -- PR - 01514
                if isnull(@PrevLocation, 0) = isnull(@ActivityLocation, 0) and
                   isnull(@PrevLocation, 0) <>  isnull(@PermLocation, 0) 
                begin
                    --PR - 01514
                    if not exists (select * from dbo.LoanLU_Location L inner join LU_YesNoSystem YN on InHospital = YN.code
                            where l.code = @ActivityLocation and YN.CIHIValue in ('1', 'Y'))
                    begin    
                        set @ReturnID = (select top 1 CLPreActivityID from cl_activity where CLActivityID = @PreviousID and VolumeID = @VolumeID) --PR - 05318 add check volume
                        set @ActivityBorrower = (select top 1 ActivityBorrower from cl_activity where CLActivityID = @ReturnID and VolumeID = @VolumeID  
                                            and ActivityLocation = @ActivityLocation and ActivityType <> 4) --PR - 05318 Add to check volume
                                    
    --                     set @ActivityBorrower = (select top 1 ActivityBorrower 
    --                          from cl_activity 
    --                          where VolumeID = @VolumeID and CLActivityID <> @PreviousID and ActivityType not in (4, 7)
    --                              and ActivityLocation = @PrevLocation
    --                              and ActivityNotes not like '%-- This transaction has been canceled on%'
    --                          order by ActivityDateOut desc, ActivityTimeOut Desc, CLActivityID Desc)
                    end
                end
            end
		end
    
        if isnull(@PullID, 0) <> 0
        begin
    		Update CL_PullList 
            set PullListStatus = 1,
                LoanDate = convert(varchar(50), getdate(), 111), 
                LoanTime = convert(varchar(50), getdate(), 108),
                Puller   = @ActivityBorrower,
                LoanReason = @LoanReason 
            where PullID = @PullID 
    
            select top 1 
                @CLPullDate = PullDate, @CLPullTime = PullTime,
                @CLPullOutDate = PullOutDate, @CLPullOutTime = PullOutTime
            from CL_PullList
            where PullID = @PullID 

        end
	end
	Else
		Print ''
/*	Delete CL_Activity where clactivityid = (Select top 1 clactivityid from CL_Activity where volumeid = @Volumeid 
		and activitydateout >= @ActivityDateOut and activitytype = 4 order by activitydateout)
*/

set @UniqueID = isnull((select max(clActivityID) from CL_Activity), '0') + 1

INSERT INTO [dbo].[CL_Activity] 
	 (
     [CLActivityID], 
     [HospitalID], 
     [VolumeID],
	 [ActivityType],
	 [ActivityDateOut],
	 [ActivityTimeOut],
	 [ActivityCoderOut],
	 [ActivityBorrower],
	 [ActivityLocation],
	 [ActivityPrevLocation],
	 [ActivityNotes],
	 [ActivityExpectedReturn],
     [CLPullDate],
     [CLPullTime],
     [CLPullOutDate],
     [CLPullOutTime],
     [CLRequestPriority],
     [CLNewPermLocation],
     [LoanReason],
     [PullID],
     [CLPreActivityID]) 
VALUES 
	( @UniqueID, @HospitalID, @VolumeID,
	 @ActivityType,
	 @ActivityDateOut,
	 @ActivityTimeOut,
	 @ActivityCoderOut,
	 @ActivityBorrower,
	 @ActivityLocation,
	 @CurrLocation,
	 @ActivityNotes,
	 @ActivityExpectReturn,
     @CLPullDate,
     @CLPullTime,
     @CLPullOutDate,
     @CLPullOutTime,
     @RequestPriority,
     @NewPermLocation,
     @LoanReason,
     @PullID,
     @PreviousID)

--EN-00183
if @ActivityType <> 4
begin
    if @ActivityType = 6 
    begin
		Update CM_CPI_Volume 
        set CLCurrentLocation = @ActivityLocation,
            CLBoxNumber = (case when isnull(@BoxNumber, '') = '' then CLBoxNumber
                                when isnull(CLBoxNumber, '') = '' then @BoxNumber
                                else left(ltrim(rtrim(@BoxNumber)) + ';' + ltrim(rtrim(CLBoxNumber)), 250)
                           end) ,
            PermLocation = @NewPermLocation,
            CLPreviousLocation = CLCurrentLocation,
            ActivityType = @ActivityType,
            CLActivityID = @UniqueID
        Where VolumeID = @VolumeID	

        set @ActivityBorrower = 0
    end
    else
    begin
        Update CM_CPI_Volume 
        set CLCurrentLocation = @ActivityLocation, 
            CLPreviousLocation = (case when @ActivityType = 7 then @PrevLocation else CLCurrentLocation end),
            ActivityType = (case when @ActivityType = 7 then @PreType else @ActivityType end),
            CLActivityID = @UniqueID
        Where VolumeID = @VolumeID	
    end
end
--Ticket 9919
--Delete the oldest activity if it total number is over the limit.
declare @MaxActivity int
declare @Total       int
declare @MinAct      int

if isnull(@HospitalID, 0) = 0
begin
    set @MaxActivity = (select max(MaxActivityNumber) from H_HospitalProfile)
end
else
    set @MaxActivity = (select top 1 MaxActivityNumber from H_HospitalProfile where HospitalID = @HospitalID)

if @MaxActivity > 0
begin
    set @Total = @MaxActivity + 1
    while(@Total > @MaxActivity)
    begin
        select @Total = count(*), @MinAct = min(CLActivityID) from CL_Activity where VolumeID = @VolumeID and ActivityType <> 4
        if @Total > @MaxActivity 
        begin
            delete from CL_Activity where CLActivityID = @MinAct
            --delete from CL_ActivityUpdateHistory where CLActivityID = @MinAct
            set @Total = @Total - 1
        end
    end
end

RETURN @UniqueID
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


--13008
CREATE PROCEDURE [I_CL_PullList]
	(@HospitalID	[int],
	 @PullListID 	[varchar](50),
	 @PullLocation 	[int],
	 @PullDate 	[datetime],
	 @PullTime 	[datetime],
	 @Puller 	[int],
	 @PullNotes	[varchar](255),
	 @VolumeID 	[int],
     @LoanNote  varchar(250),
     @PullOutDate datetime,
     @PullOutTime datetime,
     @RequestPriority int,
     @PullID int,
     @LoanReason varchar(250),
     @Coder  int)
AS 
-- delete from CL_PullList
-- where PullListID = @PullListID 
--     and VolumeID = @VolumeID
--     AND (ISNULL(HospitalID, 0) = 0 OR @HospitalID = case @HospitalID when 0 then 0 else ISNULL(HospitalID, 0) end)            
if @PullID = 0 
begin
    INSERT INTO [dbo].[CL_PullList] 
    	 ([HospitalID],
    	 [PullListID],
    	 [PullLocation],
    	 [PullDate],
    	 [PullTime],
    	 [Puller],
    	 [PullNotes],
    	 [VolumeID], 
         [LoanNote],
         [PullOutDate],
         [PullOutTime],
         [CLRequestPriority],
         PullListStatus,
         LoanReason) 
    VALUES 
    	(@HospitalID,
    	 @PullListID,
    	 @PullLocation,
    	 @PullDate,
    	 @PullTime,
    	 @Puller,
    	 @PullNotes,
    	 @VolumeID,
         @LoanNote,
         @PullOutDate,
         @PullOutTime,
         @RequestPriority,
         0,
         @LoanReason)
    set @PullID = @@Identity

    INSERT INTO CL_PullListUpdateHistory (PullID, PullListID, VolumeID, Coder, Updated, UpdateType) 
    VALUES (@PullID, @PullListID, @VolumeID, @Coder, GetDate(), 'Create')

end
else
begin
    update CL_PullList
    set HospitalID   = @HospitalID,
    	PullListID   = @PullListID,
    	PullLocation = @PullLocation,
    	PullDate     = @PullDate,
    	PullTime     = @PullTime,
    	Puller       = @Puller,
    	PullNotes    = @PullNotes,
    	VolumeID     = @VolumeID, 
        LoanNote     = @LoanNote,
        PullOutDate  = @PullOutDate,
        PullOutTime  = @PullOutTime,
        CLRequestPriority = @RequestPriority,
        LoanReason   = @LoanReason
    where PullID = @PullID

    INSERT INTO CL_PullListUpdateHistory (PullID, PullListID, VolumeID, Coder, Updated, UpdateType) 
    VALUES (@PullID, @PullListID, @VolumeID, @Coder, GetDate(), 'Saved')

end
return(@PullID)






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


--EN-00183
CREATE PROCEDURE [I_CL_PullList_FromPurged]
	(@PullID	[int],  @Coder 	[int])
AS 
    SET IDENTITY_INSERT  CL_PullList ON 

    INSERT INTO [dbo].[CL_PullList] 
    	 ([HospitalID],
    	 [PullListID],
    	 [PullLocation],
    	 [PullDate],
    	 [PullTime],
    	 [Puller],
    	 [PullNotes],
    	 [VolumeID], 
         [LoanNote],
         [PullOutDate],
         [PullOutTime],
         [CLRequestPriority],
         PullListStatus,
         LoanReason,
         PullID) 
    select
    	HospitalID,
    	PullListID,
    	PullLocation,
    	PullDate,
    	PullTime,
    	Puller,
    	PullNotes,
    	VolumeID,
        LoanNote,
        PullOutDate,
        PullOutTime,
        CLRequestPriority,
        0,
        LoanReason,
        PullID
    from CL_PullList_Purged
    where PullID = @PullID


    INSERT INTO CL_PullListUpdateHistory (PullID, PullListID, VolumeID, Coder, Updated, UpdateType) 
    select PullID, PullListID, VolumeID, @Coder, GetDate(), 'Restore'
    from CL_PullList_Purged
    where PullID = @PullID

    delete from CL_PullList_Purged where PullID = @PullID

    SET IDENTITY_INSERT  CL_PullList off 

return(@PullID)






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE  PROCEDURE [I_CL_PullListUpdateHistory] 
    @PullID as int,
    @PullListID As varchar(50), 
    @VolID As int, 
	@Coder as int,
	@UpdateType as varchar(10) = 'Saved'
AS 
    if isnull(@PullListID, '') = ''
        set @PullListID = (select top 1 PullListID from CL_PullList where PullID = @PullID)

    INSERT INTO CL_PullListUpdateHistory (PullID, PullListID, VolumeID, Coder, Updated, UpdateType) 
    VALUES (@PullID, @PullListID, @VolID, @Coder, GetDate(), @UpdateType)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [I_CL_UpdateHistory] 
    @ActID As int, 
	@Coder as int,
	@UpdateType as varchar(10) = 'Saved'
AS 

    INSERT INTO CL_ActivityUpdateHistory (CLActivityID, Coder, Updated, UpdateType) 
    VALUES (@ActID, @Coder, GetDate(), @UpdateType)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE  PROCEDURE [I_CL_UpdateHistory_FromCPI] 
    @PatientID  as int,
	@Coder as int,
	@UpdateType as varchar(10) = 'Saved'
AS 
    INSERT INTO CL_ActivityUpdateHistory (CLActivityID, Coder, Updated, UpdateType) 
    select A.CLActivityID, @Coder, GetDate(), @UpdateType
    from CL_Activity A
        inner join CM_CPI_Volume V on A.VolumeID = V.VolumeID
    where V.PatientID = @PatientID 
--    and (isnull(C.HospitalID, 0) = 0 or C.HospitalID = isnull(@HospitalID, 0))



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_CM_Address]
	(@PatientID	 	[int],
	 @Occurrence	 	[int],
	 @ContactType	 	[int],
	 @ContactName 	[varchar](60),
	 @Relationship	 	[int],
	 @Address1	 	[varchar](60),
	 @Address2	 	[varchar](60),
	 @City			[varchar](50),
	 @Province		[int],
	 @Country		[int],
	 @PostalCode	 	[varchar](12),
	 @PhoneNumber1 	[varchar](20),
	 @PhoneNumber2 	[varchar](20),
	 @CellPhone		[varchar](20),
	 @FaxNumber	 	[varchar](20),
	 @EMail		[varchar](50))

AS 
INSERT INTO [dbo].[CM_Address] 
	 ([PatientID],
	 [Occurrence],
	 [ContactType],
	 [ContactName],
	 [Relationship],
	 [Address1],
	 [Address2],
	 [City],
	 [Province],
	 [Country],
	 [PostalCode],
	 [PhoneNumber1],
	 [PhoneNumber2],
	 [CellPhone],
	 [FaxNumber],
	 [EMail]) 
VALUES 
	(@PatientID,
	 @Occurrence,
	 @ContactType,
	 @ContactName,
	 @Relationship,
	 @Address1,
	 @Address2,
	 @City,
	 @Province,
	 @Country,
	 @PostalCode,
	 @PhoneNumber1,
	 @PhoneNumber2,
	 @CellPhone,
	 @FaxNumber,
	 @EMail)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [I_CM_Alert]
	(@PatientID 		[int],
	 @AlertOccurrence	[int],
	 @AlertCode		[int],
	 @AlertNote		[varchar](250),
	 @OffendingAgent 	[int], 
	 @DrugCode 		[varchar](50), 
	 @StartDate 		[datetime], 
	 @Severity 		[int])
AS 
INSERT INTO [CM_Alert] 
	 ([PatientID],
	 [AlertOccurrence],
	 [AlertCode],
	 [AlertNote],
	 [OffendingAgent], 
	 [DrugCode], 
 	 [StartDate], 
	 [Severity]) 
VALUES 
	(@PatientID,
	 @AlertOccurrence,
	 @AlertCode,
	 @AlertNote,
	 @OffendingAgent, 
	 @DrugCode, 
	 @StartDate, 
	 @Severity)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_CM_Alias]
   (@PatientID             [int],
    @AliasOccurrence       [int],
    @MaidenAlias           [varchar](35),
    @LastAlias             [varchar](40),
    @MiddleAlias           [varchar](15),
    @FirstAlias            [varchar](35))
AS 

INSERT INTO [CM_Alias] 
    ([PatientID],
    [AliasOccurrence],
    [MaidenAlias],
    [LastAlias],
    [MiddleAlias],
    [FirstAlias]) 
 
VALUES 
   (@PatientID,
    @AliasOccurrence,
    @MaidenAlias,
    @LastAlias,
    @MiddleAlias,
    @FirstAlias)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [I_CM_BabyChart]
	(@PatientID			[int],
	 @BabyChartOccurrence		[int],
	 @BabyChartNumber		[varchar](10))
AS 

INSERT INTO [CM_BabyChart] 
	 ([PatientID],
	 [BabyChartOccurrence],
	 [BabyChartNumber]) 
 
VALUES 
	(@PatientID,
	 @BabyChartOccurrence,
	 @BabyChartNumber)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [I_CM_ChartLink]
	(@PatientID	 	[int],
	 @LinkChartOccurrence	[int],
     @LinkPatientID	[int],
	 --@LinkChartNumber	[varchar](10),
	 @LinkType		[int])
AS 

INSERT INTO [CM_ChartLink] 
	 ([PatientID],
	 [LinkChartOccurrence],
	 --[LinkChartNumber],
	 [LinkPatientID],
	 [LinkType]) 
 
VALUES 
	(@PatientID,
	 @LinkChartOccurrence,
	 --@LinkChartNumber,
     @LinkPatientID,
	 @LinkType)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_CM_CPI]
   (@PatientID             [int],
    @ChartNumber           [varchar](10),
    @MaidenName    [varchar](35),
    @LastName              [varchar](40),
    @MiddleName            [varchar](15),
    @FirstName             [varchar](35),
    @DeathDate             [datetime],
    @Gender                [int],
    @BirthDate             [datetime],
    @BirthDateEstimated    [int],
    @BirthPlace            [varchar](20),
    @LanguageCode  [int],
    @EducationLevel        [int],  
    @MaritalStatus         [int],
    @LivingArrangement     [int],
    @PrimaryAddress        [varchar](60),
    @PostalCode            [varchar](12),
    @ResidenceCode         [int],
    @ResidenceType         [int],
    @PrimaryPhone  [varchar](15),
    @HCNProvince   [int],
    @HealthCareNumber      [varchar](12),
    @HCNVersion            [varchar](2),
    @InsurCompany1         [int],
    @InsurPolicy1          [varchar](15),
    @InsurCompany2         [int],
    @InsurPolicy2          [varchar](15),
    @Occupation            [int],
    @SocialInsurNumber     [varchar](9),
    @OptionField1          [int],
    @OptionField2          [int],
    @Secret                [int],
    @DuplicateChart        [varchar](10),
    @MothersChart          [varchar](10),
    @Salutation            [varchar](10),
    @BirthName             [varchar](35),
    @CellPhone             [varchar](15),
    @FaxNumber             [varchar](15), 
    @EMail                 [varchar](50), 
    @LinkProviderNumber    [int],
    @PrimaryAddress2       [varchar](60),
    @City                  [varchar](30), 
    @Province              [int], 
    @Country               [int],
    @UniqiueLifetimeID     [varchar](20),
    @GroupNum1             [varchar](50), 
    @GroupNum2             [varchar](50), 
    @WSIB          	   [varchar](50),
    @DiagMethod 	[int], 
    @FirstDiagDate 	[datetime], 
    @FutureDate 		[datetime], 
    @MedReferralDate 	[datetime], 
    @RadReferralDate 	[datetime], 
    @SupCareReferralDate [datetime],
    @HospitalID		   [int],
    @LabelPrinted	[int],
    @MasterChart	[int],
    @DeathIndicator	[int],
    @LastVisitDate	[datetime],
    @SensitivityLevel 	[int] ,
    @RegionalPatientID	[varchar](50),
    @IAR_ConsentFlag	[int],
    @FixedChartNumber	[varchar](50),
    @LockedChart        int,
    @HighRisk           int,
    @ROILegalComments   [varchar](500)
)
AS 
SELECT @PatientID = (SELECT isnull(MAX(PatientID), 0) FROM CM_CPI) + 1
INSERT INTO [CM_CPI] 
    ([PatientID],
    [HospitalID],
    [LabelPrinted],
    [IsDeleted],
    [ChartNumber],
    [UniqiueLifetimeID],
    [MaidenName],
    [LastName],
    [MiddleName],
    [FirstName],
    [DeathDate],
    [DeathIndicator],
    [Gender],
    [BirthDate],
    [BirthDateEstimated],
    [BirthPlace],
    [LanguageCode],
    [EducationLevel],
    [MaritalStatus],
    [LivingArrangement],
    [PrimaryAddress],
    [PostalCode],
    [ResidenceCode],
    [ResidenceType],
    [PrimaryPhone],
    [HCNProvince],
    [HealthCareNumber],
    [HCNVersion],
    [InsurCompany1],
    [InsurPolicy1],
    [InsurCompany2],
    [InsurPolicy2],
    [Occupation],
    [SocialInsurNumber],
    [OptionField1],
    [OptionField2],
    [LinkProviderNumber],
    [Secret],
    [MasterChart],
    [DuplicateChart],
    [MothersChart],
    [Salutation],
    [BirthName],
    [CellPhone],
    [FaxNumber], 
    [EMail], 
    [PrimaryAddress2], 
    [City], 
    [Province], 
    [Country],
    [GroupNum1], 
    [GroupNum2], 
    [WSIB],
    [DiagMethod], 
    [FirstDiagDate], 
    [FutureDate], 
    [MedReferralDate], 
    [RadReferralDate], 
    [SupCareReferralDate],
    [LastVisitDate],
    [SensitivityLevel],
    [RegionalPatientID],
	[IAR_ConsentFlag],
	[FixedChartNumber],
	[LockedChart],
    [HighRisk],
    [ROILegalComments]) 
VALUES 
   (@PatientID, 
    @HospitalID,
    @LabelPrinted,
    2,
    @ChartNumber,
    @UniqiueLifetimeID,
    @MaidenName,
    replace(@LastName, '''''', ''''),
    @MiddleName,
    @FirstName,
    @DeathDate,
    @DeathIndicator,
    @Gender,
    @BirthDate,
    @BirthDateEstimated,
    @BirthPlace,
    @LanguageCode,
    @EducationLevel,
    @MaritalStatus,
    @LivingArrangement,
    @PrimaryAddress,
    @PostalCode,
    @ResidenceCode,
    @ResidenceType,
    @PrimaryPhone,
    @HCNProvince,
    @HealthCareNumber,
    @HCNVersion,
    @InsurCompany1,
    @InsurPolicy1,
    @InsurCompany2,
    @InsurPolicy2,
    @Occupation,
    @SocialInsurNumber,
    @OptionField1,
    @OptionField2,
    @LinkProviderNumber,
    @Secret,
    @MasterChart,
    @DuplicateChart,
    @MothersChart,
    @Salutation,
    @BirthName,
    @CellPhone,
    @FaxNumber, 
    @EMail, 
    @PrimaryAddress2, 
    @City, 
    @Province, 
    @Country,
    @GroupNum1, 
    @GroupNum2, 
    @WSIB,
    @DiagMethod, 
    @FirstDiagDate, 
    @FutureDate, 
    @MedReferralDate, 
    @RadReferralDate, 
    @SupCareReferralDate,
    @LastVisitDate,
    @SensitivityLevel,
    @RegionalPatientID,
    @IAR_ConsentFlag,
    @FixedChartNumber,
    @LockedChart,
    @HighRisk,
    @ROILegalComments
)
   --PR - 05191 Missing digital indicater parameter
   EXEC I_CM_CPI_Volume @PatientID, 0, '  000001', 0, NULL, NULL, NULL, 0, 0, NULL, 0, 0, 0, 0, 0, NULL, 0, 0, 0, 0, NULL, 0, 0, @HospitalID, @LabelPrinted, 0, 0, 0, null

   --NP-00025
   if isnull(@HospitalID, 0) <> 0 
	update CM_CPI_Volume set HospitalID = @HospitalID where PatientID = @PatientID

   RETURN @PatientID

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_CM_CPI_Volume]
	(@PatientID		[int],
	 @VolumeID		[int],
	 @VolumeNumber	[varchar](12),
	 @VolumeType	[int],
	 @BarCodeVolume 	[varchar](50),
	 @DateFrom		[datetime],
	 @DateTo		[datetime],
	 @PermLoc		[int],
	 @LinkVolume		[int],
	 @VolumeBox		[varchar](50),
	 @HasInpatient		[int],
	 @HasSDS		[int],
	 @HasOutpatient	[int],
	 @HasAmcare		[int],
	 @HasMicroFilm		[int],
	 @MircoFilmNum	[varchar](50),
	 @HasOption1		[int],
	 @HasOption2		[int],
	 @HasOption3		[int],
	 @HasOption4		[int],
	 @HasComments	[varchar](255),
	 @Location		[int],
	 @SubVolume		[int],
	 @HospitalID		[int],
	 @LabelPrinted		[int],
     @CLPreviousLocation [int],
     @UniversalID    bigint,
     @DigitalIndicator int,
     @DestructionDate datetime = null
    )
AS 

SELECT @VolumeID = (SELECT isnull(MAX(VolumeID), 0) FROM CM_CPI_Volume) + 1
INSERT INTO [CM_CPI_Volume] 
	 ([VolumeID],
	 [PatientID],
	 [HospitalID],
	 [LabelPrinted],
	 [VolumeNumber],
     [VolumeType],
	 [BarCodeVolume],
	 [VolumeDateFrom],
	 [VolumenDateTo],
	 [PermLocation],
	 [CLLinkedVolume],
	 [CLBoxNumber],
	 [CLInpatient],
	 [CLSDS],
	 [CLOutpatient],
	 [CLAmcare],
	 [CLMicroFilm],
	 [CLMircoFilmNum],
	 [CLOption1],
	 [CLOption2],
	 [CLOption3],
	 [CLOption4],
	 [CLComments],
	 [CLCurrentLocation],
	 [SubVolume],
     [CLPreviousLocation],
     [UniversalID],
     [DigitalIndicator],
     [DestructionDate]) 
VALUES 
	(@VolumeID,
	 @PatientID,
	 @HospitalID,
	 @LabelPrinted,
	 @VolumeNumber,
     @VolumeType,
	 @BarCodeVolume,
	 @DateFrom,
	 @DateTo,
	 @PermLoc,
	 @LinkVolume,
	 @VolumeBox,
	 @HasInpatient,
	 @HasSDS,
	 @HasOutpatient,
	 @HasAmcare,
	 @HasMicroFilm,
	 @MircoFilmNum,
	 @HasOption1,
	 @HasOption2,
	 @HasOption3,
	 @HasOption4,
	 @HasComments,
	 @Location,
	 @SubVolume,
     @CLPreviousLocation,
     @UniversalID,
     @DigitalIndicator,
     @DestructionDate)
	
	RETURN @VolumeID




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_CM_FamilyHistory]
	(@PatientID 	[int],
	 @Occurrence 	[int],
	 @Diagnosis 	[varchar](50),
	 @StartDate 	[datetime],
	 @AgeAtOnset 	[int],
	 @Treatment 	[varchar](50),
	 @Relationship 	[int],
	 @Notes	[varchar](255))

AS 
INSERT INTO [dbo].[CM_FamilyHistory] 
	 ([PatientID],
	 [Occurrence],
	 [Diagnosis],
	 [StartDate],
	 [AgeAtOnset],
	 [Treatment],
	 [Relationship],
	 [Notes]) 
VALUES 
	(@PatientID,
	 @Occurrence,
	 @Diagnosis,
	 @StartDate,
	 @AgeAtOnset,
	 @Treatment,
	 @Relationship,
	 @Notes)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_CM_Files]
	(@PatientID 		[int],
	 @Occurrence 		[int],
	 @FileType 		[int],
	 @FileCode 		[int],
	 @FileDateReceived 	[datetime],
	 @FileNotes	 	[varchar](255))

AS 
INSERT INTO [dbo].[CM_Files] 
	 ([PatientID],
	 [Occurrence],
	 [FileType],
	 [FileCode],
	 [FileDateReceived],
	 [FileNotes]) 
VALUES 
	(@PatientID,
	 @Occurrence,
	 @FileType,
	 @FileCode,
	 @FileDateReceived,
	 @FileNotes)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE  PROCEDURE [I_CM_History] 
	@PatientID as int,
	@Coder as int,
	@UpdateType as varchar(10) = 'Saved'
AS 

declare @HID as int --NP-00025
select @HID = HospitalID from U_Users where Code = @Coder

insert into CM_UpdateHistory (PatientID, HospitalID, Coder, Updated, UpdateType) VALUES (@PatientID, @HID, @Coder, GetDate(), @UpdateType)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_CM_LabHistory]
	(@PatientID	 	[int],
	 @Occurrence	 	[int],
	 @LabTest	 	[int],
	 @TestDate		[datetime],
	 @TestTime		[datetime],
	 @TestResult		[varchar](50),
	 @MeasureUnit	 	[int],
	 @ReferenceRange 	[int],
	 @AbnormalInd		[int],
	 @Notes		[varchar](255))

AS 
INSERT INTO [dbo].[CM_LabHistory] 
	 ([PatientID],
	 [Occurrence],
	 [LabTest],
	 [TestDate],
	 [TestTime],
	 [TestResult],
	 [MeasureUnit],
	 [ReferenceRange],
	 [AbnormalInd],
	 [Notes]) 
VALUES 
	(@PatientID,
	 @Occurrence,
	 @LabTest,
	 @TestDate,
	 @TestTime,
	 @TestResult,
	 @MeasureUnit,
	 @ReferenceRange,
	 @AbnormalInd,
	 @Notes)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_CM_RiskFactors]
	(@PatientID 	[int],
	 @Occurrence	[int],
	 @RiskFactor	[int],
	 @Exposure	[int],
	 @StartDate	[datetime],
	 @AgeAtOnset	[int],
	 @EndDate	[datetime],
	 @Notes	[varchar](255))

AS 
INSERT INTO [dbo].[CM_RiskFactors] 
	 ([PatientID],
	 [Occurrence],
	 [RiskFactor],
	 [Exposure],
	 [StartDate],
	 [AgeAtOnset],
	 [EndDate],
	 [Notes]) 
VALUES 
	(@PatientID,
	 @Occurrence,
	 @RiskFactor,
	 @Exposure,
	 @StartDate,
	 @AgeAtOnset,
	 @EndDate,
	 @Notes)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CM_UDFieldsDate]
	(@PatientID 	[int],
	 @UDDate6 	[datetime],
	 @UDDate7 	[datetime],
	 @UDDate8 	[datetime],
	 @UDDate9 	[datetime],
	 @UDDate10 	[datetime],
	 @UDDate11 	[datetime],
	 @UDDate12 	[datetime],
	 @UDDate13 	[datetime],
	 @UDDate14 	[datetime],
	 @UDDate15 	[datetime],
	 @UDDate16 	[datetime],
	 @UDDate17 	[datetime],
	 @UDDate18 	[datetime],
	 @UDDate19 	[datetime],
	 @UDDate20 	[datetime],
	 @UDDate21 	[datetime],
	 @UDDate22 	[datetime],
	 @UDDate23 	[datetime],
	 @UDDate24 	[datetime],
	 @UDDate25 	[datetime])
as 
insert into [dbo].[CM_UDFieldsDate] 
	 ([PatientID],
	 [UDDate6],
	 [UDDate7],
	 [UDDate8],
	 [UDDate9],
	 [UDDate10],
	 [UDDate11],
	 [UDDate12],
	 [UDDate13],
	 [UDDate14],
	 [UDDate15],
	 [UDDate16],
	 [UDDate17],
	 [UDDate18],
	 [UDDate19],
	 [UDDate20],
	 [UDDate21],
	 [UDDate22],
	 [UDDate23],
	 [UDDate24],
	 [UDDate25]) 
values
	(@PatientID,
	 @UDDate6,
	 @UDDate7,
	 @UDDate8,
	 @UDDate9,
	 @UDDate10,
	 @UDDate11,
	 @UDDate12,
	 @UDDate13,
	 @UDDate14,
	 @UDDate15,
	 @UDDate16,
	 @UDDate17,
	 @UDDate18,
	 @UDDate19,
	 @UDDate20,
	 @UDDate21,
	 @UDDate22,
	 @UDDate23,
	 @UDDate24,
	 @UDDate25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_CM_UDFieldsInteger]
	(@PatientID 	[int],
	 @UDInteger6 	[varchar](50),
	 @UDInteger7 	[varchar](50),
	 @UDInteger8 	[varchar](50),
	 @UDInteger9 	[varchar](50),
	 @UDInteger10 	[varchar](50),
	 @UDInteger11 	[varchar](50),
	 @UDInteger12 	[varchar](50),
	 @UDInteger13 	[varchar](50),
	 @UDInteger14 	[varchar](50),
	 @UDInteger15 	[varchar](50),
	 @UDInteger16 	[varchar](50),
	 @UDInteger17 	[varchar](50),
	 @UDInteger18 	[varchar](50),
	 @UDInteger19 	[varchar](50),
	 @UDInteger20 	[varchar](50),
	 @UDInteger21 	[varchar](50),
	 @UDInteger22 	[varchar](50),
	 @UDInteger23 	[varchar](50),
	 @UDInteger24 	[varchar](50),
	 @UDInteger25 	[varchar](50))
as 
insert into [dbo].[CM_UDFieldsInteger] 
	 ([PatientID],
	 [UDInteger6],
	 [UDInteger7],
	 [UDInteger8],
	 [UDInteger9],
	 [UDInteger10],
	 [UDInteger11],
	 [UDInteger12],
	 [UDInteger13],
	 [UDInteger14],
	 [UDInteger15],
	 [UDInteger16],
	 [UDInteger17],
	 [UDInteger18],
	 [UDInteger19],
	 [UDInteger20],
	 [UDInteger21],
	 [UDInteger22],
	 [UDInteger23],
	 [UDInteger24],
	 [UDInteger25]) 
values
	(@PatientID,
	 @UDInteger6,
	 @UDInteger7,
	 @UDInteger8,
	 @UDInteger9,
	 @UDInteger10,
	 @UDInteger11,
	 @UDInteger12,
	 @UDInteger13,
	 @UDInteger14,
	 @UDInteger15,
	 @UDInteger16,
	 @UDInteger17,
	 @UDInteger18,
	 @UDInteger19,
	 @UDInteger20,
	 @UDInteger21,
	 @UDInteger22,
	 @UDInteger23,
	 @UDInteger24,
	 @UDInteger25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CM_UDFieldsLookUp]
	(@PatientID 	[int],
	 @UDLookUp6 	[int],
	 @UDLookUp7 	[int],
	 @UDLookUp8 	[int],
	 @UDLookUp9 	[int],
	 @UDLookUp10 	[int],
	 @UDLookUp11 	[int],
	 @UDLookUp12 	[int],
	 @UDLookUp13 	[int],
	 @UDLookUp14 	[int],
	 @UDLookUp15 	[int],
	 @UDLookUp16 	[int],
	 @UDLookUp17 	[int],
	 @UDLookUp18 	[int],
	 @UDLookUp19 	[int],
	 @UDLookUp20 	[int],
	 @UDLookUp21 	[int],
	 @UDLookUp22 	[int],
	 @UDLookUp23 	[int],
	 @UDLookUp24 	[int],
	 @UDLookUp25 	[int])
as 
insert into [dbo].[CM_UDFieldsLookUp] 
	 ([PatientID],
	 [UDLookUp6],
	 [UDLookUp7],
	 [UDLookUp8],
	 [UDLookUp9],
	 [UDLookUp10],
	 [UDLookUp11],
	 [UDLookUp12],
	 [UDLookUp13],
	 [UDLookUp14],
	 [UDLookUp15],
	 [UDLookUp16],
	 [UDLookUp17],
	 [UDLookUp18],
	 [UDLookUp19],
	 [UDLookUp20],
	 [UDLookUp21],
	 [UDLookUp22],
	 [UDLookUp23],
	 [UDLookUp24],
	 [UDLookUp25]) 
values
	(@PatientID,
	 @UDLookUp6,
	 @UDLookUp7,
	 @UDLookUp8,
	 @UDLookUp9,
	 @UDLookUp10,
	 @UDLookUp11,
	 @UDLookUp12,
	 @UDLookUp13,
	 @UDLookUp14,
	 @UDLookUp15,
	 @UDLookUp16,
	 @UDLookUp17,
	 @UDLookUp18,
	 @UDLookUp19,
	 @UDLookUp20,
	 @UDLookUp21,
	 @UDLookUp22,
	 @UDLookUp23,
	 @UDLookUp24,
	 @UDLookUp25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CM_UDFieldsSmallText]
	(@PatientID 	[int],
	 @UDSmallText6 	[varchar](50),
	 @UDSmallText7 	[varchar](50),
	 @UDSmallText8 	[varchar](50),
	 @UDSmallText9 	[varchar](50),
	 @UDSmallText10 	[varchar](50),
	 @UDSmallText11 	[varchar](50),
	 @UDSmallText12 	[varchar](50),
	 @UDSmallText13 	[varchar](50),
	 @UDSmallText14 	[varchar](50),
	 @UDSmallText15 	[varchar](50),
	 @UDSmallText16 	[varchar](50),
	 @UDSmallText17 	[varchar](50),
	 @UDSmallText18 	[varchar](50),
	 @UDSmallText19 	[varchar](50),
	 @UDSmallText20 	[varchar](50),
	 @UDSmallText21 	[varchar](50),
	 @UDSmallText22 	[varchar](50),
	 @UDSmallText23 	[varchar](50),
	 @UDSmallText24 	[varchar](50),
	 @UDSmallText25 	[varchar](50))
as 
insert into [dbo].[CM_UDFieldsSmallText] 
	 ([PatientID],
	 [UDSmallText6],
	 [UDSmallText7],
	 [UDSmallText8],
	 [UDSmallText9],
	 [UDSmallText10],
	 [UDSmallText11],
	 [UDSmallText12],
	 [UDSmallText13],
	 [UDSmallText14],
	 [UDSmallText15],
	 [UDSmallText16],
	 [UDSmallText17],
	 [UDSmallText18],
	 [UDSmallText19],
	 [UDSmallText20],
	 [UDSmallText21],
	 [UDSmallText22],
	 [UDSmallText23],
	 [UDSmallText24],
	 [UDSmallText25]) 
values
	(@PatientID,
	 @UDSmallText6,
	 @UDSmallText7,
	 @UDSmallText8,
	 @UDSmallText9,
	 @UDSmallText10,
	 @UDSmallText11,
	 @UDSmallText12,
	 @UDSmallText13,
	 @UDSmallText14,
	 @UDSmallText15,
	 @UDSmallText16,
	 @UDSmallText17,
	 @UDSmallText18,
	 @UDSmallText19,
	 @UDSmallText20,
	 @UDSmallText21,
	 @UDSmallText22,
	 @UDSmallText23,
	 @UDSmallText24,
	 @UDSmallText25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CM_UDFieldsText]
	(@PatientID 	[int],
	 @UDText6 	[varchar](255),
	 @UDText7 	[varchar](255),
	 @UDText8 	[varchar](255),
	 @UDText9 	[varchar](255),
	 @UDText10 	[varchar](255),
	 @UDText11 	[varchar](255),
	 @UDText12 	[varchar](255),
	 @UDText13 	[varchar](255),
	 @UDText14 	[varchar](255),
	 @UDText15 	[varchar](255),
	 @UDText16 	[varchar](255),
	 @UDText17 	[varchar](255),
	 @UDText18 	[varchar](255),
	 @UDText19 	[varchar](255),
	 @UDText20 	[varchar](255),
	 @UDText21 	[varchar](255),
	 @UDText22 	[varchar](255),
	 @UDText23 	[varchar](255),
	 @UDText24 	[varchar](255),
	 @UDText25 	[varchar](255))
as 
insert into [dbo].[CM_UDFieldsText] 
	 ([PatientID],
	 [UDText6],
	 [UDText7],
	 [UDText8],
	 [UDText9],
	 [UDText10],
	 [UDText11],
	 [UDText12],
	 [UDText13],
	 [UDText14],
	 [UDText15],
	 [UDText16],
	 [UDText17],
	 [UDText18],
	 [UDText19],
	 [UDText20],
	 [UDText21],
	 [UDText22],
	 [UDText23],
	 [UDText24],
	 [UDText25]) 
values
	(@PatientID,
	 @UDText6,
	 @UDText7,
	 @UDText8,
	 @UDText9,
	 @UDText10,
	 @UDText11,
	 @UDText12,
	 @UDText13,
	 @UDText14,
	 @UDText15,
	 @UDText16,
	 @UDText17,
	 @UDText18,
	 @UDText19,
	 @UDText20,
	 @UDText21,
	 @UDText22,
	 @UDText23,
	 @UDText24,
	 @UDText25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CM_UDFieldsTime]
	(@PatientID 	[int],
	 @UDTime6 	[datetime],
	 @UDTime7 	[datetime],
	 @UDTime8 	[datetime],
	 @UDTime9 	[datetime],
	 @UDTime10 	[datetime],
	 @UDTime11 	[datetime],
	 @UDTime12 	[datetime],
	 @UDTime13 	[datetime],
	 @UDTime14 	[datetime],
	 @UDTime15 	[datetime],
	 @UDTime16 	[datetime],
	 @UDTime17 	[datetime],
	 @UDTime18 	[datetime],
	 @UDTime19 	[datetime],
	 @UDTime20 	[datetime],
	 @UDTime21 	[datetime],
	 @UDTime22 	[datetime],
	 @UDTime23 	[datetime],
	 @UDTime24 	[datetime],
	 @UDTime25 	[datetime])
as 
insert into [dbo].[CM_UDFieldsTime] 
	 ([PatientID],
	 [UDTime6],
	 [UDTime7],
	 [UDTime8],
	 [UDTime9],
	 [UDTime10],
	 [UDTime11],
	 [UDTime12],
	 [UDTime13],
	 [UDTime14],
	 [UDTime15],
	 [UDTime16],
	 [UDTime17],
	 [UDTime18],
	 [UDTime19],
	 [UDTime20],
	 [UDTime21],
	 [UDTime22],
	 [UDTime23],
	 [UDTime24],
	 [UDTime25]) 
values
	(@PatientID,
	 @UDTime6,
	 @UDTime7,
	 @UDTime8,
	 @UDTime9,
	 @UDTime10,
	 @UDTime11,
	 @UDTime12,
	 @UDTime13,
	 @UDTime14,
	 @UDTime15,
	 @UDTime16,
	 @UDTime17,
	 @UDTime18,
	 @UDTime19,
	 @UDTime20,
	 @UDTime21,
	 @UDTime22,
	 @UDTime23,
	 @UDTime24,
	 @UDTime25)
	 
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE  PROCEDURE [I_CM_UserDefined]
	(@PatientID 	[int],
	 @UDDate1 	[datetime],
	 @UDDate2 	[datetime],
	 @UDDate3 	[datetime],
	 @UDDate4 	[datetime],
	 @UDTime1 	[datetime],
	 @UDTime2 	[datetime],
	 @UDTime3 	[datetime],
	 @UDTime4 	[datetime],
	 @UDLookup1 	[int],
	 @UDLookup2 	[int],
	 @UDLookup3 	[int],
	 @UDLookup4 	[int],
	 @UDInteger1 	[int],
	 @UDInteger2 	[int],
	 @UDInteger3 	[int],
	 @UDInteger4 	[int],
	 @UDText1 	[varchar](255),
	 @UDText2 	[varchar](255),
	 @UDText3 	[varchar](255),
	 @UDText4 	[varchar](255),
	 @UDSmallText1 	[varchar](50),
	 @UDSmallText2 	[varchar](50),
	 @UDSmallText3 	[varchar](50),
	 @UDSmallText4 	[varchar](50),
	 @UDDate5 	[datetime], 
	 @UDTime5 	[datetime], 
	 @UDLookup5 	[int], 
	 @UDInteger5 	[varchar](50), 
	 @UDText5 	[varchar](255), 
 	 @UDSmallText5 	[varchar](50))

AS INSERT INTO [dbo].[CM_UserDefined] 
	 ([PatientID],
	 [UDDate1],
	 [UDDate2],
	 [UDDate3],
	 [UDDate4],
	 [UDTime1],
	 [UDTime2],
	 [UDTime3],
	 [UDTime4],
	 [UDLookup1],
	 [UDLookup2],
	 [UDLookup3],
	 [UDLookup4],
	 [UDInteger1],
	 [UDInteger2],
	 [UDInteger3],
	 [UDInteger4],
	 [UDText1],
	 [UDText2],
	 [UDText3],
	 [UDText4],
	 [UDSmallText1],
	 [UDSmallText2],
	 [UDSmallText3],
	 [UDSmallText4],
	 [UDDate5], 
	 [UDTime5], 
	 [UDLookup5], 
	 [UDInteger5], 
	 [UDText5], 
 	 [UDSmallText5]) 
 
VALUES 
	( @PatientID,
	 @UDDate1,
	 @UDDate2,
	 @UDDate3,
	 @UDDate4,
	 @UDTime1,
	 @UDTime2,
	 @UDTime3,
	 @UDTime4,
	 @UDLookup1,
	 @UDLookup2,
	 @UDLookup3,
	 @UDLookup4,
	 @UDInteger1,
	 @UDInteger2,
	 @UDInteger3,
	 @UDInteger4,
	 @UDText1,
	 @UDText2,
	 @UDText3,
	 @UDText4,
	 @UDSmallText1,
	 @UDSmallText2,
	 @UDSmallText3,
	 @UDSmallText4,
	 @UDDate5, 
	 @UDTime5, 
	 @UDLookup5, 
	 @UDInteger5, 
	 @UDText5, 
 	 @UDSmallText5)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE  PROCEDURE [I_CM_Volume_History] 
	@VolumeID as int,
	@Coder as int,
	@UpdateType as varchar(10) = 'Saved'
AS 

declare @HID as int --NP-00025
select @HID = HospitalID from U_Users where Code = @Coder
insert into CM_Volume_UpdateHistory (VolumeID, HospitalID, Coder, Updated, UpdateType) values (@VolumeID, @HID, @Coder, GetDate(), @UpdateType)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE PROCEDURE [I_CMV_ClinicalPathway]
	(@HospitalID		[int],
	 @RecordID 		[int],
	 @ClinicPatientID	[int],
	 @ClinicPatLName 	[varchar](50),
	 @ClinicPatFName 	[varchar](50),
	 @ClinicPatDOB 	[datetime],
	 @ClinicAbstractID 	[int],
	 @ClinicInstNumber 	[int],
	 @ClinicAdmitDate	 [datetime] ,
	 @ClinicDischDate	 [datetime],
	 @ClinicAssessDate	 [datetime],
	 @ClinicPath 	[int],
	 @ClinicLOS 	[int],
	 @ActualLOS 	[int],
	 @StartDate 	[datetime],
	 @EndDate 	[datetime],
	 @IntervDate 	[datetime])

AS 

select @RecordID = (select isnull(max(RecordID), 0) from CMV_ClinicalPathway) + 1

INSERT INTO [CMV_ClinicalPathway] 
	 ( [RecordID],
	 [ClinicPatientID],
	 [ClinicPatLName],
	 [ClinicPatFName],
	 [ClinicPatDOB],
	 [ClinicAbstractID],
	 [ClinicInstNumber],
	 [ClinicAdmitDate] ,
	 [ClinicDischDate],
	 [ClinicAssessDate],
	 [ClinicPath],
	 [ClinicLOS],
	 [ActualLOS],
	 [StartDate],
	 [EndDate],
	 [IntervDate]) 
 
VALUES 
	( @RecordID,
	 @ClinicPatientID,
	 @ClinicPatLName,
	 @ClinicPatFName,
	 @ClinicPatDOB,
	 @ClinicAbstractID,
	 @ClinicInstNumber,
	 @ClinicAdmitDate ,
	 @ClinicDischDate,
	 @ClinicAssessDate,
	 @ClinicPath,
	 @ClinicLOS,
	 @ActualLOS,
	 @StartDate,
	 @EndDate,
	 @IntervDate)

--Return the New ID
return @RecordID

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE  PROCEDURE [I_CMV_UpdateHistory]
	(@RecordID 	[int],
	 @Coder 	[int],
     	 @UpdateType varchar(10) = 'Saved')
AS 

declare @HID as int --NP-00025
select @HID = HospitalID from U_Users where Code = @Coder

insert into [CMV_UpdateHistory] ([RecordID], [HospitalID], [Coder], [Updated], UpdateType) 
values (@RecordID, @HID, @Coder,  GetDate(),  @UpdateType)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE PROCEDURE [I_CMV_Variance]
	(@RecordID	[int],
	 @Occurrence 	[int],
	 @VariantDay 	[int],
	 @VariantCode 	[int],
	 @Outcome 	[int],
	 @CoderID	[int],
	 @Commment 	[varchar](255))

AS 
INSERT INTO [CMV_Variance] 
	 ( [RecordID],
	 [Occurrence],
	 [VariantDay],
	 [VariantCode],
	 [Outcome],
	 [CoderID],
	 [Commment]) 
 
VALUES 
	( @RecordID,
	 @Occurrence,
	 @VariantDay,
	 @VariantCode,
	 @Outcome,
	 @CoderID,
	 @Commment)

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE  PROCEDURE [I_CR_BatchEncounter]
   @Provider as int,
   @Date as DateTime
AS
   Declare @AbstractID as [int]
   Declare @ChartNumber as [varchar](10)--
   Declare @HealthCareNumber as [varchar](12)--
   Declare @HCNVersion as [varchar](2)--
   Declare @MaidenName as [varchar](35)--
   Declare @LastName as [varchar](40)--
   Declare @MiddleName as [varchar](15)--
   Declare @FirstName as [varchar](35)--
   Declare @Gender as [int]--
   Declare @BirthDate as [datetime]--
   Declare @IsCorrected as [int]
   Declare @IsSubmitted as [int]
   Declare @IsValidated as [int]
   Declare @IsCompleted as [int]
   Declare @IsDeleted as [int]
   Declare @EncounterNumber as [varchar](12)
   Declare @EncounterSequence as [varchar](3)
   Declare @AdmitDate as [datetime]--
   Declare @AdmitTime as [datetime]--
   Declare @ArrivalTime as [datetime]
   Declare @TimePatientSeen as [datetime]
   Declare @DischargeTime as [datetime]
   Declare @VisitLocation as [int]--
   Declare @VisitType as [int]--
   Declare @VisitTypeMethod as [int]
   Declare @VisitTypeMode as [int]
   Declare @IntervDescProvider as [varchar](255)
   Declare @IntervDescPatient as [varchar](255)

   Set @IsCorrected = 1
   Set @IsSubmitted = 2
   Set @IsValidated = 1
   Set @IsCompleted = 1
   Set @IsDeleted = 2
   Set @ArrivalTime = NULL
   Set @TimePatientSeen = NULL
   Set @DischargeTime = NULL
   Set @VisitTypeMethod = 0
   Set @VisitTypeMode = 0
   Set @IntervDescProvider = ''
   Set @IntervDescPatient = ''
   Set @EncounterSequence = 1

   Declare cur_BatchEncounter cursor for
   SELECT dbo.SH_Appointments.AppointmentDate, dbo.SH_Appointments.AppointmentTime, dbo.CM_CPI.ChartNumber, 
   dbo.CM_CPI.HealthCareNumber, dbo.CM_CPI.HCNVersion, dbo.CM_CPI.MaidenName, dbo.CM_CPI.LastName, dbo.CM_CPI.MiddleName, 
   dbo.CM_CPI.FirstName, dbo.CM_CPI.Gender, dbo.CM_CPI.BirthDate, dbo.SH_Appointments.VisitType, dbo.SH_Appointments.Location
   FROM dbo.SH_Appointments LEFT OUTER JOIN dbo.CM_CPI ON dbo.SH_Appointments.Patientid = dbo.CM_CPI.PatientID
   Where dbo.SH_Appointments.ProviderNumber = @Provider and dbo.SH_Appointments.AppointmentDate = @Date and isnull(dbo.SH_Appointments.Status, 0) = 0
   Open cur_BatchEncounter
   fetch next from cur_BatchEncounter
   into @AdmitDate, @AdmitTime, @ChartNumber, 
   @HealthCareNumber, @HCNVersion, @MaidenName, @LastName, @MiddleName, 
   @FirstName, @Gender, @BirthDate, @VisitType, @VisitLocation
   while @@fetch_status = 0
   begin
           Exec P_UpdateClinicEncNum @EncounterNumber output
           EXEC @AbstractID = I_CR_Demographic 0,  @ChartNumber, @HealthCareNumber, @HCNVersion, 
           @MaidenName, @LastName, @MiddleName, @FirstName, @Gender, @BirthDate, 1, 1, 1, 1, 2
           EXEC I_CR_Visit @AbstractID, @Provider, @EncounterNumber, 1, @AdmitDate, @AdmitTime, NULL, NULL, NULL, @VisitLocation, @VisitType, 0, 0, NULL, NULL
           fetch next from cur_BatchEncounter
           into @AdmitDate, @AdmitTime, @ChartNumber, 
           @HealthCareNumber, @HCNVersion, @MaidenName, @LastName, @MiddleName, 
           @FirstName, @Gender, @BirthDate, @VisitType, @VisitLocation
   end
   Close cur_BatchEncounter
   Deallocate cur_BatchEncounter

   Update SH_Appointments set status = 11735
   Where ProviderNumber = @Provider and AppointmentDate = @Date and isnull(Status, 0) = 0




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE  PROCEDURE [I_CR_Demographic]
   (@AbstractID            [int],
    @AmCareID              [int],
    @ChartNumber           [varchar](10),
    @HealthCareNumber      [varchar](12),
    @HCNVersion            [varchar](2),
    @MaidenName    [varchar](35),
    @LastName              [varchar](40),
    @MiddleName            [varchar](15),
    @FirstName             [varchar](35),
    @Gender                [int],
    @BirthDate             [datetime],
    @IsCompleted           [int],
    @IsValidated           [int],
    @IsSubmitted           [int],
    @IsCorrected           [int],
    @IsDeleted             [int],
    @BillDate              [datetime],
    @BillNumber            [varchar](8),
    @HCNProvince   [int])
AS

SET @LastName = REPLACE(@LastName, '''''', '''')
SELECT @AbstractID = (SELECT ISNULL(MAX(AbstractID), 0) FROM CR_Demographic) + 1

If isnull(@IsDeleted, 0) = 0   set @IsDeleted = 2   -- PR - 03723
If isnull(@IsCorrected, 0) = 0 set @IsCorrected = 1 -- PR - 03723
If isnull(@IsSubmitted, 0) = 0  set @IsSubmitted = 2  -- PR - 03723

INSERT INTO [dbo].[CR_Demographic] 
    ([AbstractID],
    [AmCareID],
    [IsCorrected],
    [IsSubmited],
    [IsValidated],
    [IsCompleted],
    [IsDeleted],
    [BillDate],
    [BillNumber],
    [ChartNumber],
    [HealthCareNumber],
    [HCNVersion],
    [HCNProvince],
    [MaidenName],
    [LastName],
    [MiddleName],
    [FirstName],
    [Gender],
    [BirthDate]) 
 
VALUES 
   (@AbstractID,
    @AmCareID,
    1,
    2,
    @IsValidated,
    @IsCompleted,
    2,
    @BillDate,
    @BillNumber,
    @ChartNumber,
    @HealthCareNumber,
    @HCNVersion,
    @HCNProvince,
    @MaidenName,
    @LastName,
    @MiddleName,
    @FirstName,
    @Gender,
    @BirthDate)

RETURN @AbstractID




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_CR_Diagnosis]
	(@AbstractID	 	[int],
	 @DiagnosisOccurrence 	[int],
	 @DiagnosisCode	[int],
	 @ServiceCode		[int],
	 @ServiceQty		[int],
	 @ServiceFee		[money],
	 @ServiceTotal		[money],
	 @ServiceSuffix		[varchar](50))
AS 
INSERT INTO [dbo].[CR_Diagnosis] 
	 ([AbstractID],
	 [DiagnosisOccurrence],
	 [DiagnosisCode],
	 [ServiceCode],
	 [ServiceQty],
	 [ServiceFee],
	 [ServiceTotal],
	 [ServiceSuffix]) 
 
VALUES 
	(@AbstractID,
	 @DiagnosisOccurrence,
	 @DiagnosisCode,
	 @ServiceCode,
	 @ServiceQty,
	 @ServiceFee,
	 @ServiceTotal,
	 @ServiceSuffix)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_CR_DirectBilling]
	(@AbstractID [int], 
	 @InvoiceNumber [varchar](30), 
	 @InvoiceDate [datetime], 
	 @SocialInsurNumber [varchar](9), 
	 @WSIB [varchar](50), 
	 @InsurPolicy1 [varchar](15),
	 @GroupNum1 [varchar](50), 
	 @InvoiceTotal [money], 
	 @AmountPaid [money], 
	 @AmountOwed [money], 
	 @DueDate [datetime]) 

AS 
INSERT INTO [dbo].[CR_DirectBilling] 
	(AbstractID, 
	 InvoiceNumber, 
	 InvoiceDate, 
	 SocialInsurNumber, 
	 WSIB, 
	 InsurPolicy1, 
	 GroupNum1, 
	 InvoiceTotal, 
	 AmountPaid, 
	 AmountOwed, 
	 DueDate)
VALUES 
	(@AbstractID, 
	 @InvoiceNumber, 
	 @InvoiceDate, 
	 @SocialInsurNumber, 
	 @WSIB, 
	 @InsurPolicy1, 
	 @GroupNum1, 
	 @InvoiceTotal, 
	 @AmountPaid, 
	 @AmountOwed, 
	 @DueDate)






GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_CR_DirectBillingItems]
	(@AbstractID	 	[int],
	 @Occurrence		[int],
	 @Quantity 		[int], 
	 @ItemCode 		[int], 
	 @Price 		[money], 
	 @TaxCode 		[int], 
	 @Amount 		[money])
AS 
INSERT INTO [dbo].[CR_DirectBillingItems] 
	 ([AbstractID],
	 [OccurrenceNumber],
	 [Quantity], 
	 [ItemCode], 
	 [Price], 
	 [TaxCode], 
	 [Amount])
VALUES 
	(@AbstractID,
	 @Occurrence,
	 @Quantity, 
	 @ItemCode, 
	 @Price, 
	 @TaxCode, 
	 @Amount)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_CR_DirectBillingPayments]
	(@AbstractID	 	[int],
	 @Occurrence		[int],
	 @PaymentDate 	[datetime], 
	 @PaymentMethod 	[int], 
	 @PaymentAmount 	[money])
AS 
INSERT INTO [dbo].[CR_DirectBillingPayments] 
	 ([AbstractID],
	 [OccurrenceNumber],
	 [PaymentDate], 
	 [PaymentMethod], 
	 [PaymentAmount])
VALUES 
	(@AbstractID,
	 @Occurrence,
	 @PaymentDate, 
	 @PaymentMethod, 
	 @PaymentAmount)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_CR_ErrorClaimHD]
	(@HErrorID	 	[int],
	 @AbstractID	 	[int],
	 @HealthCareNumber 	[varchar](12),
	 @HCNVersion	 	[varchar](2),
	 @BirthDate	 	[datetime],
	 @AccountNumber	[varchar](8),
	 @PaymentProgram 	[varchar](3),
	 @Payee	 	[varchar](1),
	 @ReferenceProvider 	[varchar](6),
	 @InstitutionNumber 	[varchar](4),
	 @InpatAdmitDate 	[datetime],
	 @RefLabNumber 	[varchar](4),
	 @LocationCode 	[varchar](4),
	 @Error1	 	[varchar](3),
	 @Error2	 	[varchar](3),
	 @Error3	 	[varchar](3),
	 @Error4	 	[varchar](3),
	 @Error5	 	[varchar](3))
AS 
DECLARE @CErrorID AS INT
SELECT @CErrorID = (SELECT ISNULL(MAX(CErrorID), 0) FROM [dbo].[CR_ErrorClaimHD]) + 1
INSERT INTO [dbo].[CR_ErrorClaimHD] 
	 ([HErrorID],
	 [CErrorID],
	 [AbstractID],
	 [HealthCareNumber],
	 [HCNVersion],
	 [BirthDate],
	 [AccountNumber],
	 [PaymentProgram],
	 [Payee],
	 [ReferenceProvider],
	 [InstitutionNumber],
	 [InpatAdmitDate],
	 [RefLabNumber],
	 [LocationCode],
	 [Error1],
	 [Error2],
	 [Error3],
	 [Error4],
	 [Error5]) 
VALUES 
	(@HErrorID,
	 @CErrorID,
	 @AbstractID,
	 @HealthCareNumber,
	 @HCNVersion,
	 @BirthDate,
	 @AccountNumber,
	 @PaymentProgram,
	 @Payee,
	 @ReferenceProvider,
	 @InstitutionNumber,
	 @InpatAdmitDate,
	 @RefLabNumber,
	 @LocationCode,
	 @Error1,
	 @Error2,
	 @Error3,
	 @Error4,
	 @Error5)

--Need to re-set the Submited flag of the visit so it can be re-sent with corrections.
UPDATE CR_Demographic SET IsSubmited = 2 WHERE AbstractID = @AbstractID

RETURN @CErrorID



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_CR_ErrorItem]
	(@HErrorID	 	[int],
	 @CErrorID		[int],
	 @ServiceCode	 	[varchar](5),
	 @ServiceFee 		[varchar](6),
	 @ServiceQty	 	[varchar](2),
	 @ServiceDate	 	[datetime],
	 @DiagnosisCode 	[varchar](4),
	 @ExplainCode	 	[varchar](2),
	 @I_Error1		[varchar](3),
	 @I_Error2		[varchar](3),
	 @I_Error3	 	[varchar](3),
	 @I_Error4	 	[varchar](3),
	 @I_Error5		[varchar](3),
	 @HX8Code1	 	[varchar](2),
	 @HX8Desc1	 	[varchar](55),
	 @HX8Code2	 	[varchar](2),
	 @HX8Desc2	 	[varchar](55),
	 @HX8Code3	 	[varchar](2),
	 @HX8Desc3	 	[varchar](55),
	 @HX8Code4	 	[varchar](2),
	 @HX8Desc4	 	[varchar](55))

AS 
DECLARE @IErrorID AS INT
SELECT @IErrorID = (SELECT ISNULL(MAX(IErrorID), 0) FROM [dbo].[CR_ErrorItem]) + 1
INSERT INTO [dbo].[CR_ErrorItem] 
	 ([IErrorID],
	 [HErrorID],
	 [CErrorID],
	 [ServiceCode],
	 [ServiceFee],
	 [ServiceQty],
	 [ServiceDate],
	 [DiagnosisCode],
	 [ExplainCode],
	 [I_Error1],
	 [I_Error2],
	 [I_Error3],
	 [I_Error4],
	 [I_Error5],
	 [HX8Code1],
	 [HX8Desc1],
	 [HX8Code2],
	 [HX8Desc2],
	 [HX8Code3],
	 [HX8Desc3],
	 [HX8Code4],
	 [HX8Desc4]) 
VALUES 
	(@IErrorID,
	 @HErrorID,
	 @CErrorID,
	 @ServiceCode,
	 @ServiceFee,
	 @ServiceQty,
	 @ServiceDate,
	 @DiagnosisCode,
	 @ExplainCode,
	 @I_Error1,
	 @I_Error2,
	 @I_Error3,
	 @I_Error4,
	 @I_Error5,
	 @HX8Code1,
	 @HX8Desc1,
	 @HX8Code2,
	 @HX8Desc2,
	 @HX8Code3,
	 @HX8Desc3,
	 @HX8Code4,
	 @HX8Desc4)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_CR_ErrorsHeader]
	(@HErrorID		[int],
	 @MOHOfficeCode 	[varchar](1),
	 @Operator	 	[varchar](6),
	 @GroupNumber 	[varchar](4),
	 @ProviderNumber 	[varchar](6),
	 @ProviderSpecialty 	[varchar](2),
	 @ProcessDate	 	[datetime],
	 @StationNumber 	[varchar](3),
	 @FileName		[varchar](50),
	 @HDR1Cnt		[int],
	 @HDR2Cnt		[int],
	 @ItemCnt		[int],
	 @MsgCnt		[int])

AS 
--The Insert will do only half the fields (it's fed by the Header part of the file).The Update will do the other half (fed by the Footer)
SELECT @HErrorID = (SELECT ISNULL(MAX(HErrorID), 0) FROM [dbo].[CR_ErrorsHeader]) + 1
INSERT INTO [dbo].[CR_ErrorsHeader] 
	 ([HErrorID],
	 [MOHOfficeCode],
	 [Operator],
	 [GroupNumber],
	 [ProviderNumber],
	 [ProviderSpecialty],
	 [ProcessDate],
	 [StationNumber])  
VALUES 
	(@HErrorID,
	 @MOHOfficeCode,
	 @Operator,
	 @GroupNumber,
	 @ProviderNumber,
	 @ProviderSpecialty,
	 @ProcessDate,
	 @StationNumber)

RETURN @HErrorID



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_CR_Immunization]
	(@AbstractID	 	[int],
	 @Occurrence		[int],
	 @ImmuneType	 	[int],
	 @ImmuneDate	 	[datetime],
	 @ImmuneRefused 	[int],
	 @RefusedDate	 	[datetime],
	 @Notes		[varchar](255))

AS 
INSERT INTO [dbo].[CR_Immunization] 
	 ([AbstractID],
	 [Occurrence],
	 [ImmuneType],
	 [ImmuneDate],
	 [ImmuneRefused],
	 [RefusedDate],
	 [Notes]) 
VALUES 
	(@AbstractID,
	 @Occurrence,
	 @ImmuneType,
	 @ImmuneDate,
	 @ImmuneRefused,
	 @RefusedDate,
	 @Notes)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_CR_Intervention]
	(@AbstractID	 	[int],
	 @IntervOccurrence 	[int],
	 @IntervCode		[int])

AS 
INSERT INTO [dbo].[CR_Intervention] 
	 ([AbstractID],
	 [IntervOccurrence],
	 [IntervCode]) 
 
VALUES 
	(@AbstractID,
	 @IntervOccurrence,
	 @IntervCode)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_CR_OBEC]
	(@OBECID	 	[int],
	 @HealthCareNumber	[varchar](10),
	 @HCNVersion		[varchar](2),
	 @ResponseCode 	[varchar](2),
	 @SubmissionID 	[varchar](4),
	 @Gender		[varchar](1),
	 @BirthDate		[datetime],
	 @ExpiryDate		[datetime],
	 @LastName		[varchar](30),
	 @FirstName	 	[varchar](20),
	 @MiddleName	 	[varchar](20))
AS
SELECT @OBECID = (SELECT ISNULL(MAX(OBECID), 0) FROM [dbo].[CR_OBEC]) + 1
INSERT INTO [dbo].[CR_OBEC] 
	 ([OBECID],
	 [HealthCareNumber],
	 [HCNVersion],
	 [ResponseCode],
	 [SubmissionID],
	 [Gender],
	 [BirthDate],
	 [ExpiryDate],
	 [LastName],
	 [FirstName],
	 [MiddleName]) 
 
VALUES 
	(@OBECID,
	 @HealthCareNumber,
	 @HCNVersion,
	 @ResponseCode,
	 @SubmissionID,
	 @Gender,
	 @BirthDate,
	 @ExpiryDate,
	 @LastName,
	 @FirstName,
	 @MiddleName)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_CR_Prescription]
	(@AbstractID 			[int],
	 @PrescriptionOccurrence 	[int],
	 @Medication			[int],
	 @Instructions		 	[int],
	 @Repeat		 	[int],
	 @AdversReaction		[varchar](255),
	 @Comments			[varchar](255),
	 @Pharmacy		 	[int],
	 @CancellationReason	 	[varchar](255),
	 @PrescriptionDate 		[datetime], 
	 @StartDate 			[datetime], 
	 @EndDate 			[datetime], 
	 @Dosage 			[int], 
	 @Frequency 			[int], 
	 @Quantity 			[int], 
	 @Route 			[int], 
	 @Duration 			[int], 
	 @LongTermMed 		[int], 
	 @PatientCompliance 		[int])

AS 
INSERT INTO [dbo].[CR_Prescription] 
	 ([AbstractID],
	 [PrescriptionOccurrence],
	 [Medication],
	 [Instructions],
	 [Repeat],
	 [AdversReaction],
	 [Comments],
	 [Pharmacy],
	 [CancellationReason],
	 [PrescriptionDate], 
 	 [StartDate], 
	 [EndDate], 
	 [Dosage], 
	 [Frequency], 
	 [Quantity],
	 [Route], 
	 [Duration], 
	 [LongTermMed], 
	 [PatientCompliance]) 
VALUES 
	(@AbstractID,
	 @PrescriptionOccurrence,
	 @Medication,
	 @Instructions,
	 @Repeat,
	 @AdversReaction,
	 @Comments,
	 @Pharmacy,
	 @CancellationReason,
	 @PrescriptionDate, 
	 @StartDate, 
	 @EndDate, 
	 @Dosage, 
	 @Frequency, 
	 @Quantity, 
	 @Route, 
	 @Duration, 
	 @LongTermMed, 
	 @PatientCompliance)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_CR_ProviderService]
	(@AbstractID	 	[int],
	 @ProviderOccurrence	[int],
	 @ProviderService	[int])

AS 
INSERT INTO [dbo].[CR_ProviderService] 
	 ([AbstractID],
	 [ProviderOccurrence],
	 [ProviderService]) 
VALUES 
	(@AbstractID,
	 @ProviderOccurrence,
	 @ProviderService)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_CR_ReconClaimHD]
	(@HReconID		[int],
	 @AbstractID		[int],
	 @ClaimNumber	 	[varchar](11),
	 @TransType		[varchar](1),
	 @ProviderNumber 	[varchar](12),
	 @ProviderSpecialty 	[varchar](2),
	 @AccountNumber 	[varchar](8),
	 @LastName		[varchar](14),
	 @FirstName	 	[varchar](5),
	 @HCNProvince 	[varchar](2),
	 @HealthCareNumber	[varchar](12),
	 @HCNVersion		[varchar](2),
	 @PaymentProgram 	[varchar](3),
	 @LocationCode 	[varchar](4))
AS 
DECLARE @CReconID AS INT
SELECT @CReconID = (SELECT ISNULL(MAX(CReconID), 0) FROM [dbo].[CR_ReconClaimHD]) + 1
INSERT INTO [dbo].[CR_ReconClaimHD] 
	 ([CReconID],
	 [HReconID],
	 [AbstractID],
	 [ClaimNumber],
	 [TransType],
	 [ProviderNumber],
	 [ProviderSpecialty],
	 [AccountNumber],
	 [LastName],
	 [FirstName],
	 [HCNProvince],
	 [HealthCareNumber],
	 [HCNVersion],
	 [PaymentProgram],
	 [LocationCode]) 
VALUES 
	(@CReconID,
	 @HReconID,
	 @AbstractID,	 
	 @ClaimNumber,
	 @TransType,
	 @ProviderNumber,
	 @ProviderSpecialty,
	 @AccountNumber,
	 @LastName,
	 @FirstName,
	 @HCNProvince,
	 @HealthCareNumber,
	 @HCNVersion,
	 @PaymentProgram,
	 @LocationCode)

--Need to re-set the Submited flag of the visit so it can be re-sent with corrections.
UPDATE CR_Demographic SET IsSubmited = 2 WHERE AbstractID = @AbstractID

RETURN @CReconID



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_CR_ReconHeader]
	(@HReconID	 	[int],
	 @MOHOfficeCode 	[varchar](1),
	 @GroupNumber 	[varchar](4),
	 @ProviderNumber 	[varchar](12),
	 @ProviderSpecialty 	[varchar](2),
	 @PaymentDate 	[datetime],
	 @PayeeName 		[varchar](30),
	 @TotalPayable	 	[money],
	 @ChequeNumber 	[varchar](9),
	 @BillingAgent	 	[varchar](30),
	 @Address1	 	[varchar](30),
	 @Address2	 	[varchar](30),
	 @Address3	 	[varchar](30),
	 @AmtAdjustment 	[money],
	 @AmtAdvances 	[money],
	 @AmtReductions 	[money],
	 @AmtOther		[money],
	 @TransCode	 	[varchar](2),
	 @ChequeIndicator 	[varchar](1),
	 @TransDate	 	[datetime],
	 @TransAmount 	[money],
	 @TransMessage 	[varchar](50),
	 @MinistryMessage 	[text])
AS 
--The Insert will do only half the fields (it's fed by the Header part of the file).The Update will do the other half (fed by the Balance, Account & Message parts)
SELECT @HReconID = (SELECT ISNULL(MAX(HReconID), 0) FROM [dbo].[CR_ReconHeader]) + 1
INSERT INTO [dbo].[CR_ReconHeader] 
	 ([HReconID],
	 [MOHOfficeCode],
	 [GroupNumber],
	 [ProviderNumber],
	 [ProviderSpecialty],
	 [PaymentDate],
	 [PayeeName],
	 [TotalPayable],
	 [ChequeNumber],
	 [BillingAgent],
	 [Address1],
	 [Address2],
	 [Address3]) 
VALUES 
	(@HReconID,
	 @MOHOfficeCode,
	 @GroupNumber,
	 @ProviderNumber,
	 @ProviderSpecialty,
	 @PaymentDate,
	 @PayeeName,
	 @TotalPayable,
	 @ChequeNumber,
	 @BillingAgent,
	 @Address1,
	 @Address2,
	 @Address3)

RETURN @HReconID



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_CR_ReconItem]
	(@HReconID	 	[int],
	 @CReconID	 	[int],
	 @ClaimNumber	 	[varchar](11),
	 @TransType		[varchar](1),
	 @ServiceDate	 	[datetime],
	 @ServiceQty	 	[varchar](2),
	 @ServiceCode	 	[varchar](5),
	 @ServiceFee	 	[money],
	 @AmountPaid	 	[money],
	 @ExplainCode	 	[varchar](2))
AS 
DECLARE @IReconID AS INT
SELECT @IReconID = (SELECT ISNULL(MAX(IReconID), 0) FROM [dbo].[CR_ReconItem]) + 1
INSERT INTO [dbo].[CR_ReconItem] 
	 ([IReconID],
	 [HReconID],
	 [CReconID],
	 [ClaimNumber],
	 [TransType],
	 [ServiceDate],
	 [ServiceQty],
	 [ServiceCode],
	 [ServiceFee],
	 [AmountPaid],
	 [ExplainCode])  
VALUES 
	(@IReconID,
	 @HReconID,
	 @CReconID,
	 @ClaimNumber,
	 @TransType,
	 @ServiceDate,
	 @ServiceQty,
	 @ServiceCode,
	 @ServiceFee,
	 @AmountPaid,
	 @ExplainCode)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_CR_Supply]
	(@AbstractID	 	[int],
	 @SuppliesOccurrence	[int],
	 @SuppliesUsed		[int],
	 @Quantity		[int])

AS 
INSERT INTO [dbo].[CR_Supply] 
	 ([AbstractID],
	 [SuppliesOccurrence],
	 [SuppliesUsed],
	 [Quantity]) 
 
VALUES 
	(@AbstractID,
	 @SuppliesOccurrence,
	 @SuppliesUsed,
	 @Quantity)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_CR_UpdateHistory] 
	@AbstractID as int,
	@Coder as int
AS 

INSERT INTO CR_UpdateHistory (AbstractID, Coder, Updated) Values (@AbstractID, @Coder, GetDate())



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_CR_Visit]
	(@AbstractID 		[int],
	 @IsMultiContact	[int],
	 @ProviderNumber 	[int],
	 @EncounterNumber 	[varchar](12),
	 @EncounterSequence 	[varchar](3),
	 @AdmitDate	 	[datetime],
	 @AdmitTime	 	[datetime],
	 @ArrivalTime	 	[datetime],
	 @TimePatientSeen 	[datetime],
	 @DischargeTime 	[datetime],
	 @VisitLocation	 	[int],
	 @VisitType	 	[int],
	 @VisitTypeMethod 	[int],
	 @VisitTypeMode 	[int],
	 @IntervDescProvider 	[varchar](255),
	 @IntervDescPatient 	[varchar](255),
	 @RefLabNumber	[varchar](50),
	 @ReferenceProvider 	[varchar](6), 
	 @PaymentProgram 	[int],
	 @Payee 		[int],
	 @ManualReviewInd 	[int], 
	 @InpatAdmitDate 	[datetime],
	 @ProviderSpecialty	[int],
	 @InstitutionNumber 	[int], 
	 @MOH_Code 		[varchar](1), 
	 @LocationCode 	[varchar](4),
	 @MRINotes 		[varchar](255),
	 @IntervDateOfOnset 	[datetime])
AS 

-- If it's a Multi Contact then Increment the Encounter Sequence.
IF @IsMultiContact = 1 
SELECT @EncounterSequence = (SELECT ISNULL(MAX(	[EncounterSequence]), 1)  FROM [dbo].[CR_Visit] WHERE [EncounterNumber] = @EncounterNumber) + 1

INSERT INTO [dbo].[CR_Visit] 
	 ([AbstractID],
	 [MOHOfficeCode],
	 [InstitutionNumber],
	 [LocationCode],
	 [ProviderNumber],
	 [ProviderSpecialty],
	 [EncounterNumber],
	 [EncounterSequence],
	 [AdmitDate],
	 [AdmitTime],
	 [ArrivalTime],
	 [TimePatientSeen],
	 [DischargeTime],
	 [VisitLocation],
	 [VisitType],
	 [VisitTypeMethod],
	 [VisitTypeMode],
	 [RefLabNumber],
	 [IntervDateOfOnset],
	 [IntervDescProvider],
	 [IntervDescPatient],
	 [ReferenceProvider], 
	 [PaymentProgram],	
	 [Payee],
	 [ManualReviewInd], 
	 [MRINotes],
	 [InpatAdmitDate])  
VALUES 
	(@AbstractID,
	 @MOH_Code,
	 @InstitutionNumber,
	 @LocationCode,
	 @ProviderNumber,
	 @ProviderSpecialty,
	 @EncounterNumber,
	 @EncounterSequence,
	 @AdmitDate,
	 @AdmitTime,
	 @ArrivalTime,
	 @TimePatientSeen,
	 @DischargeTime,
	 @VisitLocation,
	 @VisitType,
	 @VisitTypeMethod,
	 @VisitTypeMode,
	 @RefLabNumber,
	 @IntervDateOfOnset,
	 @IntervDescProvider,
	 @IntervDescPatient,
	 @ReferenceProvider, 
	 @PaymentProgram,	
	 @Payee,
	 @ManualReviewInd, 
	 @MRINotes,
	 @InpatAdmitDate)

--Clear some of the fields for New Contacts. The User must Enter a Unique one.
IF @IsMultiContact = 1 
	UPDATE [dbo].[CR_Visit] SET ProviderNumber = 0, ProviderSpecialty = 0, IntervDescProvider = NULL, IntervDescPatient = NULL WHERE AbstractID = @AbstractID



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_CR_VitalSign]
	(@AbstractID	 		[int],
	 @BloodPressureSystolic 	[int],
	 @BloodPressureDiastolic	[int],
	 @Pulse		 	[int],
	 @Temperature			[decimal],
	 @Weight		 	[decimal],
	 @TimeVitalsTaken	 	[datetime],
	 @VitalsTakenBy	 	[int])

AS 
INSERT INTO [dbo].[CR_VitalSign] 
	 ([AbstractID],
	 [BloodPressureSystolic],
	 [BloodPressureDiastolic],
	 [Pulse],
	 [Temperature],
	 [Weight],
	 [TimeVitalsTaken],
	 [VitalsTakenBy]) 
VALUES 
	(@AbstractID,
	 @BloodPressureSystolic,
	 @BloodPressureDiastolic,
	 @Pulse,
	 @Temperature,
	 @Weight,
	 @TimeVitalsTaken,
	 @VitalsTakenBy)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_CRS_Admission]
	(@AbstractID 	[int],
	 @AB3 		[int],
	 @AB4 		[varchar](7),
	 @AB5All 	[int],
	 @AB5a	[int],
	 @AB5b	[int],
	 @AB5c 	[int],
	 @AB5d 	[int],
	 @AB5e 	[int],
	 @AB7	 	[int],
	 @AB8	 	[int],
	 @AB9	 	[int],
	 @AB10a 	[int],
	 @AB10b 	[int],
	 @AB10c 	[int],
	 @AB10d 	[int],
	 @AB10e 	[int],
	 @AB10f 	[int],
	 @AC1a 	[int],
	 @AC1b 	[int],
	 @AC1c 	[int],
	 @AC1d 	[int],
	 @AC1e 	[int],
	 @AC1f 	[int],
	 @AC1g 	[int],
	 @AC1I 	[int],
	 @AC1j	 	[int],
	 @AC1k 	[int],
	 @AC1m 	[int],
	 @AC1n 	[int],
	 @AC1o 	[int],
	 @AC1p 	[int],
	 @AC1q 	[int],
	 @AC1s 	[int],
	 @AC1t 	[int],
	 @AC1u 	[int],
	 @AC1v 	[int],
	 @AC1w 	[int],
     @ResidenceCode [int]
	 --@AA7   [int]
	 )

AS INSERT INTO [dbo].[CRS_Admission] 
	 ([AbstractID],
	 [AB3],
	 [AB4],
	 [AB5All],
	 [AB5a],
	 [AB5b],
	 [AB5c],
	 [AB5d],
	 [AB5e],
	 [AB7],
	 [AB8],
	 [AB9],
	 [AB10a],
	 [AB10b],
	 [AB10c],
	 [AB10d],
	 [AB10e],
	 [AB10f],
	 [AC1a],
	 [AC1b],
	 [AC1c],
	 [AC1d],
	 [AC1e],
	 [AC1f],
	 [AC1g],
	 [AC1I],
	 [AC1j],
	 [AC1k],
	 [AC1m],
	 [AC1n],
	 [AC1o],
	 [AC1p],
	 [AC1q],
	 [AC1s],
	 [AC1t],
	 [AC1u],
	 [AC1v],
	 [AC1w],
     [ResidenceCode]
	 --[AA7]
	 ) 
 
VALUES 
	(@AbstractID,
	 @AB3,
	 @AB4,
	 @AB5All,
	 @AB5a,
	 @AB5b,
	 @AB5c,
	 @AB5d,
	 @AB5e,
	 @AB7,
	 @AB8,
	 @AB9,
	 @AB10a,
	 @AB10b,
	 @AB10c,
	 @AB10d,
	 @AB10e,
	 @AB10f,
	 @AC1a,
	 @AC1b,
	 @AC1c,
	 @AC1d,
	 @AC1e,
	 @AC1f,
	 @AC1g,
	 @AC1I,
	 @AC1j,
	 @AC1k,
	 @AC1m,
	 @AC1n,
	 @AC1o,
	 @AC1p,
	 @AC1q,
	 @AC1s,
	 @AC1t,
	 @AC1u,
	 @AC1v,
	 @AC1w,
     @ResidenceCode
	 --@AA7
	 )



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_CRS_Ancillary]
	(@AbstractID	 	[int],
	 @AncillaryField1 	[int],
	 @AncillaryField2 	[int],
	 @AncillaryField3 	[int],
	 @AncillaryField4 	[int],
	 @AncillaryField5 	[int],
	 @AncillaryField6 	[int],
	 @AncillaryField7 	[int],
	 @AncillaryField8 	[int],
	 @AncillaryField9 	[int],
	 @AncillaryField10 	[int],
	 @AncillaryField11 	[int],
	 @AncillaryField12 	[int],
	 @AncillaryField13 	[int],
	 @AncillaryField14 	[int],
	 @AncillaryField15 	[int],
	 @AncillaryField16 	[int],
	 @AncillaryField17 	[int])
AS 

INSERT INTO [CRS_Ancillary] 
	 ( [AbstractID],
	 [AncillaryField1],
	 [AncillaryField2],
	 [AncillaryField3],
	 [AncillaryField4],
	 [AncillaryField5],
	 [AncillaryField6],
	 [AncillaryField7],
	 [AncillaryField8],
	 [AncillaryField9],
	 [AncillaryField10],
	 [AncillaryField11],
	 [AncillaryField12],
	 [AncillaryField13],
	 [AncillaryField14],
	 [AncillaryField15],
	 [AncillaryField16],
	 [AncillaryField17]) 
 
VALUES 
	(@AbstractID,
	 @AncillaryField1,
	 @AncillaryField2,
	 @AncillaryField3,
	 @AncillaryField4,
	 @AncillaryField5,
	 @AncillaryField6,
	 @AncillaryField7,
	 @AncillaryField8,
	 @AncillaryField9,
	 @AncillaryField10,
	 @AncillaryField11,
	 @AncillaryField12,
	 @AncillaryField13,
	 @AncillaryField14,
	 @AncillaryField15,
	 @AncillaryField16,
	 @AncillaryField17)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_CRS_AssessFull1]
	(@AbstractID 	[int],
	 @A7a 		[int],
	 @A7b 		[int], 
	 @A7c 		[int],
	 @A7d 		[int], 
	 @A7e 		[int], 
	 @A7f 		[int], 
	 @A7g 		[int], 
	 @A7h 		[int], 
	 @A7I 		[int], 
	 @A7j 		[int], 
	 @A7k 		[int],
	 @C1 		[int],
	 @C2All 	[int],
	 @C2a	 	[int],
	 @C2b	 	[int],
	 @C2c	 	[int],
	 @C3All 	[int],
	 @C3a	 	[int],
	 @C3b	 	[int],
	 @C3c	 	[int],
	 @C3d	 	[int],
	 @C3e	 	[int],
	 @C3f	 	[int],
	 @C5	 	[int],
	 @D1	 	[int],
	 @D2a	 	[int],
	 @D2b	 	[int],
	 @D3	 	[int],
	 @F2All	 	[int],
	 @F2a	 	[int],
	 @F2b	 	[int],
	 @F2c	 	[int],
	 @F2d	 	[int],
	 @F2e	 	[int],
	 @F2f	 	[int],
	 @F2g	 	[int],
	 @F3a	 	[int],
	 @F3b	 	[int],
	 @F3c	 	[int],
	 @G5All 	[int],
	 @G5a	 	[int],
	 @G5b	 	[int],
	 @G5c	 	[int],
	 @G5d	 	[int],
	 @G8All 	[int],
	 @G8a	 	[int],
	 @G8b	 	[int],
	 @G8c	 	[int],
	 @G8d	 	[int],
	 @J3a	 	[int],
	 @J3b	 	[int],
	 @J3c	 	[int],
	 @J3d	 	[int],
	 @J3e	 	[int],
	 @J3f	 	[int],
	 @J3g	 	[int],
	 @J3h	 	[int],
	 @J3I	 	[int],
	 @J3j	 	[int])

AS INSERT INTO [dbo].[CRS_AssessFull1] 
	 ([AbstractID],
	 [A7a],
	 [A7b],
	 [A7c],
	 [A7d],
	 [A7e],
	 [A7f],
	 [A7g],
	 [A7h],
	 [A7I],
	 [A7j],
	 [A7k],
	 [C1],
	 [C2All],
	 [C2a],
	 [C2b],
	 [C2c],
	 [C3All],
	 [C3a],
	 [C3b],
	 [C3c],
	 [C3d],
	 [C3e],
	 [C3f],
	 [C5],
	 [D1],
	 [D2a],
	 [D2b],
	 [D3],
	 [F2All],
	 [F2a],
	 [F2b],
	 [F2c],
	 [F2d],
	 [F2e],
	 [F2f],
	 [F2g],
	 [F3a],
	 [F3b],
	 [F3c],
	 [G5All],
	 [G5a],
	 [G5b],
	 [G5c],
	 [G5d],
	 [G8All],
	 [G8a],
	 [G8b],
	 [G8c],
	 [G8d],
	 [J3a],
	 [J3b],
	 [J3c],
	 [J3d],
	 [J3e],
	 [J3f],
	 [J3g],
	 [J3h],
	 [J3I],
	 [J3j]) 
 
VALUES 
	(@AbstractID,
	 @A7a,
	 @A7b,
	 @A7c,
	 @A7d,
	 @A7e,
	 @A7f ,
	 @A7g,
	 @A7h,
	 @A7I,
	 @A7j,
	 @A7k,
	 @C1,
	 @C2All,
	 @C2a,
	 @C2b,
	 @C2c,
	 @C3All,
	 @C3a,
	 @C3b,
	 @C3c,
	 @C3d,
	 @C3e,
	 @C3f,
	 @C5,
	 @D1,
	 @D2a,
	 @D2b,
	 @D3,
	 @F2All,
	 @F2a,
	 @F2b,
	 @F2c,
	 @F2d,
	 @F2e,
	 @F2f,
	 @F2g,
	 @F3a,
	 @F3b,
	 @F3c,
	 @G5All,
	 @G5a,
	 @G5b,
	 @G5c,
	 @G5d,
	 @G8All,
	 @G8a,
	 @G8b,
	 @G8c,
	 @G8d,
	 @J3a,
	 @J3b,
	 @J3c,
	 @J3d,
	 @J3e,
	 @J3f,
	 @J3g,
	 @J3h,
	 @J3I,
	 @J3j)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_CRS_AssessFull2]
	(@AbstractID 	[int],
	 @L1All 	[int],
	 @L1a	 	[int],
	 @L1b	 	[int],
	 @L1c	 	[int],
	 @L1d	 	[int],
	 @L1e	 	[int],
	 @L1f	 	[int],
	 @M3	 	[int],
	 @N3All 	[int],
	 @N3a	 	[int],
	 @N3b	 	[int],
	 @N3c	 	[int],
	 @N3d	 	[int],
	 @N4All 	[int],
	 @N4a	 	[int],
	 @N4b	 	[int],
	 @N4c	 	[int],
	 @N4d	 	[int],
	 @N4e	 	[int],
	 @N4f	 	[int],
	 @N4g	 	[int],
	 @N4h	 	[int],
	 @N4I	 	[int],
	 @N4j	 	[int],
	 @N4k	 	[int],
	 @N4l	 	[int],
	 @N5a	 	[int],
	 @N5b	 	[int],
	 @O2	 	[int],
	 @P2All 	[int],
	 @P2a	 	[int],
	 @P2b	 	[int],
	 @P2c	 	[int],
	 @P2d	 	[int],
	 @P2e	 	[int],
	 @P5	 	[varchar](2),
	 @P6	 	[varchar](2),
	 @P9	 	[int],
	 @Q1a	 	[int],
	 @Q1b	 	[int],
	 @Q1c	 	[int],
	 @R1a	 	[int],
	 @R1b	 	[int],
	 @R1c		[int])

AS INSERT INTO [dbo].[CRS_AssessFull2] 
	 ([AbstractID],
	 [L1All],
	 [L1a],
	 [L1b],
	 [L1c],
	 [L1d],
	 [L1e],
	 [L1f],
	 [M3],
	 [N3All],
	 [N3a],
	 [N3b],
	 [N3c],
	 [N3d],
	 [N4All],
	 [N4a],
	 [N4b],
	 [N4c],
	 [N4d],
	 [N4e],
	 [N4f],
	 [N4g],
	 [N4h],
	 [N4I],
	 [N4j],
	 [N4k],
	 [N4l],
	 [N5a],
	 [N5b],
	 [O2],
	 [P2All],
	 [P2a],
	 [P2b],
	 [P2c],
	 [P2d],
	 [P2e],
	 [P5],
	 [P6],
	 [P9],
	 [Q1a],
	 [Q1b],
	 [Q1c],
	 [R1a],
	 [R1b],
	 [R1c]) 
 
VALUES 
	(@AbstractID,
	 @L1All,
	 @L1a,
	 @L1b,
	 @L1c,
	 @L1d,
	 @L1e,
	 @L1f,
	 @M3,
	 @N3All,
	 @N3a,
	 @N3b,
	 @N3c,
	 @N3d,
	 @N4All,
	 @N4a,
	 @N4b,
	 @N4c,
	 @N4d,
	 @N4e,
	 @N4f,
	 @N4g,
	 @N4h,
	 @N4I,
	 @N4j,
	 @N4k,
	 @N4l,
	 @N5a,
	 @N5b,
	 @O2,
	 @P2All,
	 @P2a,
	 @P2b,
	 @P2c,
	 @P2d,
	 @P2e,
	 @P5,
	 @P6,
	 @P9,
	 @Q1a,
	 @Q1b,
	 @Q1c,
	 @R1a,
	 @R1b,
	 @R1c)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [I_CRS_AssessShare1]
	(@AbstractID 	[int],
	 @A9All 	[int],
	 @A9a	 	[int],
	 @A9b	 	[int],
	 @A9c	 	[int],
	 @A9d	 	[int],
	 @A9e	 	[int],
	 @A9f	 	[int],
	 @A10All 	[int],
	 @A10a 	[int],
	 @A10b 	[int],
	 @A10c 	[int],
	 @A10d 	[int],
	 @A10e 	[int],
	 @A10f 		[int],
	 @A10g 	[int],
	 @A10h 	[int],
	 @B1	 	[int],
	 @B2a	 	[int],
	 @B2b	 	[int],
	 @B3All 	[int],
	 @B3a	 	[int],
	 @B3b	 	[int],
	 @B3c	 	[int],
	 @B3d	 	[int],
	 @B4	 	[int],
	 @B5a	 	[int],
	 @B5b	 	[int],
	 @B5c	 	[int],
	 @B5d	 	[int],
	 @B5e	 	[int],
	 @B5f	 	[int],
	 @B6	 	[int],
	 @C4	 	[int],
	 @C6	 	[int],
	 @C7	 	[int],
	 @E1a	 	[int],
	 @E1b	 	[int],
	 @E1c	 	[int],
	 @E1d	 	[int],
	 @E1e	 	[int],
	 @E1f	 	[int],
	 @E1g	 	[int],
	 @E1h	 	[int],
	 @E1I	 	[int],
	 @E1j	 	[int],
	 @E1k	 	[int],
	 @E1l	 	[int],
	 @E1m	 	[int],
	 @E1n	 	[int],
	 @E1o	 	[int],
	 @E1p	 	[int],
	 @E2	 	[int],
	 @E3	 	[int],
	 @E4aA 	[int],
	 @E4aB 	[int],
	 @E4bA 	[int],
	 @E4bB 	[int],
	 @E4cA 	[int],
	 @E4cB 	[int],
	 @E4dA 	[int],
	 @E4dB 	[int],
	 @E4eA 	[int],
	 @E4eB 	[int],
	 @E5	 	[int],
	 @A11a	 	[int],
	 @A11b	 	[int],
	 @A12a	 	[int],
	 @A12b	 	[int]
	 )

AS INSERT INTO [dbo].[CRS_AssessShare1] 
	 ([AbstractID],
	 [A9All],
	 [A9a],
	 [A9b],
	 [A9c],
	 [A9d],
	 [A9e],
	 [A9f],
	 [A10All],
	 [A10a],
	 [A10b],
	 [A10c],
	 [A10d],
	 [A10e],
	 [A10f],
	 [A10g],
	 [A10h],
	 [B1],
	 [B2a],
	 [B2b],
	 [B3All],
	 [B3a],
	 [B3b],
	 [B3c],
	 [B3d],
	 [B4],
	 [B5a],
	 [B5b],
	 [B5c],
	 [B5d],
	 [B5e],
	 [B5f],
	 [B6],
	 [C4],
	 [C6],
	 [C7],
	 [E1a],
	 [E1b],
	 [E1c],
	 [E1d],
	 [E1e],
	 [E1f],
	 [E1g],
	 [E1h],
	 [E1I],
	 [E1j],
	 [E1k],
	 [E1l],
	 [E1m],
	 [E1n],
	 [E1o],
	 [E1p],
	 [E2],
	 [E3],
	 [E4aA],
	 [E4aB],
	 [E4bA],
	 [E4bB],
	 [E4cA],
	 [E4cB],
	 [E4dA],
	 [E4dB],
	 [E4eA],
	 [E4eB],
	 [E5],
	 [A11a],
	 [A11b],
	 [A12a],
	 [A12b]) 
 
VALUES 
	(@AbstractID,
	 @A9All,
	 @A9a,
	 @A9b,
	 @A9c,
	 @A9d,
	 @A9e,
	 @A9f,
	 @A10All,
	 @A10a,
	 @A10b,
	 @A10c,
	 @A10d,
	 @A10e,
	 @A10f,
	 @A10g,
	 @A10h,
	 @B1,
	 @B2a,
	 @B2b,
	 @B3All,
	 @B3a,
	 @B3b,
	 @B3c,
	 @B3d,
	 @B4,
	 @B5a,
	 @B5b,
	 @B5c,
	 @B5d,
	 @B5e,
	 @B5f,
	 @B6,
	 @C4,
	 @C6,
	 @C7,
	 @E1a,
	 @E1b,
	 @E1c,
	 @E1d,
	 @E1e,
	 @E1f,
	 @E1g,
	 @E1h,
	 @E1I,
	 @E1j,
	 @E1k,
	 @E1l,
	 @E1m,
	 @E1n,
	 @E1o,
	 @E1p,
	 @E2,
	 @E3,
	 @E4aA,
	 @E4aB,
	 @E4bA,
	 @E4bB,
	 @E4cA,
	 @E4cB,
	 @E4dA,
	 @E4dB,
	 @E4eA,
	 @E4eB,
	 @E5,
	 @A11a,
	 @A11b,
	 @A12a,
	 @A12b
	 )



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_CRS_AssessShare2]
	(@AbstractID 	[int],
	 @F1All 	[int],
	 @F1a	 	[int],
	 @F1b	 	[int],
	 @F1c	 	[int],
	 @F1d	 	[int],
	 @F1e	 	[int],
	 @F1f		[int],
	 @G1aA 	[int],
	 @G1aB 	[int],
	 @G1bA 	[int],
	 @G1bB 	[int],
	 @G1cA 	[int],
	 @G1cB 	[int],
	 @G1dA 	[int],
	 @G1dB 	[int],
	 @G1eA 	[int],
	 @G1eB 	[int],
	 @G1fA 	[int],
	 @G1fB 	[int],
	 @G1gA 	[int],
	 @G1gB 	[int],
	 @G1hA 	[int],
	 @G1hB 	[int],
	 @G1iA 	[int],
	 @G1iB 	[int],
	 @G1jA 	[int],
	 @G1jB 	[int],
	 @G2A	 	[int],
	 @G2B	 	[int],
	 @G3a	 	[int],
	 @G3b	 	[int],
	 @G4aA 	[int],
	 @G4aB 	[int],
	 @G4bA 	[int],
	 @G4bB 	[int],
	 @G4cA 	[int],
	 @G4cB 	[int],
	 @G4dA 	[int],
	 @G4dB 	[int],
	 @G4eA 	[int],
	 @G4eB 	[int],
	 @G4fA 	[int],
	 @G4fB 	[int],
	 @G6All 	[int],
	 @G6a	 	[int],
	 @G6b	 	[int],
	 @G6c	 	[int],
	 @G6d	 	[int],
	 @G6e	 	[int],
	 @G7	 	[int],
	 @G9	 	[int],
	 @H1a	 	[int],
	 @H1b	 	[int],
	 @H2All 	[int],
	 @H2a	 	[int],
	 @H2b	 	[int],
	 @H2c	 	[int],
	 @H2d	 	[int],
	 @H3All 	[int],
	 @H3a	 	[int],
	 @H3b	 	[int],
	 @H3c	 	[int],
	 @H3d	 	[int],
	 @H3e	 	[int],
	 @H3f		[int],
	 @H3g	 	[int],
	 @H3h	 	[int],
	 @H3I	 	[int],
	 @H4	 	[int])

AS INSERT INTO [dbo].[CRS_AssessShare2] 
	 ([AbstractID],
	 [F1All],
	 [F1a],
	 [F1b],
	 [F1c],
	 [F1d],
	 [F1e],
	 [F1f],
	 [G1aA],
	 [G1aB],
	 [G1bA],
	 [G1bB],
	 [G1cA],
	 [G1cB],
	 [G1dA],
	 [G1dB],
	 [G1eA],
	 [G1eB],
	 [G1fA],
	 [G1fB],
	 [G1gA],
	 [G1gB],
	 [G1hA],
	 [G1hB],
	 [G1iA],
	 [G1iB],
	 [G1jA],
	 [G1jB],
	 [G2A],
	 [G2B],
	 [G3a],
	 [G3b],
	 [G4aA],
	 [G4aB],
	 [G4bA],
	 [G4bB],
	 [G4cA],
	 [G4cB],
	 [G4dA],
	 [G4dB],
	 [G4eA],
	 [G4eB],
	 [G4fA],
	 [G4fB],
	 [G6All],
	 [G6a],
	 [G6b],
	 [G6c],
	 [G6d],
	 [G6e],
	 [G7],
	 [G9],
	 [H1a],
	 [H1b],
	 [H2All],
	 [H2a],
	 [H2b],
	 [H2c],
	 [H2d],
	 [H3All],
	 [H3a],
	 [H3b],
	 [H3c],
	 [H3d],
	 [H3e],
	 [H3f],
	 [H3g],
	 [H3h],
	 [H3I],
	 [H4]) 
 
VALUES 
	(@AbstractID,
	 @F1All,
	 @F1a,
	 @F1b,
	 @F1c,
	 @F1d,
	 @F1e,
	 @F1f,
	 @G1aA,
	 @G1aB,
	 @G1bA,
	 @G1bB,
	 @G1cA,
	 @G1cB,
	 @G1dA,
	 @G1dB,
	 @G1eA,
	 @G1eB,
	 @G1fA,
	 @G1fB,
	 @G1gA,
	 @G1gB,
	 @G1hA,
	 @G1hB,
	 @G1iA,
	 @G1iB,
	 @G1jA,
	 @G1jB,
	 @G2A,
	 @G2B,
	 @G3a,
	 @G3b,
	 @G4aA,
	 @G4aB,
	 @G4bA,
	 @G4bB,
	 @G4cA,
	 @G4cB,
	 @G4dA,
	 @G4dB,
	 @G4eA,
	 @G4eB,
	 @G4fA,
	 @G4fB,
	 @G6All,
	 @G6a,
	 @G6b,
	 @G6c,
	 @G6d,
	 @G6e,
	 @G7,
	 @G9,
	 @H1a,
	 @H1b,
	 @H2All,
	 @H2a,
	 @H2b,
	 @H2c,
	 @H2d,
	 @H3All,
	 @H3a,
	 @H3b,
	 @H3c,
	 @H3d,
	 @H3e,
	 @H3f,
	 @H3g,
	 @H3h,
	 @H3I,
	 @H4)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [I_CRS_AssessShare3]
	(@AbstractID 	[int],
	 @I1All	 	[int],
	 @I1a	 	[int],
	 @I1b	 	[int],
	 @I1c	 	[int],
	 @I1d	 	[int],
	 @I1e	 	[int],
	 @I1f		[int],
	 @I1g	 	[int],
	 @I1h	 	[int],
	 @I1i	 	[int],
	 @I1j	 	[int],
	 @I1k	 	[int],
	 @I1l	 	[int],
	 @I1m	 	[int],
	 @I1n	 	[int],
	 @I1o	 	[int],
	 @I1p	 	[int],
	 @I1q	 	[int],
	 @I1r	 	[int],
	 @I1s	 	[int],
	 @I1t	 	[int],
	 @I1u	 	[int],
	 @I1v	 	[int],
	 @I1w	 	[int],
	 @I1x	 	[int],
	 @I1y	 	[int],
	 @I1z	 	[int],
	 @I1aa	 	[int],
	 @I1bb	 	[int],
	 @I1cc	 	[int],
	 @I1dd	 	[int],
	 @I1ee	 	[int],
	 @I1ff	 	[int],
	 @I1gg	 	[int],
	 @I1hh	 	[int],
	 @I1ii	 	[int],
	 @I1jj	 	[int],
	 @I1kk	 	[int],
	 @I1ll	 	[int],
	 @I1mm 	[int],
	 @I1nn	 	[int],
	 @I1oo	 	[int],
	 @I1pp	 	[int],
	 @I1qq	 	[int],
	 @I1rr	 	[int],
	 @I1ss	 	[int],
	 @I1tt	 	[int],
	 @I1uu	 	[int],
	 @I2All	 	[int],
	 @I2a	 	[int],
	 @I2b	 	[int],
	 @I2c	 	[int],
	 @I2d	 	[int],
	 @I2e	 	[int],
	 @I2f	 	[int],
	 @I2g	 	[int],
	 @I2h	 	[int],
	 @I2I	 	[int],
	 @I2j		[int],
	 @I2k	 	[int],
	 @I2l	 	[int],
	 @I2m	 	[int],
	 @J1All	 	[int],
	 @J1a	 	[int],
	 @J1b	 	[int],
	 @J1c	 	[int],
	 @J1d	 	[int],
	 @J1e	 	[int],
	 @J1f	 	[int],
	 @J1g	 	[int],
	 @J1h	 	[int],
	 @J1i	 	[int],
	 @J1j	 	[int],
	 @J1k	 	[int],
	 @J1l	 	[int],
	 @J1m	 	[int],
	 @J1n	 	[int],
	 @J1o	 	[int],
	 @J2a	 	[int],
	 @J2b	 	[int],
	 @J4All	 	[int],
	 @J4a	 	[int],
	 @J4b	 	[int],
	 @J4c	 	[int],
	 @J4d	 	[int],
	 @J5All	 	[int],
	 @J5a	 	[int],
	 @J5b	 	[int],
	 @J5c	 	[int]
     --,@PURS      [int]
     )

AS INSERT INTO [dbo].[CRS_AssessShare3] 
	 ([AbstractID],
	 [I1All],
	 [I1a],
	 [I1b],
	 [I1c],
	 [I1d],
	 [I1e],
	 [I1f],
	 [I1g],
	 [I1h],
	 [I1i],
	 [I1j],
	 [I1k],
	 [I1l],
	 [I1m],
	 [I1n],
	 [I1o],
	 [I1p],
	 [I1q],
	 [I1r],
	 [I1s],
	 [I1t],
	 [I1u],
	 [I1v],
	 [I1w],
	 [I1x],
	 [I1y],
	 [I1z],
	 [I1aa],
	 [I1bb],
	 [I1cc],
	 [I1dd],
	 [I1ee],
	 [I1ff],
	 [I1gg],
	 [I1hh],
	 [I1ii],
	 [I1jj],
	 [I1kk],
	 [I1ll],
	 [I1mm],
	 [I1nn],
	 [I1oo],
	 [I1pp],
	 [I1qq],
	 [I1rr],
	 [I1ss],
	 [I1tt],
	 [I1uu],
	 [I2All],
	 [I2a],
	 [I2b],
	 [I2c],
	 [I2d],
	 [I2e],
	 [I2f],
	 [I2g],
	 [I2h],
	 [I2I],
	 [I2j],
	 [I2k],
	 [I2l],
	 [I2m],
	 [J1All],
	 [J1a],
	 [J1b],
	 [J1c],
	 [J1d],
	 [J1e],
	 [J1f],
	 [J1g],
	 [J1h],
	 [J1i],
	 [J1j],
	 [J1k],
	 [J1l],
	 [J1m],
	 [J1n],
	 [J1o],
	 [J2a],
	 [J2b],
	 [J4All],
	 [J4a],
	 [J4b],
	 [J4c],
	 [J4d],
	 [J5All],
	 [J5a],
	 [J5b],
	 [J5c] --,     [PURS]
     ) 
 
VALUES 
	(@AbstractID,
	 @I1All,
	 @I1a,
	 @I1b,
	 @I1c,
	 @I1d,
	 @I1e,
	 @I1f,
	 @I1g,
	 @I1h,
	 @I1i,
	 @I1j,
	 @I1k,
	 @I1l,
	 @I1m,
	 @I1n,
	 @I1o,
	 @I1p,
	 @I1q,
	 @I1r,
	 @I1s,
	 @I1t,
	 @I1u,
	 @I1v,
	 @I1w,
	 @I1x,
	 @I1y,
	 @I1z,
	 @I1aa,
	 @I1bb,
	 @I1cc,
	 @I1dd,
	 @I1ee,
	 @I1ff,
	 @I1gg,
	 @I1hh,
	 @I1ii,
	 @I1jj,
	 @I1kk,
	 @I1ll,
	 @I1mm,
	 @I1nn,
	 @I1oo,
	 @I1pp,
	 @I1qq,
	 @I1rr,
	 @I1ss,
	 @I1tt,
	 @I1uu,
	 @I2All,
	 @I2a,
	 @I2b,
	 @I2c,
	 @I2d,
	 @I2e,
	 @I2f,
	 @I2g,
	 @I2h,
	 @I2I,
	 @I2j,
	 @I2k,
	 @I2l,
	 @I2m,
	 @J1All,
	 @J1a,
	 @J1b,
	 @J1c,
	 @J1d,
	 @J1e,
	 @J1f,
	 @J1g,
	 @J1h,
	 @J1i,
	 @J1j,
	 @J1k,
	 @J1l,
	 @J1m,
	 @J1n,
	 @J1o,
	 @J2a,
	 @J2b,
	 @J4All,
	 @J4a,
	 @J4b,
	 @J4c,
	 @J4d,
	 @J5All,
	 @J5a,
	 @J5b,
	 @J5c --     @PURS
	 )



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_CRS_AssessShare4]
	(@AbstractID 	[int],
	 @K1All 	[int],
	 @K1a	 	[int],
	 @K1b	 	[int],
	 @K1c	 	[int],
	 @K2a	 	[varchar](3),
	 @K2b	 	[varchar](5),
	 @K3a	 	[int],
	 @K3b	 	[int],
	 @K4All 	[int],
	 @K4a	 	[int],
	 @K4b	 	[int],
	 @K4c	 	[int],
	 @K5All 	[int],
	 @K5a	 	[int],
	 @K5b	 	[int],
	 @K5c	 	[int],
	 @K5d	 	[int],
	 @K5e	 	[int],
	 @K5f	 	[int],
	 @K5g	 	[int],
	 @K5h	 	[int],
	 @K6a 		[int],
	 @K6b	 	[int],
	 @M1a	 	[int],
	 @M1b	 	[int],
	 @M1c	 	[int],
	 @M1d	 	[int],
	 @M2a	 	[int],
	 @M2b	 	[int],
	 @M4All 	[int],
	 @M4a	 	[int],
	 @M4b	 	[int],
	 @M4c	 	[int],
	 @M4d	 	[int],
	 @M4e	 	[int],
	 @M4f	 	[int],
	 @M4g	 	[int],
	 @M5All 	[int],
	 @M5a	 	[int],
	 @M5b	 	[int],
	 @M5c	 	[int],
	 @M5d	 	[int],
	 @M5e	 	[int],
	 @M5f	 	[int],
	 @M5g	 	[int],
	 @M5h	 	[int],
	 @M5I		[int],
	 @M6All 	[int],
	 @M6a	 	[int],
	 @M6b	 	[int],
	 @M6c	 	[int],
	 @M6d	 	[int],
	 @M6e	 	[int],
	 @M6f	 	[int],
	 @N1All 	[int],
	 @N1a	 	[int],
	 @N1b	 	[int],
	 @N1c	 	[int],
	 @N2	 	[int],
	 @O1	 	[varchar](2),
	 @O3	 	[int],
	 @O4a	 	[int],
	 @O4b	 	[int],
	 @O4c	 	[int],
	 @O4d	 	[int],
	 @O4e	 	[int],
	 @O4f	 	[int])

AS INSERT INTO [dbo].[CRS_AssessShare4] 
	 ([AbstractID],
	 [K1All],
	 [K1a],
	 [K1b],
	 [K1c],
	 [K2a],
	 [K2b],
	 [K3a],
	 [K3b],
	 [K4All],
	 [K4a],
	 [K4b],
	 [K4c],
	 [K5All],
	 [K5a],
	 [K5b],
	 [K5c],
	 [K5d],
	 [K5e],
	 [K5f],
	 [K5g],
	 [K5h],
	 [K6a],
	 [K6b],
	 [M1a],
	 [M1b],
	 [M1c],
	 [M1d],
	 [M2a],
	 [M2b],
	 [M4All],
	 [M4a],
	 [M4b],
	 [M4c],
	 [M4d],
	 [M4e],
	 [M4f],
	 [M4g],
	 [M5All],
	 [M5a],
	 [M5b],
	 [M5c],
	 [M5d],
	 [M5e],
	 [M5f],
	 [M5g],
	 [M5h],
	 [M5I],
	 [M6All],
	 [M6a],
	 [M6b],
	 [M6c],
	 [M6d],
	 [M6e],
	 [M6f],
	 [N1All],
	 [N1a],
	 [N1b],
	 [N1c],
	 [N2],
	 [O1],
	 [O3],
	 [O4a],
	 [O4b],
	 [O4c],
	 [O4d],
	 [O4e],
	 [O4f]) 
 
VALUES 
	(@AbstractID,
	 @K1All,
	 @K1a,
	 @K1b,
	 @K1c,
	 @K2a,
	 @K2b,
	 @K3a,
	 @K3b,
	 @K4All,
	 @K4a,
	 @K4b,
	 @K4c,
	 @K5All,
	 @K5a,
	 @K5b,
	 @K5c,
	 @K5d,
	 @K5e,
	 @K5f,
	 @K5g,
	 @K5h,
	 @K6a,
	 @K6b,
	 @M1a,
	 @M1b,
	 @M1c,
	 @M1d,
	 @M2a,
	 @M2b,
	 @M4All,
	 @M4a,
	 @M4b,
	 @M4c,
	 @M4d,
	 @M4e,
	 @M4f,
	 @M4g,
	 @M5All,
	 @M5a,
	 @M5b,
	 @M5c,
	 @M5d,
	 @M5e,
	 @M5f,
	 @M5g,
	 @M5h,
	 @M5I,
	 @M6All,
	 @M6a,
	 @M6b,
	 @M6c,
	 @M6d,
	 @M6e,
	 @M6f,
	 @N1All,
	 @N1a,
	 @N1b,
	 @N1c,
	 @N2,
	 @O1,
	 @O3,
	 @O4a,
	 @O4b,
	 @O4c,
	 @O4d,
	 @O4e,
	 @O4f)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_CRS_AssessShare5]
	(@AbstractID 	[int],
	 @P1aAll 	[int],
	 @P1aa 	[int],
	 @P1ab 	[int],
	 @P1ac 	[int],
	 @P1ad 	[int],
	 @P1ae 	[int],
	 @P1af		[int],
	 @P1ag 	[int],
	 @P1ah 	[int],
	 @P1ai	 	[int],
	 @P1aj	 	[int],
	 @P1ak 	[int],
	 @P1al	 	[int],
	 @P1am 	[int],
	 @P1an 	[int],
	 @P1ao 	[int],
	 @P1ap 	[int],
	 @P1aq 	[int],
	 @P1ar	 	[int],
	 @P1baA 	[int],
	 @P1baB 	[int],
	 @P1bbA 	[int],
	 @P1bbB 	[int],
	 @P1bcA 	[int],
	 @P1bcB 	[int],
	 @P1bdA 	[int],
	 @P1bdB 	[int],
	 @P1beA 	[int],
	 @P1beB 	[int],
	 @P1bfA 	[int],
	 @P1bfB 	[int],
	 @P3a	 	[int],
	 @P3b	 	[int],
	 @P3c	 	[int],
	 @P3d	 	[int],
	 @P3e	 	[int],
	 @P3f		[int],
	 @P3g	 	[int],
	 @P3h	 	[int],
	 @P3I	 	[int],
	 @P3j	 	[int],
	 @P3k	 	[int],
	 @P4a	 	[int],
	 @P4b	 	[int],
	 @P4c	 	[int],
	 @P4d	 	[int],
	 @P4e	 	[int],
	 @P7		[varchar](2),
	 @P8	 	[varchar](2),
	 @Q2	 	[int])

AS INSERT INTO [dbo].[CRS_AssessShare5] 
	 ([AbstractID],
	 [P1aAll],
	 [P1aa],
	 [P1ab],
	 [P1ac],
	 [P1ad],
	 [P1ae],
	 [P1af],
	 [P1ag],
	 [P1ah],
	 [P1ai],
	 [P1aj],
	 [P1ak],
	 [P1al],
	 [P1am],
	 [P1an],
	 [P1ao],
	 [P1ap],
	 [P1aq],
	 [P1ar],
	 [P1baA],
	 [P1baB],
	 [P1bbA],
	 [P1bbB],
	 [P1bcA],
	 [P1bcB],
	 [P1bdA],
	 [P1bdB],
	 [P1beA],
	 [P1beB],
	 [P1bfA],
	 [P1bfB],
	 [P3a],
	 [P3b],
	 [P3c],
	 [P3d],
	 [P3e],
	 [P3f],
	 [P3g],
	 [P3h],
	 [P3I],
	 [P3j],
	 [P3k],
	 [P4a],
	 [P4b],
	 [P4c],
	 [P4d],
	 [P4e],
	 [P7],
	 [P8],
	 [Q2]) 
 
VALUES 
	(@AbstractID,
	 @P1aAll,
	 @P1aa,
	 @P1ab,
	 @P1ac,
	 @P1ad,
	 @P1ae,
	 @P1af,
	 @P1ag,
	 @P1ah,
	 @P1ai,
	 @P1aj,
	 @P1ak,
	 @P1al,	
	 @P1am,
	 @P1an,
	 @P1ao,
	 @P1ap,
	 @P1aq,
	 @P1ar,
	 @P1baA,
	 @P1baB,
	 @P1bbA,
	 @P1bbB,
	 @P1bcA,
	 @P1bcB,
	 @P1bdA,
	 @P1bdB,
	 @P1beA,
	 @P1beB,
	 @P1bfA,
	 @P1bfB,
	 @P3a,
	 @P3b,
	 @P3c,
	 @P3d,
	 @P3e,
	 @P3f,
	 @P3g,
	 @P3h,
	 @P3I,
	 @P3j,
	 @P3k,
	 @P4a,
	 @P4b,
	 @P4c,
	 @P4d,
	 @P4e,
	 @P7,
	 @P8,
	 @Q2)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_CRS_BasicOption]
	(@AbstractID 	[int],
	 @BasicOption1 	[int],
	 @BasicOption2 	[int],
	 @BasicOption3 	[int],
	 @BasicOption4 	[int],
	 @BasicOption5 	[int],
	 @BasicOption6 	[int],
	 @BasicOption7 	[int],
	 @BasicOption8 	[int],
	 @BasicOption9 	[int],
	 @BasicOption10 	[int],
	 @BasicOption11 	[int],
	 @BasicOption12 	[int],
	 @BasicOption13 	[int],
	 @BasicOption14 	[int],
	 @BasicOption15 	[int],
	 @BasicOption16 	[int],
	 @BasicOption17 	[int],
	 @BasicOption18 	[int],
	 @BasicOption19 	[int])
AS 

INSERT INTO [CRS_BasicOption] 
	 ([AbstractID],
	 [BasicOption1],
	 [BasicOption2],
	 [BasicOption3],
	 [BasicOption4],
	 [BasicOption5],
	 [BasicOption6],
	 [BasicOption7],
	 [BasicOption8],
	 [BasicOption9],
	 [BasicOption10],
	 [BasicOption11],
	 [BasicOption12],
	 [BasicOption13],
	 [BasicOption14],
	 [BasicOption15],
	 [BasicOption16],
	 [BasicOption17],
	 [BasicOption18],
	 [BasicOption19]) 
 
VALUES 
	(@AbstractID,
	 @BasicOption1,
	 @BasicOption2,
	 @BasicOption3,
	 @BasicOption4,
	 @BasicOption5,
	 @BasicOption6,
	 @BasicOption7,
	 @BasicOption8,
	 @BasicOption9,
	 @BasicOption10,
	 @BasicOption11,
	 @BasicOption12,
	 @BasicOption13,
	 @BasicOption14,
	 @BasicOption15,
	 @BasicOption16,
	 @BasicOption17,
	 @BasicOption18,
	 @BasicOption19)





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE   PROCEDURE [I_CRS_CAPS]	(
	@AbstractID 		int, 
	@ActivitiesDailyLiving 	int,	
	@PhysicalRestraints 	int,
	@CognitiveLoss 		int,
	@Delirium	 	int,
	@Communication		int,
	@Mood			int,
	@Behaviour		int,
	@Activities		int,
	@SocialRelationship	int,
	@Falls			int,
	@Pain			int,
	@PressureUlcers		int,
	@CardioRespiratoryConditions	int,
	@UnderNutrition		int,
	@Dehydration		int,
	@FeedingTube		int,
	@AppropriateMedications	int,
	@UrinaryIncontinence	int,
	@BowelConditions	int
)  
AS INSERT INTO [dbo].[CRS_CAPS] 
	([AbstractID], 
	[CAP_ActivitiesDailyLiving],	
	[CAP_PhysicalRestraints],
	[CAP_CognitiveLoss],
	[CAP_Delirium],
	[CAP_Communication],
	[CAP_Mood],
	[CAP_Behaviour],
	[CAP_Activities],
	[CAP_SocialRelationship],
	[CAP_Falls],
	[CAP_Pain],
	[CAP_PressureUlcers],
	[CAP_CardioRespiratoryConditions],
	[CAP_UnderNutrition],
	[CAP_Dehydration],
	[CAP_FeedingTube],
	[CAP_AppropriateMedications],
	[CAP_UrinaryIncontinence],
	[CAP_BowelConditions])  
VALUES 
	(@AbstractID, 
	@ActivitiesDailyLiving,	
	@PhysicalRestraints,
	@CognitiveLoss,
	@Delirium,
	@Communication,
	@Mood,
	@Behaviour,
	@Activities,
	@SocialRelationship,
	@Falls,
	@Pain,
	@PressureUlcers,
	@CardioRespiratoryConditions,
	@UnderNutrition,
	@Dehydration,
	@FeedingTube,
	@AppropriateMedications,
	@UrinaryIncontinence,
	@BowelConditions
)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [I_CRS_Demographic]
   (@HospitalID		   [int],
    @AbstractID            [int],
    @LinkID                [int],
    @AA8                   [int],
    @AA1                   [varchar](20),
    @ChartNumber           [varchar](10),
    @RegisterNumber        [int],
    @AdmitDate             [datetime],
    @Z7                    [datetime],
    @A3                    [datetime],
    @DischargeDate         [datetime],
    @AB1b          [datetime],
    @MaidenName    [varchar](35),
    @LastName              [varchar](40),
    @MiddleName            [varchar](15),
    @FirstName             [varchar](35),
    @AdmittingNurseArea    [int],
    @RoomNumber            [varchar](10),
    @Gender                [int],
    @BirthDate             [datetime],
    @BirthDateEstimated    [int],
    @AA4a          [int],
    @MaritalStatus         [int],
    @HealthCareNumber      [varchar](12),
    @HCNProvince   [int],
    @InstitutionNumber     [int],
    @AB2a          [int],
    @AB2c          [int],
    @InstitutionFrom       [int],
    @R3a                   [int],
    @InstitutionTo         [int],
    @Z1                    [int],
    @IsCompleted           [int],
    @IsValidated           [int],
    @IsSubmited            [int],          
    @SiteNumber            [int], 
    @CoderNumber   [int],
    @HCNVersion            [varchar](2),
    @ZA6b          [int], 
    @ZAB1          [datetime], 
    @ZR4                   [datetime],
    @InterfaceDate         [datetime], 
    @InterfaceTime         [datetime], 
    @InterfaceCoder        [int], 
    @InputDate             [datetime], 
    @InputTime             [datetime], 
    @DataEntryCoder        [int], 
    @FinishDate            [datetime], 
    @FinishTime            [datetime], 
    @Secret                [int],
    @TSIDate               [datetime], 
    @TSITime               [datetime], 
    @TSICoder              [int],
    @EncounterNumber [varchar](50), 
    @SecondChartRegNumber [varchar](50), 
    @MISCode 	[int], 
    @AttendingPhysician [int], 
    @RefPhysician 	[int],
    @Z12		[datetime],
    @Z13		[datetime],
    @IsCorrected int,
    @Y3     int,
    @AA4b   int,
    @AA4c   int,
    @FixedChartNumber [varchar](50),
    @NextAssessmentDate datetime,
	@UniversalEpisodeIdentifier [varchar](50),
    @HospitalAccountRecord varchar(50),
    @R3c    int
)
AS
SELECT @AbstractID = (SELECT ISNULL(MAX(AbstractID), 0) FROM CRS_Demographic) + 1
IF @LinkID = 0 SET @LinkID = @AbstractID

UPDATE CRS_Demographic SET IsCurrent = 0 WHERE LinkID = @LinkID
INSERT INTO [dbo].[CRS_Demographic] 
    ([AbstractID],
    [LinkID],
    [HospitalID],
    [AA8],
    [AA1],
    [ChartNumber],
    [RegisterNumber],
    [ZA6b], 
    [AdmitDate],
    [ZAB1], 
    [Z7],
    [A3],
    [DischargeDate],
    [ZR4],
    [AB1b],
    [MaidenName],
    [LastName],
    [MiddleName],
    [FirstName],
    [AdmittingNurseArea],
    [RoomNumber],
    [Gender],
    [BirthDate],
    [BirthDateEstimated],
    [AA4a],
    [MaritalStatus],
    [HealthCareNumber],
    [HCNVersion],
    [HCNProvince],
    [InstitutionNumber],
    [SiteNumber],
    [CoderNumber],
    [AB2a],
    [AB2c],
    [InstitutionFrom],
    [R3a],
    [InstitutionTo],
    [Z1],
    [IsCurrent],
    [IsSubmited], 
    [IsValidated], 
    [IsCompleted], 
    [IsDeleted],
    [InterfaceDate],
    [InterfaceTime], 
    [InterfaceCoder], 
    [InputDate], 
    [InputTime], 
    [DataEntryCoder], 
    [FinishDate], 
    [FinishTime], 
    [Secret], 
    [TSIDate], 
    [TSITime], 
    [TSICoder],
    [EncounterNumber],
    [SecondChartRegNumber],
    [MISCode],
    [AttendingPhysician],
    [RefPhysician],
    [Z12],
    [Z13],
    IsCorrected,
    Y3,
    AA4b,
    AA4c,
    FixedChartNumber,
    NextAssessmentDate,
	[UniversalEpisodeIdentifier],
    [HospitalAccountRecord],
    [R3c]
)  
VALUES 
   (@AbstractID,
    @LinkID,
    @HospitalID,
    @AA8,
    @AA1,
    @ChartNumber,
    @RegisterNumber,
    @ZA6b, 
    @AdmitDate,
    @ZAB1, 
    @Z7,
    @A3,
    @DischargeDate,
    @ZR4,
    @AB1b,
    @MaidenName,
    @LastName,
    @MiddleName,
    @FirstName,
    @AdmittingNurseArea,
    @RoomNumber,
    @Gender,
    @BirthDate,
    @BirthDateEstimated,
    @AA4a,
    @MaritalStatus,
    @HealthCareNumber,
    @HCNVersion,
    @HCNProvince,
    @InstitutionNumber,
    @SiteNumber, 
    @CoderNumber,
    @AB2a,
    @AB2c,
    @InstitutionFrom,
    @R3a,
    @InstitutionTo,
    @Z1,
    1,
    @IsSubmited, 
    @IsValidated, 
    @IsCompleted, 
    2,
   @InterfaceDate, 
   @InterfaceTime, 
   @InterfaceCoder, 
   @InputDate, 
   @InputTime, 
   @DataEntryCoder, 
   @FinishDate,
   @FinishTime, 
   @Secret, 
   @TSIDate, 
   @TSITime, 
   @TSICoder,
   @EncounterNumber,
   @SecondChartRegNumber,
   @MISCode,
   @AttendingPhysician,
   @RefPhysician,
   @Z12,
   @Z13,
   @IsCorrected,
   @Y3,
   @AA4b,
   @AA4c,
   @FixedChartNumber,
   @NextAssessmentDate,
   @UniversalEpisodeIdentifier,
   @HospitalAccountRecord,
   @R3c

   )

--PR-01427
--    IF @AA8 = 14500 
--            UPDATE [dbo].[CRS_Demographic] 
--                    SET      [HospitalID]	   = @HospitalID,
-- 			    [RegisterNumber]       = @RegisterNumber,
--                             [MaidenName]           = @MaidenName,
--                             [LastName]             = @LastName,
--                             [MiddleName]           = @MiddleName,
--                             [FirstName]            = @FirstName,
--                             [Gender]               = @Gender,
--                             [BirthDate]            = @BirthDate,
--                             [BirthDateEstimated]   = @BirthDateEstimated,
--                             [MaritalStatus]                = @MaritalStatus,
--                             [HealthCareNumber]     = @HealthCareNumber,
--                             [HCNVersion]           = @HCNVersion,
--                             [HCNProvince]          = @HCNProvince,
--                             [InstitutionNumber]    = @InstitutionNumber,
--                             [SiteNumber]           = @SiteNumber,
--                             [Secret]               = @Secret
--            WHERE ([LinkID] = @LinkID)

   RETURN @AbstractID
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_CRS_Diagnosis]
	(@AbstractID 	[int],
	 @I3a	 	[int],
	 @I3b	 	[int],
	 @I3c	 	[int],
	 @I3d	 	[int],
	 @I3e	 	[int],
	 @I3f		[int])

AS INSERT INTO [dbo].[CRS_Diagnosis] 
	 ([AbstractID],
	 [I3a],
	 [I3b],
	 [I3c],
	 [I3d],
	 [I3e],
	 [I3f]) 
VALUES 
	(@AbstractID,
	 @I3a,
	 @I3b,
	 @I3c,
	 @I3d,
	 @I3e,
	 @I3f)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create procedure [I_CRS_Hobic]
    @AbstractID int,    @Fatigue int,
    @Dyspnea    int,    @Nausea  int
as
    insert into dbo.CRS_Hobic(AbstractID, Fatigue, Dyspnea, Nausea)
    values(@AbstractID, @Fatigue, @Dyspnea, @Nausea)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_CRS_Medication]
	(@AbstractID 	[int],
	 @Occurrence 	[int],
	 @U1	 	[varchar](255),
	 @U2	 	[int],
	 @U3	 	[int],
	 @U4	 	[int],
	 @U5	 	[varchar](2),
	 @U6	 	[int])

AS INSERT INTO [dbo].[CRS_Medication] 
	 ([AbstractID],
	 [Occurrence],
	 [U1],
	 [U2],
	 [U3],
	 [U4],
	 [U5],
	 [U6]) 
VALUES 
	(@AbstractID,
	 @Occurrence,
	 @U1,
	 @U2,
	 @U3,
	 @U4,
	 @U5,
	 @U6)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  procedure [I_CRS_OutcomeScale]
    @AbstractID int
    ,@ADL_Long 	int
    ,@ADL_Short int
    ,@ADL_Self 	int
    ,@ABS 	int
    ,@CHESS 	int
    ,@CPS 	int
    ,@DRS 	int
    ,@ISE 	int
    ,@Pain 	int
    ,@PSI 	int
    ,@PURS  int
    ,@FRS   int
as
    insert into dbo.CRS_OutcomeScale
	(AbstractID
	,[ADL_Long]
	,[ADL_Short]
	,[ADL_Self]
	,[ABS]
	,[CHESS]
	,[CPS]
	,[DRS]
	,[ISE]
	,[Pain]
	,[PSI]
	,[PURS]
    ,[FRS]
	)
    values
	(@AbstractID
	,@ADL_Long
	,@ADL_Short
	,@ADL_Self
	,@ABS
	,@CHESS
	,@CPS
	,@DRS
	,@ISE
	,@Pain
	,@PSI
	,@PURS
    ,@FRS
	)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_CRS_Project]
	(@AbstractID	 	[int],
	 @ProjectOccurrence	[int],
	 @ProjectNumber	[int],
	 @Question1		[int],
	 @Question2	 	[int],
	 @Question3	 	[int],
	 @Question4	 	[int],
	 @Question5		[int],
	 @Question6		[int],
	 @Question7	 	[int],
	 @Question8	 	[int],
	 @Question9	 	[int],
	 @Question10	 	[int],
	 @Question11	 	[int],
	 @Question12		[int],
	 @Question13	 	[int],
	 @Question14	 	[varchar](10),
	 @Question15	 	[varchar](10),
	 @Question16	 	[varchar](10),
	 @Question17	 	[varchar](10))
AS 

INSERT INTO [CRS_Project] 
	 ([AbstractID],
	 [ProjectOccurrence],
	 [ProjectNumber],
	 [Question1],
	 [Question2],
	 [Question3],
	 [Question4],
	 [Question5],
	 [Question6],
	 [Question7],
	 [Question8],
	 [Question9],
	 [Question10],
	 [Question11],
	 [Question12],
	 [Question13],
	 [Question14],
	 [Question15],
	 [Question16],
	 [Question17]) 
 
VALUES 
	(@AbstractID,
	 @ProjectOccurrence,
	 @ProjectNumber,
	 @Question1,
	 @Question2,
	 @Question3,
	 @Question4,
	 @Question5,
	 @Question6,
	 @Question7,
	 @Question8,
	 @Question9,
	 @Question10,
	 @Question11,
	 @Question12,
	 @Question13,
	 @Question14,
	 @Question15,
	 @Question16,
	 @Question17)





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_CRS_RAPS2]
	(@AbstractID 		int, 
	 @Delirium 		int, 
	 @Cognitive 		int, 
	 @Visual 		int, 
	 @Communication 	int, 
	 @ADL_Function 	int, 
	 @Urinary 		int, 
	 @Psychosocial 		int,
	 @Mood 		int, 
	 @Behavioural 		int, 
	 @Activities 		int, 
	 @Falls 			int, 
	 @Nutritional 		int,
	 @Feeding 		int, 
	 @Dehydration 		int, 
	 @Dental 		int, 
	 @Ulcers 		int, 
	 @Drugs 		int, 
	 @Restraints 		int)  
AS INSERT INTO [dbo].[CRS_RAPS2] 
	([AbstractID], 
	 [Delirium], 
	 [Cognitive], 
	 [Visual], 
	 [Communication], 
	 [ADL_Function], 
	 [Urinary], 
	 [Psychosocial],
	 [Mood], 
	 [Behavioural], 
	 [Activities], 
	 [Falls], 
	 [Nutritional],
	 [Feeding], 
	 [Dehydration], 
	 [Dental], 
	 [Ulcers], 
	 [Drugs], 
	 [Restraints])  
VALUES 
	(@AbstractID, 
	 @Delirium, 
	 @Cognitive, 
	 @Visual, 
	 @Communication, 
	 @ADL_Function, 
	 @Urinary, 
	 @Psychosocial,
	 @Mood, 
	 @Behavioural, 
	 @Activities, 
	 @Falls, 
	 @Nutritional,
	 @Feeding, 
	 @Dehydration, 
	 @Dental, 
	 @Ulcers, 
	 @Drugs, 
	 @Restraints)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_CRS_Signature]
	(@AbstractID	 	[int],
	 @ProviderOccurrence 	[int],
	 @R2b			[datetime],
	 @ProviderNumber 	[int],
	 @ProviderService 	[int],
	 @ProviderNotes 	[varchar](255))

AS 
INSERT INTO [dbo].[CRS_Signature] 
	 ([AbstractID],
	 [ProviderOccurrence],
	 [R2b],
	 [ProviderNumber],
	 [ProviderService],
	 [ProviderNotes]) 
 
VALUES 
	(@AbstractID,
	 @ProviderOccurrence,
	 @R2b,
	 @ProviderNumber,
	 @ProviderService,
	 @ProviderNotes)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE  PROCEDURE [I_CRS_UDAbstracting]
	(@AbstractID 	[int],
	 @UDDate1 	[datetime],
	 @UDDate2 	[datetime],
	 @UDDate3 	[datetime],
	 @UDDate4 	[datetime],
	 @UDTime1 	[datetime],
	 @UDTime2 	[datetime],
	 @UDTime3 	[datetime],
	 @UDTime4 	[datetime],
	 @UDLookup1 	[int],
	 @UDLookup2 	[int],
	 @UDLookup3 	[int],
	 @UDLookup4 	[int],
	 @UDInteger1 	[int],
	 @UDInteger2 	[int],
	 @UDInteger3 	[int],
	 @UDInteger4 	[int],
	 @UDText1 	[varchar](255),
	 @UDText2 	[varchar](255),
	 @UDText3 	[varchar](255),
	 @UDText4 	[varchar](255),
 	 @UDSmallText1 [varchar](50), 
	 @UDSmallText2 [varchar](50), 
	 @UDSmallText3 [varchar](50), 
	 @UDSmallText4 [varchar](50),
	 @UDDate5 	[datetime], 
	 @UDTime5 	[datetime], 
	 @UDLookup5 	[int], 
	 @UDInteger5 	[varchar](50), 
	 @UDText5 	[varchar](255), 
 	 @UDSmallText5 	[varchar](50))
AS 
INSERT INTO [dbo].[CRS_UDAbstracting] 
	 ([AbstractID],
	 [UDDate1],
	 [UDDate2],
	 [UDDate3],
	 [UDDate4],
	 [UDTime1],
	 [UDTime2],
	 [UDTime3],
	 [UDTime4],
	 [UDLookup1],
	 [UDLookup2],
	 [UDLookup3],
	 [UDLookup4],
	 [UDInteger1],
	 [UDInteger2],
	 [UDInteger3],
	 [UDInteger4],
	 [UDText1],
	 [UDText2],
	 [UDText3],
	 [UDText4],
	 [UDSmallText1], 
	 [UDSmallText2], 
	 [UDSmallText3], 
	 [UDSmallText4],
	 [UDDate5], 
	 [UDTime5], 
	 [UDLookup5], 
	 [UDInteger5], 
	 [UDText5], 
 	 [UDSmallText5]) 
VALUES 
	(@AbstractID,
	 @UDDate1,
	 @UDDate2,
	 @UDDate3,
	 @UDDate4,
	 @UDTime1,
	 @UDTime2,
	 @UDTime3,
	 @UDTime4,
	 @UDLookup1,
	 @UDLookup2,
	 @UDLookup3,
	 @UDLookup4,
	 @UDInteger1,
	 @UDInteger2,
	 @UDInteger3,
	 @UDInteger4,
	 @UDText1,
	 @UDText2,
	 @UDText3,
	 @UDText4,
	 @UDSmallText1, 
	 @UDSmallText2, 
	 @UDSmallText3, 
	 @UDSmallText4,
	 @UDDate5, 
	 @UDTime5, 
	 @UDLookup5, 
	 @UDInteger5, 
	 @UDText5, 
 	 @UDSmallText5)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CRS_UDFieldsDate]
	(@AbstractID 	[int],
	 @UDDate6 	[datetime],
	 @UDDate7 	[datetime],
	 @UDDate8 	[datetime],
	 @UDDate9 	[datetime],
	 @UDDate10 	[datetime],
	 @UDDate11 	[datetime],
	 @UDDate12 	[datetime],
	 @UDDate13 	[datetime],
	 @UDDate14 	[datetime],
	 @UDDate15 	[datetime],
	 @UDDate16 	[datetime],
	 @UDDate17 	[datetime],
	 @UDDate18 	[datetime],
	 @UDDate19 	[datetime],
	 @UDDate20 	[datetime],
	 @UDDate21 	[datetime],
	 @UDDate22 	[datetime],
	 @UDDate23 	[datetime],
	 @UDDate24 	[datetime],
	 @UDDate25 	[datetime])
as 
insert into [dbo].[CRS_UDFieldsDate] 
	 ([AbstractID],
	 [UDDate6],
	 [UDDate7],
	 [UDDate8],
	 [UDDate9],
	 [UDDate10],
	 [UDDate11],
	 [UDDate12],
	 [UDDate13],
	 [UDDate14],
	 [UDDate15],
	 [UDDate16],
	 [UDDate17],
	 [UDDate18],
	 [UDDate19],
	 [UDDate20],
	 [UDDate21],
	 [UDDate22],
	 [UDDate23],
	 [UDDate24],
	 [UDDate25]) 
values
	(@AbstractID,
	 @UDDate6,
	 @UDDate7,
	 @UDDate8,
	 @UDDate9,
	 @UDDate10,
	 @UDDate11,
	 @UDDate12,
	 @UDDate13,
	 @UDDate14,
	 @UDDate15,
	 @UDDate16,
	 @UDDate17,
	 @UDDate18,
	 @UDDate19,
	 @UDDate20,
	 @UDDate21,
	 @UDDate22,
	 @UDDate23,
	 @UDDate24,
	 @UDDate25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CRS_UDFieldsInteger]
	(@AbstractID 	[int],
	 @UDInteger6 	[varchar](50),
	 @UDInteger7 	[varchar](50),
	 @UDInteger8 	[varchar](50),
	 @UDInteger9 	[varchar](50),
	 @UDInteger10 	[varchar](50),
	 @UDInteger11 	[varchar](50),
	 @UDInteger12 	[varchar](50),
	 @UDInteger13 	[varchar](50),
	 @UDInteger14 	[varchar](50),
	 @UDInteger15 	[varchar](50),
	 @UDInteger16 	[varchar](50),
	 @UDInteger17 	[varchar](50),
	 @UDInteger18 	[varchar](50),
	 @UDInteger19 	[varchar](50),
	 @UDInteger20 	[varchar](50),
	 @UDInteger21 	[varchar](50),
	 @UDInteger22 	[varchar](50),
	 @UDInteger23 	[varchar](50),
	 @UDInteger24 	[varchar](50),
	 @UDInteger25 	[varchar](50))
as 
insert into [dbo].[CRS_UDFieldsInteger] 
	 ([AbstractID],
	 [UDInteger6],
	 [UDInteger7],
	 [UDInteger8],
	 [UDInteger9],
	 [UDInteger10],
	 [UDInteger11],
	 [UDInteger12],
	 [UDInteger13],
	 [UDInteger14],
	 [UDInteger15],
	 [UDInteger16],
	 [UDInteger17],
	 [UDInteger18],
	 [UDInteger19],
	 [UDInteger20],
	 [UDInteger21],
	 [UDInteger22],
	 [UDInteger23],
	 [UDInteger24],
	 [UDInteger25]) 
values
	(@AbstractID,
	 @UDInteger6,
	 @UDInteger7,
	 @UDInteger8,
	 @UDInteger9,
	 @UDInteger10,
	 @UDInteger11,
	 @UDInteger12,
	 @UDInteger13,
	 @UDInteger14,
	 @UDInteger15,
	 @UDInteger16,
	 @UDInteger17,
	 @UDInteger18,
	 @UDInteger19,
	 @UDInteger20,
	 @UDInteger21,
	 @UDInteger22,
	 @UDInteger23,
	 @UDInteger24,
	 @UDInteger25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CRS_UDFieldsLookUp]
	(@AbstractID 	[int],
	 @UDLookUp6 	[int],
	 @UDLookUp7 	[int],
	 @UDLookUp8 	[int],
	 @UDLookUp9 	[int],
	 @UDLookUp10 	[int],
	 @UDLookUp11 	[int],
	 @UDLookUp12 	[int],
	 @UDLookUp13 	[int],
	 @UDLookUp14 	[int],
	 @UDLookUp15 	[int],
	 @UDLookUp16 	[int],
	 @UDLookUp17 	[int],
	 @UDLookUp18 	[int],
	 @UDLookUp19 	[int],
	 @UDLookUp20 	[int],
	 @UDLookUp21 	[int],
	 @UDLookUp22 	[int],
	 @UDLookUp23 	[int],
	 @UDLookUp24 	[int],
	 @UDLookUp25 	[int])
as 
insert into [dbo].[CRS_UDFieldsLookUp] 
	 ([AbstractID],
	 [UDLookUp6],
	 [UDLookUp7],
	 [UDLookUp8],
	 [UDLookUp9],
	 [UDLookUp10],
	 [UDLookUp11],
	 [UDLookUp12],
	 [UDLookUp13],
	 [UDLookUp14],
	 [UDLookUp15],
	 [UDLookUp16],
	 [UDLookUp17],
	 [UDLookUp18],
	 [UDLookUp19],
	 [UDLookUp20],
	 [UDLookUp21],
	 [UDLookUp22],
	 [UDLookUp23],
	 [UDLookUp24],
	 [UDLookUp25]) 
values
	(@AbstractID,
	 @UDLookUp6,
	 @UDLookUp7,
	 @UDLookUp8,
	 @UDLookUp9,
	 @UDLookUp10,
	 @UDLookUp11,
	 @UDLookUp12,
	 @UDLookUp13,
	 @UDLookUp14,
	 @UDLookUp15,
	 @UDLookUp16,
	 @UDLookUp17,
	 @UDLookUp18,
	 @UDLookUp19,
	 @UDLookUp20,
	 @UDLookUp21,
	 @UDLookUp22,
	 @UDLookUp23,
	 @UDLookUp24,
	 @UDLookUp25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CRS_UDFieldsSmallText]
	(@AbstractID 	[int],
	 @UDSmallText6 	[varchar](50),
	 @UDSmallText7 	[varchar](50),
	 @UDSmallText8 	[varchar](50),
	 @UDSmallText9 	[varchar](50),
	 @UDSmallText10 	[varchar](50),
	 @UDSmallText11 	[varchar](50),
	 @UDSmallText12 	[varchar](50),
	 @UDSmallText13 	[varchar](50),
	 @UDSmallText14 	[varchar](50),
	 @UDSmallText15 	[varchar](50),
	 @UDSmallText16 	[varchar](50),
	 @UDSmallText17 	[varchar](50),
	 @UDSmallText18 	[varchar](50),
	 @UDSmallText19 	[varchar](50),
	 @UDSmallText20 	[varchar](50),
	 @UDSmallText21 	[varchar](50),
	 @UDSmallText22 	[varchar](50),
	 @UDSmallText23 	[varchar](50),
	 @UDSmallText24 	[varchar](50),
	 @UDSmallText25 	[varchar](50))
as 
insert into [dbo].[CRS_UDFieldsSmallText] 
	 ([AbstractID],
	 [UDSmallText6],
	 [UDSmallText7],
	 [UDSmallText8],
	 [UDSmallText9],
	 [UDSmallText10],
	 [UDSmallText11],
	 [UDSmallText12],
	 [UDSmallText13],
	 [UDSmallText14],
	 [UDSmallText15],
	 [UDSmallText16],
	 [UDSmallText17],
	 [UDSmallText18],
	 [UDSmallText19],
	 [UDSmallText20],
	 [UDSmallText21],
	 [UDSmallText22],
	 [UDSmallText23],
	 [UDSmallText24],
	 [UDSmallText25]) 
values
	(@AbstractID,
	 @UDSmallText6,
	 @UDSmallText7,
	 @UDSmallText8,
	 @UDSmallText9,
	 @UDSmallText10,
	 @UDSmallText11,
	 @UDSmallText12,
	 @UDSmallText13,
	 @UDSmallText14,
	 @UDSmallText15,
	 @UDSmallText16,
	 @UDSmallText17,
	 @UDSmallText18,
	 @UDSmallText19,
	 @UDSmallText20,
	 @UDSmallText21,
	 @UDSmallText22,
	 @UDSmallText23,
	 @UDSmallText24,
	 @UDSmallText25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CRS_UDFieldsText]
	(@AbstractID 	[int],
	 @UDText6 	[varchar](255),
	 @UDText7 	[varchar](255),
	 @UDText8 	[varchar](255),
	 @UDText9 	[varchar](255),
	 @UDText10 	[varchar](255),
	 @UDText11 	[varchar](255),
	 @UDText12 	[varchar](255),
	 @UDText13 	[varchar](255),
	 @UDText14 	[varchar](255),
	 @UDText15 	[varchar](255),
	 @UDText16 	[varchar](255),
	 @UDText17 	[varchar](255),
	 @UDText18 	[varchar](255),
	 @UDText19 	[varchar](255),
	 @UDText20 	[varchar](255),
	 @UDText21 	[varchar](255),
	 @UDText22 	[varchar](255),
	 @UDText23 	[varchar](255),
	 @UDText24 	[varchar](255),
	 @UDText25 	[varchar](255))
as 
insert into [dbo].[CRS_UDFieldsText] 
	 ([AbstractID],
	 [UDText6],
	 [UDText7],
	 [UDText8],
	 [UDText9],
	 [UDText10],
	 [UDText11],
	 [UDText12],
	 [UDText13],
	 [UDText14],
	 [UDText15],
	 [UDText16],
	 [UDText17],
	 [UDText18],
	 [UDText19],
	 [UDText20],
	 [UDText21],
	 [UDText22],
	 [UDText23],
	 [UDText24],
	 [UDText25]) 
values
	(@AbstractID,
	 @UDText6,
	 @UDText7,
	 @UDText8,
	 @UDText9,
	 @UDText10,
	 @UDText11,
	 @UDText12,
	 @UDText13,
	 @UDText14,
	 @UDText15,
	 @UDText16,
	 @UDText17,
	 @UDText18,
	 @UDText19,
	 @UDText20,
	 @UDText21,
	 @UDText22,
	 @UDText23,
	 @UDText24,
	 @UDText25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_CRS_UDFieldsTime]
	(@AbstractID 	[int],
	 @UDTime6 	[datetime],
	 @UDTime7 	[datetime],
	 @UDTime8 	[datetime],
	 @UDTime9 	[datetime],
	 @UDTime10 	[datetime],
	 @UDTime11 	[datetime],
	 @UDTime12 	[datetime],
	 @UDTime13 	[datetime],
	 @UDTime14 	[datetime],
	 @UDTime15 	[datetime],
	 @UDTime16 	[datetime],
	 @UDTime17 	[datetime],
	 @UDTime18 	[datetime],
	 @UDTime19 	[datetime],
	 @UDTime20 	[datetime],
	 @UDTime21 	[datetime],
	 @UDTime22 	[datetime],
	 @UDTime23 	[datetime],
	 @UDTime24 	[datetime],
	 @UDTime25 	[datetime])
as 
insert into [dbo].[CRS_UDFieldsTime] 
	 ([AbstractID],
	 [UDTime6],
	 [UDTime7],
	 [UDTime8],
	 [UDTime9],
	 [UDTime10],
	 [UDTime11],
	 [UDTime12],
	 [UDTime13],
	 [UDTime14],
	 [UDTime15],
	 [UDTime16],
	 [UDTime17],
	 [UDTime18],
	 [UDTime19],
	 [UDTime20],
	 [UDTime21],
	 [UDTime22],
	 [UDTime23],
	 [UDTime24],
	 [UDTime25]) 
values
	(@AbstractID,
	 @UDTime6,
	 @UDTime7,
	 @UDTime8,
	 @UDTime9,
	 @UDTime10,
	 @UDTime11,
	 @UDTime12,
	 @UDTime13,
	 @UDTime14,
	 @UDTime15,
	 @UDTime16,
	 @UDTime17,
	 @UDTime18,
	 @UDTime19,
	 @UDTime20,
	 @UDTime21,
	 @UDTime22,
	 @UDTime23,
	 @UDTime24,
	 @UDTime25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE   PROCEDURE [I_CRS_UpdateRecord]
	(@AbstractID 	[int],
	 @AD1		[int],
	 @AD2		[int],
     @AD4    int --varchar(5)
	 
)

AS INSERT INTO [dbo].[CRS_UpdateRecord] 
	 ([AbstractID],
	 [AD1],
	 [AD2],
	 [AD4]) 
 
VALUES 
	(@AbstractID,
	 @AD1,
	 @AD2,
	 @AD4)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--EN-00183
--@HeaderDefID		[int],
CREATE  PROCEDURE [I_Def_Activity]
	(@DefID		[int],
	 @DefOccurrence	[int],
	 @DefeciencyID 	[int],
	 @DefStartDate 		[datetime],
	 @DefEndDate 		[datetime],
	 @DefDays 		[int],
	 @DefCompletedBy 	[int],
	 @DefCode 		[int],
	 @DefCodeType 	[int],
	 @DefMessage 		[int],
	 @DefResident 		[varchar](20),
	 @DefStatus 		[int],
	 @DefNote 		[varchar](255),
     @JobNumber     varchar(255))
AS 
INSERT INTO [dbo].[Def_Activity] 
	 ([DefID],
	 [DefOccurrence],
	 [DefeciencyID],
	 [DefStartDate],
	 [DefEndDate],
	 [DefDays],
	 [DefCompletedBy],
	 [DefCode],
	 [DefCodeType],
	 [DefMessage],
	 [DefResident],
	 [DefStatus],
	 [DefNote],
     JobNumber) 
VALUES 
	(@DefID,
	 @DefOccurrence,
	 @DefeciencyID,
	 @DefStartDate,
	 @DefEndDate,
	 @DefDays,
	 @DefCompletedBy,
	 @DefCode,
	 @DefCodeType,
	 @DefMessage,
	 @DefResident,
	 @DefStatus,
	 @DefNote,
     @JobNumber)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE Procedure [I_Def_BatchComplete]
(
    @DefeciencyID     int,
    @DefCompleteCoder  int
)
as

declare @DefEndDate  datetime
Declare @Count            int
        
set @DefEndDate = getdate()
set @Count = 0

Update dbo.Def_SlipMain 
set DefMainStatus = 8, 
    DefEndDate = @DefEndDate,
    DefDays = datediff(day, DefStartDate, @DefEndDate)
where DefeciencyID = @DefeciencyID

set @Count = @@Rowcount

Update dbo.Def_Activity
set DefCompletedBy = @DefCompleteCoder,
    DefEndDate = @DefEndDate, 
    DefStatus = 8, 
    DefDays = datediff(day, DefStartDate, @DefEndDate)
where HeaderDefID = @DefeciencyID and isnull(DefStatus, 0) not in (8, 11)

-- Return Value: 0 no records affect, 1 success, -1 means the lastest tra
return (@Count)







GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE Procedure [I_Def_BatchCompleteDetail]
(
    @DefID            int,
    @DetailID         int,
    @DefeciencyID     int,
    @DefCompleteCoder  int
)
as

declare @DefEndDate  datetime
        
set @DefEndDate = getdate()
--EN-00183
Update dbo.Def_Activity 
set DefStatus = 8, 
    DefEndDate = @DefEndDate,
    DefDays = datediff(day, DefStartDate, @DefEndDate),
    DefCompletedBy = @DefCompleteCoder
where DefeciencyID = @DetailID and DefID = @DefID

if not exists (select top 1 DefeciencyID from dbo.Def_Activity A
        inner join dbo.DefLU_ChartStatus S on A.DefStatus = S.Code
        where S.DisplayCode not in ('C', 'X') and DefID = @DefID) --HeaderDefID = @DefeciencyID
begin
    Update dbo.Def_SlipMain 
    set DefMainStatus = 8, 
        DefEndDate = @DefEndDate,
        DefDays = datediff(day, DefStartDate, @DefEndDate) - (isnull(DefHoldDays, 0) + isnull(DefManualDays, 0) + isnull(DefVacationDays, 0) + isnull(DefSuspensionDays, 0))
    where DefID = @DefID
--    where DefeciencyID = @DefeciencyID

	declare @HID as int --NP-00025
	select @HID = HospitalID from U_Users where Code = @DefCompleteCoder
	insert Def_UpdateHistory (DefID, DefeciencyID, HospitalID, Coder, Updated, UpdateType) 
    values(@DefID, @DefeciencyID, @HID, @DefCompleteCoder, @DefEndDate, 'Saved')
end

return (0)




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [I_Def_Key]
	@DefNumber as Int output,
	@HospID as int = 0
AS 

--According James, TOH want the deficiency ID to be unique after conversion. But we don't get ticket to do it.
--    set @HospID  =0

	if @HospID = 0
	begin
		SET @DefNumber = (SELECT  TOP 1 (CASE WHEN MAX(StartDefNumber) + 100 > 10000000 THEN MAX(StartDefNumber) + 100 ELSE 10000000 END) FROM dbo.H_HospitalProfile)
		UPDATE dbo.H_HospitalProfile SET StartDefNumber = @DefNumber
	end

	else
	begin
		SET @DefNumber = (SELECT  TOP 1 (CASE WHEN MAX(StartDefNumber) + 100 > 10000000 THEN MAX(StartDefNumber) + 100 ELSE 10000000 END) FROM dbo.H_HospitalProfile WHERE Code = @HospID)
		UPDATE dbo.H_HospitalProfile SET StartDefNumber = @DefNumber WHERE Code = @HospID
	end


	RETURN 0


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




--EN-00183 Add DefID
CREATE      PROCEDURE [I_Def_SlipMain]
   (@HospitalID [int],
    @DefID         [int],
    @DefeciencyID  [int],
    @DefPatientID          [int],
    @DefLastName           [varchar](40),
    @DefFirstName          [varchar](35),
    @DefBirthDate          [datetime],
    @DefAbstractID         [int],
    @DefVolumeID   [int],
    @DefInstNumber [int],
    @DefSiteNumber [int],
    @DefDrNumber   [int],
    @DefDrStatus           [varchar](10),
    @DefColour             [int],
    @DefMainStatus         [int],
    @DefMainNote   [varchar](255),
    @DefStartDate          [datetime],
    @DefEndDate            [datetime],
    @DefDays               [int],
    @DefHoldStartDate      [datetime],
    @DefHoldEndDate        [datetime],
    @DefHoldDays   [int],
    @DefManualDays         [int],
    @DefVacationDays       [int],
    @DefSuspensionDays     [int],
    @ProviderService 	[int], 
    @ProviderSpecialty 	[int],
    @DefTotalDays int)
AS 

declare @ID int

INSERT INTO  [dbo].[Def_SlipMain] 
   ([HospitalID],
    [DefeciencyID],
    [DefPatientID], 
    [DefPatLastName],
    [DefPatFirstName],
    [DefBirthDate],
    [DefAbstractID],
    [DefVolumeID],  
    [DefInstNumber],
    [DefSiteNumber],
    [DefDrNumber],
    [ProviderService], 
    [ProviderSpecialty],
    [DefDrStatus],
    [DefColour],
    [DefMainStatus]        ,
    [DefMainNote],
    [DefStartDate],
    [DefEndDate],
    [DefDays],
    [DefHoldStartDate],
    [DefHoldEndDate],
    [DefHoldDays],
    [DefManualDays],
    [DefVacationDays],
    [DefSuspensionDays],
    [DefTotalDays])
VALUES
   (@HospitalID,
    @DefeciencyID,
    @DefPatientID,
    @DefLastName,
    @DefFirstName,
    @DefBirthDate,
    @DefAbstractID,
    @DefVolumeID,
    @DefInstNumber,
    @DefSiteNumber,
    @DefDrNumber,
    @ProviderService, 
    @ProviderSpecialty,
    @DefDrStatus,
    @DefColour,
    @DefMainStatus,
    @DefMainNote,
    @DefStartDate,
    @DefEndDate,
    @DefDays,
    @DefHoldStartDate,
    @DefHoldEndDate,
    @DefHoldDays,
    @DefManualDays,
    @DefVacationDays,
    @DefSuspensionDays,
    @DefTotalDays)

set @ID = @@Identity
exec P_ResetProviderCurrentLevel @DefDrNumber

    return(@ID)






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE    Procedure [I_Def_Transfer]
(
    @DefDrNumberFrom  int,
    @DefID            int,
    @DefDetailID      int,
    @DefDrNumberTo    int,
    @DefTransferCoder int,
    @DefNewStartDate  datetime
)
as
Declare @DefeciencyID    int
Declare @DefTransferDate  datetime
Declare @DefStartDate     datetime
Declare @Count            int
Declare @DefTransferID     int, @DefTransferLastId     int
Declare @IsSameProvider   int    --0 will no, 1 will yes
Declare @NewDefeciencyID  int
Declare @NewDetailID      int
Declare @UniversalID      int
Declare @DefPatientID     int
Declare @DefInstNumber    int
Declare @DefVolumeID      int
Declare @HospitalID       int
Declare @New              int
Declare @TotalDetail      int
Declare @Occ              int
Declare @NewDefID         int

set @New = 0
--EN-00183
--set @DefeciencyID = (select top 1 HeaderDefID from dbo.Def_Activity where DefeciencyID = @DefDetailID)
select 
    @DefeciencyID  = DefeciencyID,
    @UniversalID   = DefAbstractID, 
    @DefPatientID  = DefPatientID,
    @DefVolumeID   = DefVolumeID,
    @DefInstNumber = DefInstNumber,
    @HospitalID    = isnull(HospitalID, 0)
from dbo.Def_SlipMain
where DefID = @DefID
--where DefeciencyID = @DefeciencyID

--set @TotalDetail = (select count(*) from dbo.Def_Activity where HeaderDefID = @DefeciencyID)
set @TotalDetail = (select count(*) from dbo.Def_Activity where DefID = @DefID)

-- PR - 02183 Always to merge into new doctor
select top 1 @NewDefeciencyID = DefeciencyID, @NewDefID = DefID
from dbo.Def_SlipMain
where DefDrNumber = @DefDrNumberTo
    and isnull(DefPatientID, 0)  = isnull(@DefPatientID, 0)
    and isnull(DefVolumeID, 0)   = isnull(@DefVolumeID, 0)
    and isnull(DefInstNumber, 0) = isnull(@DefInstNumber, 0)
    and isnull(DefAbstractID, 0) = isnull(@UniversalID, 0)
    and isnull(HospitalID, 0)    = isnull(@HospitalID, 0)

if @TotalDetail = 1 and isnull(@NewDefeciencyID, 0) = 0
begin
    set @NewDefeciencyID = @DefeciencyID
    set @NewDefID = @DefID
end

if @NewDefeciencyID is null
begin
    execute I_Def_Key @NewDefeciencyID output, @HospitalID
    set @NewDetailID = @NewDefeciencyID + 1
    set @Occ = 1
    set @New = 1
end
else if @DefID = isnull(@NewDefID, 0)  --@NewDefeciencyID = @DefeciencyID
    set @NewDetailID = @DefDetailID
--EN-00183
else
begin
--    set @NewDetailID = isnull((select max(DefeciencyID) from dbo.Def_Activity where HeaderDefID = @NewDefeciencyID), @NewDefeciencyID) + 1
    set @NewDetailID = isnull((select max(DefeciencyID) from dbo.Def_Activity where DefID = @NewDefID), @NewDefeciencyID) + 1
    set @Occ = @NewDetailID % 100
end

set @DefNewStartDate = isnull(@DefNewStartDate, '1900/01/01')
set @DefTransferDate = getdate()
set @Count = 0
set @IsSameProvider = 1

set @DefTransferLastId = (select max(DefTransferID) 
                          from Def_Transfer 
                            inner join DefLU_TransferStatus on Code = DefTransferStatus 
                          where DisplayCode not in ('U', 'T')
                             and DefeciencyID = @DefDetailID) 

-- if @DefTransferLastId is not null 
-- begin
--     if @DefDrNumberFrom = (select DefDrNumberTo from Def_Transfer where DefTransferId = @DefTransferLastId)
--         set @IsSameProvider = 1
--     else
--         set @IsSameProvider = 0
-- end
if @IsSameProvider = 1
begin
    --If the records has been Transfered before, we need to disable the last DefTransferStatus.
    --Because procedure only passes none completed deficiency. I only update the latest none undo transfer record.
    --print '@DefTransferLastId = ' + cast(@DefTransferLastId as varchar(10))
    insert Def_Transfer_History (DefTransferID, DefTransferLastStatus, 
        DefTransferCurrStatus, DefTransferStatusCoder, DefTransferStatusDate)
    select DefTransferID, DefTransferStatus, 
        (select top 1 Code from DefLU_TransferStatus S where S.DisplayCode = 'T' order by Code), 
        @DefTransferCoder, @DefTransferDate
    from Def_Transfer
    where DefTransferID = @DefTransferLastId

    Update Def_Transfer
    set DefTransferStatus = (select top 1 Code from DefLU_TransferStatus S where S.DisplayCode = 'T' order by Code), 
        DefTransferStatusCoder = @DefTransferCoder,
        DefTransferStatusDate = @DefTransferDate
    where DefTransferID = @DefTransferLastId

    --Keep Transfer Records
    set @DefTransferID = isnull((select max(DefTransferID) from Def_Transfer), 0) + 1
    --print '@DefTransferID = ' + cast(@DefTransferID as varchar(10))



    insert Def_Transfer(DefTransferID, DefTransferCoder, DefDrNumberFrom, DefeciencyID, 
        DefDrNumberTo, DefTransferDate, DefStartDate, DefNewStartDate, DefTransferLastId, 
        DefTransferStatus, DefTransferStatusCoder, DefTransferStatusDate, NewDetailID, DefID) 
    select @DefTransferID, @DefTransferCoder, @DefDrNumberFrom, @DefDetailID, 
        @DefDrNumberTo, @DefTransferDate, DefStartDate, 
        DefNewStartDate = (case when isnull(@DefNewStartDate, '1900/01/01') < '1950/01/01' then DefStartDate else @DefNewStartDate end),
        @DefTransferLastId, 
        DefTransferStatus = (select top 1 Code from DefLU_TransferStatus S where S.DisplayCode = 'N' order by Code), 
        null, @DefTransferDate, @NewDetailID, @NewDefID  --PR-01721 @DefID
    from Def_SlipMain
    where DefID = @DefID
--    where DefeciencyID = @DefeciencyID

    insert Def_Transfer_History (DefTransferID, DefTransferLastStatus, 
        DefTransferCurrStatus, DefTransferStatusCoder, DefTransferStatusDate)
    select @DefTransferID, null, 
        (select top 1 Code from DefLU_TransferStatus S where S.DisplayCode = 'N' order by Code), 
        @DefTransferCoder, @DefTransferDate
    --Ticket     
    --Transfer
    if @New = 0 and @DefeciencyID = @NewDefeciencyID
    begin
        UPdate dbo.Def_SlipMain
        set DefDrNumber = @DefDrNumberTo,
            DefStartDate = (case when isnull(@DefNewStartDate, '1900/01/01') < '1950/01/01' then DefStartDate else @DefNewStartDate end),
            ProviderService = (select top 1 code from dbo.LLU_ProviderServices where AssociationID = @DefDrNumberTo and isnull(AssociationID, 0) <> 0 and Type = 1 and (case when isnull(@DefNewStartDate, '1900/01/01') < '1950/01/01' then DefStartDate else @DefNewStartDate end) between validfrom and validto),
            ProviderSpecialty = (select top 1 code from dbo.LLU_ProviderSpecialty where AssociationID = @DefDrNumberTo and isnull(AssociationID, 0) <> 0 and Type = 1 and (case when isnull(@DefNewStartDate, '1900/01/01') < '1950/01/01' then DefStartDate else @DefNewStartDate end) between validfrom and validto)
        from Def_SlipMain 
           inner join DefLU_ChartStatus on Def_SlipMain.DefMainStatus = DefLU_ChartStatus.code
        where DefID = @DefID
--EN-00183
--        where DefDrNumber = @DefDrNumberFrom 
--            and DefeciencyID = @DefeciencyID
        if isnull(@DefNewStartDate, '1900/01/01') > '1950/01/01'
            update Def_Activity 
            set DefStartDate = @DefNewStartDate 
            where DefID = @DefID
--            where HeaderDefID = @DefeciencyID 
        if isnull(@DefNewStartDate, '1900/01/01') > '1950/01/01' 
            exec dbo.C_DefCount @DefID
    end
    else     
    begin
        if @New = 1
        begin
            insert into dbo.Def_SlipMain(DefeciencyID, DefPatientID, DefPatLastName, DefPatFirstName, DefBirthDate, DefAbstractID, DefVolumeID, DefInstNumber, DefSiteNumber, DefDrNumber, DefDrStatus, DefColour, DefMainStatus, DefMainNote, DefStartDate, DefEndDate, DefDays, DefHoldStartDate, DefHoldEndDate, DefHoldDays, DefManualDays, DefVacationDays, DefSuspensionDays, ProviderService, ProviderSpecialty, HospitalID)
            select @NewDefeciencyID, DefPatientID, DefPatLastName, DefPatFirstName, DefBirthDate, DefAbstractID, DefVolumeID, DefInstNumber, DefSiteNumber, 
                @DefDrNumberTo, 
                DefDrStatus = (select top 1 ProvdrState from lu_provider where Code = @DefDrNumberTo), 
                DefColour, DefMainStatus, DefMainNote, 
                DefStartDate = (case when isnull(@DefNewStartDate, '1900/01/01') < '1950/01/01' then DefStartDate else @DefNewStartDate end), 
                DefEndDate, DefDays, DefHoldStartDate, DefHoldEndDate, DefHoldDays, DefManualDays, DefVacationDays, DefSuspensionDays, 
                ProviderService = (select top 1 code from dbo.LLU_ProviderServices where AssociationID = @DefDrNumberTo and isnull(AssociationID, 0) <> 0 and Type = 1 and (case when isnull(@DefNewStartDate, '1900/01/01') < '1950/01/01' then DefStartDate else @DefNewStartDate end) between validfrom and validto),
                ProviderSpecialty = (select top 1 code from dbo.LLU_ProviderSpecialty where AssociationID = @DefDrNumberTo and isnull(AssociationID, 0) <> 0 and Type = 1 and (case when isnull(@DefNewStartDate, '1900/01/01') < '1950/01/01' then DefStartDate else @DefNewStartDate end) between validfrom and validto),
                HospitalID
            from dbo.Def_SlipMain
            where DefID = @DefID
--EN-00183
--            where DefeciencyID = @DefeciencyID
            set @NewDefID = @@Identity
--PR-01721
            update Def_Transfer set DefID = @NewDefID where DefTransferID = @DefTransferID

        end

        Update Def_Activity
        set DefeciencyID = @NewDetailID,
            HeaderDefID = @NewDefeciencyID,
            DefStartDate = (case when isnull(@DefNewStartDate, '1900/01/01') < '1950/01/01' then DefStartDate else @DefNewStartDate end),
            DefID = @NewDefID
        where DefeciencyID = @DefDetailID and DefID = @DefID

        --EN-00183
        Update Def_SlipMain set DefMainStatus = 7 
        where DefMainStatus in (8, 11) and DefID = @NewDefID     --DefeciencyID = @NewDefeciencyID

        if not exists (select * from dbo.Def_Activity where DefID = @DefID)    --HeaderDefID = @DefeciencyID)
            delete from dbo.Def_SlipMain where DefID = @DefID    --    DefeciencyID = @DefeciencyID
        else if not exists (select * from dbo.Def_Activity where DefID = @DefID and isnull(DefStatus, 0) not in (8, 11)) --HeaderDefID = @DefeciencyID 
            Update dbo.Def_SlipMain 
            set DefMainStatus = 8, 
                DefEndDate = isnull(DefEndDate, getdate()) 
            where DefID = @DefID
--            where DefeciencyID = @DefeciencyID
        if isnull(@DefNewStartDate, '1900/01/01') > '1950/01/01' 
            exec dbo.C_DefCount @NewDefID
    end
    set @Count = @NewDetailID
    -- PR - 02183 Always to merge into new doctor
    if not exists (select * from Def_Activity where DefID = @DefID)
    begin
        Delete from Def_SlipMain where DefID = @DefID
    end
    --PR - 02083
    insert into dbo.Def_UpdateHistory(DefeciencyID, Coder, Updated, UpdateType, HospitalID, DefID)
    values(@NewDefeciencyID, @DefTransferCoder, getdate(), 'Transfer', @HospitalID, isnull(@NewDefID, @DefID))
    if isnull(@NewDefID, 0) > 0
        Update dbo.Def_UpdateHistory 
        set DefID = @NewDefID,
            DefeciencyID = @NewDefeciencyID
        where DefID = @DefID

end
else 
    set @Count = -1   


-- Return Value: 0 no records affect, 1 success, -1 means the lastest tra
return (@Count)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--Only one record undo each call
CREATE    Procedure [I_Def_Transfer_Undo]
(
    @DefDrNumberFrom  int,
    @DefDetailID      int,
    @DefDrNumberTo    int,
    @DefTransferCoder int,
    @TranDefDetailID  int 
--I am not sure we need the new deficiency start date. Just disable now.
--,    @DefNewStartDate  datetime 
)
as

Declare @DefTransferDate  datetime
Declare @DefStartDate     datetime
Declare @Count            int
Declare @DefTransferID     int, @DefTransferLastId     int
Declare @IsSameProvider   int    --0 will no, 1 will yes
declare @DefeciencyID     int
declare @TranDefID        int
declare @NewDetailID      int
declare @occ              int
declare @NewDefID         int

set @DefeciencyID = (@DefDetailID / 100) * 100
set @TranDefID = (select top 1 HeaderDefID from dbo.Def_Activity where DefeciencyID = @TranDefDetailID)


--set @DefNewStartDate = isnull(@DefNewStartDate, '1900/01/01')
set @DefTransferDate = getdate()
set @Count = 0
set @IsSameProvider = 1

set @DefTransferLastId = (select max(DefTransferID) from Def_Transfer 
                            inner join DefLU_TransferStatus on Code = DefTransferStatus 
                         where DisplayCode not in ('U', 'T')
                            and DefeciencyID = @DefDetailID) 
if @DefTransferLastId is not null 
begin
    if @DefDrNumberFrom = (select DefDrNumberFrom from Def_Transfer where DefTransferId = @DefTransferLastId)
        and @DefDrNumberTo = (select DefDrNumberTo from Def_Transfer where DefTransferId = @DefTransferLastId)
        set @IsSameProvider = 1
    else
        set @IsSameProvider = 0
end
-- print '@DefTransferLastId = ' + cast(isnull(@DefTransferLastId, '-1') as varchar(10)) + 
--     '   @IsSameProvider = ' + cast(isnull(@IsSameProvider, '-1') as varchar(10))

if @IsSameProvider = 1 and @DefTransferLastId > 0
begin

    --If the records has been Transfered before, we need to disable the last DefTransferStatus.
    insert Def_Transfer_History (DefTransferID, DefTransferLastStatus, 
        DefTransferCurrStatus, DefTransferStatusCoder, DefTransferStatusDate) 
    select DefTransferID, DefTransferStatus, 
        (select top 1 Code from DefLU_TransferStatus S where S.DisplayCode = 'U' order by Code), 
        @DefTransferCoder, @DefTransferDate
    from Def_Transfer
    where DefTransferID = @DefTransferLastId

    Update Def_Transfer
    set DefTransferStatus = (select top 1 Code from DefLU_TransferStatus S where S.DisplayCode = 'U' order by Code), 
        DefTransferStatusCoder = @DefTransferCoder,
        DefTransferStatusDate = @DefTransferDate
    where DefTransferID = @DefTransferLastId
    
    --set Roll Back Flag
    set @DefTransferID = (select DefTransferLastId from Def_Transfer where DefTransferID = @DefTransferLastId)
    if isnull(@DefTransferID, 0) > 0
    begin
        insert Def_Transfer_History (DefTransferID, DefTransferLastStatus, 
            DefTransferCurrStatus, DefTransferStatusCoder, DefTransferStatusDate)
        select DefTransferID, DefTransferStatus, 
            (select top 1 Code from DefLU_TransferStatus S where S.DisplayCode = 'R' order by Code), 
            @DefTransferCoder, @DefTransferDate
        from Def_Transfer
        where DefTransferID = @DefTransferID

        Update Def_Transfer
        set DefTransferStatus = (select top 1 Code from DefLU_TransferStatus S where S.DisplayCode = 'R' order by Code), 
            DefTransferStatusCoder = @DefTransferCoder,
            DefTransferStatusDate = @DefTransferDate
        where DefTransferID = @DefTransferID
    end
    --Transfer back
    if @DefDetailID = @TranDefDetailID
    begin
        if isnull(@DefTransferID, 0) > 0
            Update Def_SlipMain
            set DefDrNumber = DefDrNumberTo,
                DefStartDate = Def_Transfer.DefNewStartDate
            from Def_SlipMain 
                inner join Def_Transfer on Def_SlipMain.DefeciencyID = Def_Transfer.DefeciencyID
            where Def_SlipMain.DefeciencyID = @DefeciencyID 
                and Def_Transfer.DefTransferID = @DefTransferID
        else
            Update Def_SlipMain
            set DefDrNumber = Def_Transfer.DefDrNumberFrom,
                DefStartDate = Def_Transfer.DefStartDate
            from Def_SlipMain 
                inner join Def_Transfer on Def_SlipMain.DefeciencyID = Def_Transfer.DefeciencyID
            where DefDrNumber = @DefDrNumberTo 
                and Def_SlipMain.DefeciencyID = @DefeciencyID 
                and Def_Transfer.DefTransferID = @DefTransferLastId
    end
    else
    begin
        if exists (select * from dbo.Def_Activity where DefeciencyID = @DefDetailID)
            set @NewDetailID = isnull( (select max(DefeciencyID) from Def_Activity where HeaderDefID = @DefeciencyID), @DefeciencyID) + 1
        else
            set @NewDetailID = @DefDetailID
        set @occ = @NewDetailID % 100
        if not exists (select * from dbo.Def_SlipMain where DefeciencyID = @DefeciencyID)
            insert into dbo.Def_SlipMain(DefeciencyID, DefPatientID, DefPatLastName, DefPatFirstName, DefBirthDate, DefAbstractID, DefVolumeID, DefInstNumber, DefSiteNumber, DefDrNumber, DefDrStatus, DefColour, DefMainStatus, DefMainNote, DefStartDate, DefEndDate, DefDays, DefHoldStartDate, DefHoldEndDate, DefHoldDays, DefManualDays, DefVacationDays, DefSuspensionDays, ProviderService, ProviderSpecialty, HospitalID)
            select @DefeciencyID, DefPatientID, DefPatLastName, DefPatFirstName, 
                DefBirthDate, DefAbstractID, DefVolumeID, DefInstNumber, DefSiteNumber, 
                (case when isnull(@DefTransferID, 0) > 0 
                      then @DefDrNumberTo 
                      else @DefDrNumberFrom
                 end), DefDrStatus, DefColour, DefMainStatus, DefMainNote, DefStartDate, DefEndDate, DefDays, DefHoldStartDate, DefHoldEndDate, DefHoldDays, DefManualDays, DefVacationDays, DefSuspensionDays, ProviderService, ProviderSpecialty, HospitalID
            from dbo.Def_SlipMain
            where DefeciencyID = @TranDefID
        update dbo.Def_Activity
        set DefeciencyID = @NewDetailID,
            DefOccurrence = @occ
        where DefeciencyID = @TranDefDetailID
    end
    set @Count = @@Rowcount
end    
else if @DefTransferLastId = 0 -- ProviderFrom or Provider To not match with parameter
    set @Count = -2
else 
    set @Count = -1    -- Not found

--Return 1 success, 0 fail to update, -1 transfer record not match, -2 not transfer record found

return (@Count)    






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE   PROCEDURE [I_Def_UpdateHistory]
(@DefID 	[int],
 @Coder 	[int],
@UpdateType varchar(10))
AS 

declare @HID as int --NP-00025
select @HID = HospitalID from U_Users where Code = @Coder

--EN-00183
declare @DeficiencyID int
set @DeficiencyID = (select top 1 DefeciencyID from Def_SlipMain where DefID = @DefID)

if @DefID > 0 --PR - 03582 Some records are inserted when @DefID = 0
    insert into [Def_UpdateHistory] ([DefeciencyID], [HospitalID], [Coder], [Updated], UpdateType, DefID) 
    values (@DeficiencyID,  @HID, @Coder, GetDate(), @UpdateType, @DefID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE    PROCEDURE [I_Def_UpdateHistory_FromCPI] 
	@PatientID  as int,
	@Coder as int,
	@UpdateType as varchar(10) = 'Saved'
AS  

declare @HID as int --NP-00025
select @HID = HospitalID from U_Users where Code = @Coder

--EN-00183
insert into Def_UpdateHistory (DefeciencyID, HospitalID, Coder, Updated, UpdateType, DefID) 
select 
	DefeciencyID, @HID, @Coder, GetDate(), @UpdateType, DefID
from Def_SlipMain 
where DefPatientID = @PatientID
    and isnull(DefMainStatus, 0) not in (8, 11)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [I_Deficiency_FromTran]
   (@TranscriptionID  int,
    @DefCode          int,
    @Coder            int,
    @Completed        varchar(12)
)
AS
    declare @DefeciencyID   int
    declare @HospitalID     int
    declare @Occ            int
    declare @AbstractID     int
    declare @PatientiD      int
    declare @Provider       int 
    declare @CareType       int
    declare @SignDate datetime
    declare @UniversalID    int
    declare @Colour         int
    declare @DefID          int

    select top 1 
        @AbstractID = AbstractID, 
        @PatientID  = PatientID, 
        @Provider   = SignPhysician,
        @SignDate   = SignDate,
        @CareType   = CareType,
        @HospitalID = HospitalID
    from TR_Main
    where  TranscriptionID = @TranscriptionID

    --This step may not be needed
    select top 1 
        @DefeciencyID = Def_SlipMain.DefeciencyID,
        @UniversalID  = AB_Main.UniversalID,
        @DefID        = DefID
    from Def_SlipMain 
        inner join AB_Main on Def_SlipMain.DefAbstractID = AB_Main.UniversalID
    where Def_SlipMain.DefDrNumber = @Provider
        and AB_Main.AppType = @CareType 
        and AB_Main.AbstractID = @AbstractID
--        and Def_SlipMain.DefMainStatus <> 11 
    
    
    if @DefeciencyID is null and @Completed = '0'
    begin
        exec I_Def_Key @DefeciencyID output, @HospitalID 
        if isnull(@UniversalID, 0) = 0 
            set @Colour = 1
        else
        begin
            set @Colour = isnull((select max(DefColour) from Def_SlipMain where DefAbstractID = @UniversalID), 0) + 1
            if not exists (select * from DefLU_DocColourCode where Code = @Colour)
                set @Colour = 1
        end

        INSERT INTO Def_SlipMain(HospitalID, DefeciencyID, DefPatientID, 
            DefPatLastName, DefPatFirstName, DefBirthDate, DefAbstractID,
            DefVolumeID, DefInstNumber, DefSiteNumber, DefDrNumber,
            ProviderService, ProviderSpecialty, DefDrStatus, DefColour,
            DefMainStatus, DefMainNote, DefStartDate, DefEndDate,
            DefDays)
        select top 1
            T.HospitalID, @DefeciencyID, T.PatientID, 
            C.LastName, C.FirstName, C.BirthDate, M.UniversalID,
            M.VolumeID, M.InstitutionNumber, null, T.SignPhysician,
            ProviderService = (case when isnull(T.CareType, 0) = 5  then null else 
                (select top 1 Code from LLU_ProviderServices where Type = 1 and AssociationID = T.SignPhysician and getdate() between validfrom and validto)
            end),
            ProviderSpecialty = (case when T.CareType <> 5  then null else
                (select top 1 Code from LLU_ProviderSpecialty where Type = 1 and AssociationID = T.SignPhysician and getdate() between validfrom and validto)
            end),
            P.ProvdrState, @Colour, 
            DefMainStatus = 7, 
            DefMainNote = 'Create by Transcription ',
            DefStartDate = convert(varchar(10), getdate(), 111),
            DefEndDate = (case when @Completed = '1' then convert(varchar(10), getdate(), 111) else null end),
            DefDays = (case when @Completed = '1' then 1 else null end)
        from TR_Main T
            inner join LU_Provider P on T.SignPhysician = P.Code
            left join CM_CPI C on T.PatientID = C.PatientID
            left join AB_Main M on T.AbstractID = M.AbstractID and T.CareType = M.APPType
--            left join AB_Abstract A on T.AbstractID = A.AbstractID and T.CareType = A.CareType
        where T.TranscriptionID = @TranscriptionID
        --EN-00183
        set @DefID = @@Identity
        set @occ = 1
    end

    if @DefeciencyID is not null
    begin
        update Def_Activity
        set DefStatus = 8, 
            DefCompletedBy = @Coder, 
            DefEndDate = convert(varchar(10), getdate(), 111),
            DefDays = (case when datediff(day, DefStartDate, getdate()) = 0 then 1 else datediff(day, DefStartDate, getdate()) end),
            DefNote = left((case when isnull(DefNote, '') = '' then '' else DefNote + '; ' end) + 'Completed by transcription', 255)
        where DefStatus not in (8, 11) 
--EN-00183
--            and HeaderDefID = @DefeciencyID 
            and DefID = @DefID 
            and DefCode = @DefCode

        if @Completed = '1' 
        begin
--EN-00183
--             if not exists (select * from Def_Activity where HeaderDefID = @DefeciencyID and DefStatus not in (8, 11))
--                 Update Def_SlipMain set DefMainStatus = 8 where DefeciencyID = @DefeciencyID   
            if not exists (select * from Def_Activity where DefID = @DefID and DefStatus not in (8, 11))
                Update Def_SlipMain set DefMainStatus = 8 where DefID = @DefID   
        end
        else
        begin
--EN-00183
--            set @occ = isnull((select max(DefOccurrence) from Def_Activity where HeaderDefID = @DefeciencyID), 1) + 1
--            if @Completed = '0' and (select top 1 DefMainStatus from Def_SlipMain where DefeciencyID = @DefeciencyID) = 8
            set @occ = isnull((select max(DefOccurrence) from Def_Activity where DefID = @DefID), 1) + 1
            if @Completed = '0' and (select top 1 DefMainStatus from Def_SlipMain where DefID = @DefID) = 8
                Update Def_SlipMain 
                set DefMainStatus = 7,
                    DefMainNote = left(( case when isnull(DefMainNote, '') = '' then '' else DefMainNote + '; ' end) + 'ReActived by Transcription(' + convert(varchar(12), getdate(), 111) + ')', 255)
                where DefID = @DefID and DefMainStatus = 8  
--EN-00183
--                where DefeciencyID = @DefeciencyID and DefMainStatus = 8  
            --dbo.Def_Activity
            insert dbo.Def_Activity(DefeciencyID, DefOccurrence, 
                DefStartDate, DefEndDate, DefDays, DefCompletedBy, 
                DefCode, DefCodeType, DefMessage, DefResident, DefStatus, 
                DefNote, HeaderDefID, DefID)
            select @DefeciencyID + @occ, @occ,
                convert(varchar(10), getdate(), 111), null, null,
                @Coder, @DefCode, 5,
--                (select top 1 code from DefLU_DeficiencyType where DisplayCode = 'S'),
                null, null,  7,
                'Create by transcription', @DefeciencyID, @DefID

        end

	declare @HID as int --NP-00025
	select @HID = HospitalID from U_Users where Code = @Coder

        insert into Def_UpdateHistory(DefeciencyID, HospitalID, Coder, Updated, UpdateType, DefID) 
        values(@DefeciencyID, @HID, @Coder, getdate(), 'Saved', @DefID)
    end           




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE  PROCEDURE [I_H_History] 
	@AppID as int,
	@RecordID as int,
	@Coder as int
AS 

declare @HID as int --NP-00025
select @HID = HospitalID from U_Users where Code = @Coder

insert into H_UpdateHistory (AppID, HospitalID, RecordID, Coder, Updated) Values (@AppID, @HID, @RecordID, @Coder, GetDate())



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [I_H_HospitalProfile_Message]
	(@Code 		[int],
	 @PrivacyMessage 		[varchar](8000)
	 )
AS 
    INSERT INTO [dbo].[H_HospitalProfile_Message](Code, PrivacyMessage) Values(@code , @PrivacyMessage)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_H_InstitutionProfile]
 	(@FakeAssocID			[int],
 	@Code		 		[int],
 	@DisplayCode 			[varchar](50),
 	@UserDescription		[varchar](255),
 	@DefaultDescription		[varchar](255),
 	@CIHIValue			[varchar](50),
 	@Validfrom			[datetime],
 	@ValidTo			[datetime],
 	@InterfaceIn			[varchar](50),
 	@AssociationID			[int],
 	@SiteNumber	 		[int],
	@ICDCMLive			[datetime],
	@ICDTLive			[datetime],
 	@CIHIYear			[varchar](10),
 	@CIHIPeriod	 		[int],
 	@RegionYear			[varchar](10),
 	@RegionPeriod 			[varchar](10),
 	@CostPerRIW	 		[varchar](10),
 	@AutoGenEncounterNum 	[int],
 	@StartEncounterNumber		[varchar](20),
 	@UseMentalHealth		[int],
 	@BOP_State1 			[int],
 	@BOP_Text1			[varchar](100),
 	@BOP_State2 			[int],
 	@BOP_Text2			[varchar](100),
 	@BOP_State3 			[int],
 	@BOP_Text3			[varchar](100),
 	@BOP_State4 			[int],
 	@BOP_Text4			[varchar](100),
 	@BOP_State5 			[int],
 	@BOP_Text5			[varchar](100),
 	@BOP_State6 			[int],
 	@BOP_Text6			[varchar](100),
 	@BOP_State7 			[int],
 	@BOP_Text7			[varchar](100),
 	@BOP_State8 			[int],
 	@BOP_Text8			[varchar](100),
 	@BOP_State9 			[int],
 	@BOP_Text9			[varchar](100),
 	@BOP_State10 			[int],
 	@BOP_Text10			[varchar](100),
 	@BOP_State11 			[int],
 	@BOP_Text11			[varchar](100),
 	@BOP_State12 			[int],
 	@BOP_Text12			[varchar](100),
 	@BOP_State13 			[int],
 	@BOP_Text13			[varchar](100),
 	@BOP_State14 			[int],
 	@BOP_Text14	 		[varchar](100),
 	@BOP_State15 			[int],
 	@BOP_Text15 			[varchar](100),
 	@BOP_State16 			[int],
 	@BOP_Text16			[varchar](100),
 	@BOP_State17 			[int],
 	@BOP_Text17	 		[varchar](100),	
 	@BOP_State18 			[int],
 	@BOP_Text18			[varchar](100),
 	@BOP_State19 			[int],
 	@BOP_Text19	 		[varchar](100),
	@UserEditsPath			[varchar](255),
	@MOHOfficeCode		[varchar](1),
	@GroupNumber			[varchar](4),
	@LocationCode			[varchar](4),
	@RefLabNumber 		[varchar](4), 
	@GSTNumber 			[varchar](25), 
	@PSTNumber 			[varchar](25), 
	@ContactID 			[varchar](35), 
	@Street 			[varchar](35), 
	@City 				[varchar](35), 
	@ProvinceNumber 		[varchar](2), 
	@PostalCode 			[varchar](7), 
	@WebAddress 			[varchar](60), 
	@EMail 			[varchar](60), 
	@PrimaryPhone 			[varchar](15),
	@LockDownDate 		[datetime],
	@OverlookCIHI 			[int],
	@UsetransferWorksheetData	[int],
	@NewChartPrefix 		[varchar](3),
	@CIHIDirectory 			[varchar](1000), 
	@NextAssessDay 		[int],
	@HospitalID			[int],
	@ProvdrRequestor 		[int],
	@LUText        			[varchar](255),
	@FacilitySequence 		[int],
    @RBillingDirectory  varchar(1000),
	@RehabSubDate		[datetime],
    @IsMultiSubmission  int,
	--, @PatientType 			[int] 
	@ShowSubmissionLog int,
	@PreferedLevelCode int,
	@CopyAssessment     int,
	@UseLite			int,
	@EnableCopyButton	int,
    @SubmitCJRR         int,
    @InstitutionType  varchar(1),
    @AutoProject012     int
)
AS 

--2.x-20480 Disble it
--if len(@CIHIValue) = 5 and len(isnull(@InstitutionType, '')) = 0
--	set @InstitutionType = isnull((select top 1 [InstitutionType] from LU_Institution_Type where [InstitutionNumber] = @CIHIValue), '')

--if @InstitutionType is null set @InstitutionType = ''

--EN - 00458 to make @IsMultiSubmission has value 1, 2
if @IsMultiSubmission > 2 and @AssociationID = 3 
	set @IsMultiSubmission = isnull((select top 1 code from LU_YeaBlankAlpha where code in (1, 2) and 
							CIHIValue in (select CIHIValue from LU_YeaBlankAlpha where code = @IsMultiSubmission)), 2)


select @Code = (select isnull(max(Code), 0) from H_InstitutionProfile) + 1
--select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end) 
 
 insert into [H_InstitutionProfile] 
 	([Code],
 	[DisplayCode],
 	[UserDescription],
 	[DefaultDescription],
 	[CIHIValue],
 	[Validfrom],
 	[ValidTo],
    	[LUText],
 	[InterfaceIn],
 	[AssociationID],
	--[PatientType], 
	[HospitalID],
 	[SiteNumber],
	[ICDCMLive],	 	
	[ICDTLive], 	
 	[CIHIYear],
 	[CIHIPeriod],
	[FacilitySequence],
 	[RegionYear],
 	[RegionPeriod],
 	[CostPerRIW],
 	[AutoGenEncounterNum],
 	[StartEncounterNumber],
 	[UseMentalHealthData],
	[UsetransferWorksheetData],
 	[BOP_State1],		
 	[BOP_Text1],
 	[BOP_State2],
 	[BOP_Text2],
 	[BOP_State3],
 	[BOP_Text3],
 	[BOP_State4],
 	[BOP_Text4],
 	[BOP_State5],	
 	[BOP_Text5],
 	[BOP_State6],
 	[BOP_Text6],
 	[BOP_State7],
 	[BOP_Text7],
 	[BOP_State8],
 	[BOP_Text8],
 	[BOP_State9],
 	[BOP_Text9],
 	[BOP_State10],
 	[BOP_Text10],
 	[BOP_State11],
 	[BOP_Text11],
 	[BOP_State12],
 	[BOP_Text12],
 	[BOP_State13],
 	[BOP_Text13],
 	[BOP_State14],
 	[BOP_Text14],
 	[BOP_State15],
 	[BOP_Text15],
 	[BOP_State16],
 	[BOP_Text16],
 	[BOP_State17],
 	[BOP_Text17],
 	[BOP_State18],
 	[BOP_Text18],
 	[BOP_State19],
 	[BOP_Text19], 
	[UserEditsPath],
	[MOHOfficeCode],
	[GroupNumber],
	[LocationCode],
	[RefLabNumber], 
	[GSTNumber], 
	[PSTNumber], 
	[ContactID], 
	[Street], 
	[City], 
	[ProvinceNumber], 
	[PostalCode], 
	[WebAddress], 
	[EMail], 
	[PrimaryPhone],
	[LockDownDate],
	[OverlookCIHI],
	[NewChartPrefix],
	[ProvdrRequestor],
	[NextAssessDay],
	[CIHIDirectory],
    [RBillingDirectory],
    [RehabSubDate],
    [IsMultiSubmission],
    [ShowSubmissionLog],
    [PreferedLevelCode],
    [CopyAssessment],
	[UseLite],
	[EnableCopyButton],
    [SubmitCJRR],
	[InstitutionType],
    [AutoProject012])
 values 
 	(@Code, 
 	@DisplayCode,
 	@UserDescription,
 	@DefaultDescription,
 	@CIHIValue,
 	@Validfrom,
 	@ValidTo,
    	@LUText,
 	@InterfaceIn,
 	@AssociationID,
	--@PatientType, 
	@HospitalID,
 	@SiteNumber,
	@ICDCMLive,
	@ICDTLive,
 	@CIHIYear,
 	@CIHIPeriod,
	@FacilitySequence,
 	@RegionYear,
 	@RegionPeriod,
 	@CostPerRIW,
 	@AutoGenEncounterNum,
 	@StartEncounterNumber,
 	@UseMentalHealth,
	@UsetransferWorksheetData,
 	@BOP_State1,		
 	@BOP_Text1,
 	@BOP_State2,
 	@BOP_Text2,
 	@BOP_State3,
 	@BOP_Text3,
 	@BOP_State4,
 	@BOP_Text4,
 	@BOP_State5,	
 	@BOP_Text5,
 	@BOP_State6,
 	@BOP_Text6,
 	@BOP_State7,
 	@BOP_Text7,
 	@BOP_State8,
 	@BOP_Text8,
 	@BOP_State9,
 	@BOP_Text9,
 	@BOP_State10,
 	@BOP_Text10,
 	@BOP_State11,
 	@BOP_Text11,
 	@BOP_State12,
 	@BOP_Text12,
 	@BOP_State13,
 	@BOP_Text13,
 	@BOP_State14,
 	@BOP_Text14,
 	@BOP_State15,
 	@BOP_Text15,
 	@BOP_State16,
 	@BOP_Text16,
 	@BOP_State17,
 	@BOP_Text17,
 	@BOP_State18,
 	@BOP_Text18,
 	@BOP_State19,
 	@BOP_Text19,
	@UserEditsPath,
	@MOHOfficeCode,
	@GroupNumber,
	@LocationCode,
	@RefLabNumber, 
	@GSTNumber, 
	@PSTNumber, 
	@ContactID, 
	@Street, 
	@City, 
	@ProvinceNumber, 
	@PostalCode, 
	@WebAddress, 
	@EMail, 
	@PrimaryPhone,
	@LockDownDate,
	@OverlookCIHI,
	@NewChartPrefix,
	@ProvdrRequestor,
	@NextAssessDay,
	@CIHIDirectory,
    @RBillingDirectory,
    @RehabSubDate,
    @IsMultiSubmission,
    @ShowSubmissionLog,
    @PreferedLevelCode,
    @CopyAssessment,
	@UseLite,
	@EnableCopyButton,
    @SubmitCJRR,
	@InstitutionType,
    @AutoProject012)
 	
 	-- Now update the Basic Options with the Real Institution System Code.
 	update [LU_BasicOption1] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
 	update [LU_BasicOption2] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
 	update [LU_BasicOption3] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
 	update [LU_BasicOption4] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
 	update [LU_BasicOption5] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
 	update [LU_BasicOption6] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
 	update [LU_BasicOption7] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
 	update [LU_BasicOption8] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
 	update [LU_BasicOption9] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
 	update [LU_BasicOption10] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
 	update [LU_BasicOption11] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
 	update [LU_BasicOption12] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
 	update [LU_BasicOption13] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
 	update [LU_BasicOption14] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
 	update [LU_BasicOption15] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
 	update [LU_BasicOption16] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
 	update [LU_BasicOption17] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
 	update [LU_BasicOption18] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
 	update [LU_BasicOption19] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)

--If there is a ROI Requestor
if @ProvdrRequestor > 0
    update [LU_ROI_Requesters] set [UserDescription] = @UserDescription, [Validfrom] = @Validfrom, [ValidTo] = @ValidTo, [Address] = @Street, [PostalCode] = @PostalCode, [Phone] = @PrimaryPhone, [City] = @City, [Province] = @ProvinceNumber, [HospitalID] = @HospitalID where Code = @ProvdrRequestor

if isnull(@HospitalID, 0) = 0 
	update H_InstitutionProfile set FacilityFileID = (select top 1 h.Code from H_HospitalProfile h) where Code = @Code
else
	update H_InstitutionProfile set FacilityFileID =  @HospitalID where Code = @Code


--NACRS Level code
declare @province varchar(10)
if isnull(@HospitalID, 0) = 0 
    set @province = isnull((select top 1 p.cihivalue from h_hospitalprofile h
                        inner join lu_province p on h.provincenumber = p.code), '')
else
    set @province = isnull((select top 1 p.cihivalue from h_hospitalprofile h
                        inner join lu_province p on h.provincenumber = p.code where h.code = @hospitalid), '')
if @AssociationID = 5
begin
    if @province = '5'
        update H_InstitutionProfile set LevelCode = '3', Level3Date = '2002/04/01' where code = @Code
    else if @province = '6'
        update H_InstitutionProfile set LevelCode = '3', Level3Date = '2004/04/01' where code = @Code
    else 
        update H_InstitutionProfile set LevelCode = '3', Level3Date = '2001/04/01' where code = @Code
end

return  @Code
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [I_H_RegionProfile_Message]
	(@Code 		[int],
	 @PrivacyMessage 		[varchar](8000)
	 )
AS 
    INSERT INTO [dbo].[H_RegionProfile_Message](Code, PrivacyMessage) Values(@code , @PrivacyMessage)
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [I_LLU_History] 
	@TableName as varchar(50),
	@RecordID as int,
	@Coder as int
AS 

declare @HID as int --NP-00025
select @HID = HospitalID from U_Users where Code = @Coder

insert into LLU_UpdateHistory (TableName, RecordID, Coder, Updated, HospitalID) Values (@TableName, @RecordID, @Coder, GetDate(), @HID)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_LLU_Provider_Schedule]
	(@ProviderID	[int],
	 @Occurrence	[int],
	 @SchedDay 	[int],
	 @StartTime 	[datetime],
	 @FinishTime 	[datetime],
	 @IntervalLen 	[int],
	 @BreakTime 	[datetime],
	 @BreakLen 	[int])

AS INSERT INTO [dbo].[LLU_Provider_Schedule] 
	 ([ProviderID], 
	 [Occurrence],
	 [SchedDay],
	 [StartTime],
	 [FinishTime],
	 [IntervalLen],
	 [BreakTime],
	 [BreakLen]) 
VALUES 
	(@ProviderID,
	 @Occurrence,
	 @SchedDay,
	 @StartTime,
	 @FinishTime,
	 @IntervalLen,
	 @BreakTime,
	 @BreakLen)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [I_LLU_Provider_Suspention]
	(@ProviderID		[int],
	 @Occurance	 	[int],
	 @DateFrom		[datetime],
	 @DateTo		[datetime],
	 @SuspensionType	[int])
AS 

INSERT INTO [LLU_Provider_Suspention] 
	 ([ProviderID],
	 [Occurance],
	 [DateFrom],
	 [DateTo],
	 [SuspensionType]) 
 
VALUES 
	(@ProviderID,
	 @Occurance,
	 @DateFrom,
	 @DateTo,
	 @SuspensionType)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE PROCEDURE [I_LLU_Provider_UnAvailable]
	(@ProviderID 	[int],
	 @Occurrence 	[int],
	 @UnAvailableType 	[int],
	 @DateFrom 	[datetime],
	 @DateTo 	[datetime])

AS 
INSERT INTO [dbo].[LLU_Provider_UnAvailable] 
	 ( [ProviderID],
	 [Occurrence],
	 [UnAvailableType],
	 [DateFrom],
	 [DateTo]) 
 
VALUES 
	( @ProviderID,
	 @Occurrence,
	 @UnAvailableType,
	 @DateFrom,
	 @DateTo)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [I_LLU_Provider_Vacation]
	(@ProviderID	 	[int],
	 @Occurance	 	[int],
	 @DateFrom		[datetime],
	 @DateTo		[datetime])

AS 

INSERT INTO [LLU_Provider_Vacation] 
	 ([ProviderID],
	 [Occurance],
	 [DateFrom],
	 [DateTo]) 
VALUES 
	(@ProviderID,
	 @Occurance,
	 @DateFrom,
	 @DateTo)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE PROCEDURE [I_LLU_ProviderPrivileges]
	(@ProviderID	 	[int],
	 @Occurrence	 	[int],
	 @DateFrom	 	[datetime],
	 @DateTo	 	[datetime],
	 @PrivilegeCode		[int],
	 @ReviewDate	 	[datetime],
	 @Comment	 	[varchar](255))

AS 
INSERT INTO [LLU_ProviderPrivileges] 
	 ([ProviderID],
	 [Occurrence],
	 [DateFrom],
	 [DateTo],
	 [PrivilegeCode],
	 [ReviewDate],
	 [Comment]) 
 
VALUES 
	(@ProviderID,
	 @Occurrence,
	 @DateFrom,
	 @DateTo,
	 @PrivilegeCode,
	 @ReviewDate,
	 @Comment)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE  PROCEDURE [I_LLU_ProviderServices]
	(@AssociationID		[int],
	 @Occurrence		[int],
	 @Code 		[int],
	 @Type 		[int],
	 @ValidFrom		[datetime],
	 @ValidTo 		[datetime])
AS 
if isnull(@AssociationID, 0) <> 0 and isnull(@Code, 0) <> 0
    INSERT INTO [LLU_ProviderServices] 
    	 ([Code],
    	 [Type],
    	 [ValidFrom],
    	 [ValidTo],
    	 [AssociationID],
 	 [Occurrence]) 
    VALUES 
    	(@Code,
    	 @Type,
    	 @ValidFrom,
    	 @ValidTo,
    	 @AssociationID,
	 @Occurrence)
--8889 - Added Occurrence

RETURN @Code

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [I_LLU_ProviderSpecialty]
	(@AssociationID		[int],
	 @Occurrence		[int],
	 @Code 		[int],
	 @Type 		[int],
	 @ValidFrom		[datetime],
	 @ValidTo 		[datetime])
AS 
if isnull(@AssociationID, 0) <> 0 and isnull(@Code, 0) <> 0 --PR - 05652
INSERT INTO [LLU_ProviderSpecialty] 
	 ([Code],
	 [Type],
	 [ValidFrom],
	 [ValidTo],
	 [AssociationID],
	 [Occurrence]) 
VALUES 
	(@Code,
	 @Type,
	 @ValidFrom,
	 @ValidTo,
	 @AssociationID,
	 @Occurrence)
--8889 - Added Occurrence

RETURN @Code

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE PROCEDURE [I_LLU_ReportDistribution]
   (@Code          [int],
    @Occurrence            [int],
    @Printers              [varchar](255),
    @EMailAddress          [varchar](255),
    @PrintCopy             [int],
    @FrequencySched        [int],
    @FrequencyDay  [int], 
    @FrequencyTime         [datetime])
AS 
INSERT INTO [dbo].[LLU_ReportDistribution] 
    ([Code],
    [Occurrence],
    [Printers],
    [EMailAddress],
    [PrintCopy],
    [FrequencySched], 
    [FrequencyDay], 
    [FrequencyTime]) 
 
VALUES 
   (@Code,
    @Occurrence,
    @Printers,
    @EMailAddress,
    @PrintCopy,
    @FrequencySched, 
    @FrequencyDay, 
    @FrequencyTime)

UPDATE [dbo].[LLU_ReportDistribution] SET LastPrintDate = GetDate() WHERE ISDATE(LastPrintDate) = 0 AND ISNULL(FrequencySched, 0) <> 0



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE    PROCEDURE [I_LU_AutoBorrower]
	@SearchString as VarChar(50),
	@HospitalID as int = 0
AS 

declare @Code as int
set nocount on

select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from LoanLU_Borrower)
insert into [LoanLU_Borrower] 
	 ([Code],
	 [DisplayCode],
	 [UserDescription],
	 [ValidFrom],
	 [ValidTo],
	 [HospitalID],
	 [InterfaceIn]) 
values
	(@Code,
	 @SearchString,
	 @SearchString,
	 '1950/01/01',
	 '2020/01/01',
	 @HospitalID,
	 @SearchString)

set nocount off
select [Code] as [ ], 
	[DisplayCode] as [Code Value],
	[UserDescription] as [Hospital Description], 
	convert (varchar(10), [ValidFrom], 111) as [Valid From],
	convert (varchar(10), [ValidTo], 111) as [Valid To] 				
from LoanLU_Borrower
where [Code] = @Code 

return 0


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE    PROCEDURE [I_LU_AutoRequester]
	@SearchString as VarChar(50),
	@HospitalID as int = 0
AS 

declare @Code as int
set nocount on

select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from LU_ROI_Requesters)
insert into [LU_ROI_Requesters] 
	 ([Code],
	 [DisplayCode],
	 [UserDescription],
	 [ValidFrom],
	 [ValidTo],
	 [HospitalID],
	 [InterfaceIn]) 
values
	(@Code,
	 @SearchString,
	 @SearchString,
	 '1950/01/01',
	 '2020/01/01',
	 @HospitalID,
	 @SearchString)

set nocount off
select [Code] as [ ],  
	[DisplayCode] as [Code Value],
	[UserDescription] as [Hospital Description], 
	convert (varchar(10), [ValidFrom], 111) as [Valid From],
	convert (varchar(10), [ValidTo], 111) as [Valid To] 				
from LU_ROI_Requesters
where [Code] = @Code

return 0


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


--exec I_LU_BasicOptions 'LU_BasicOption19', '0004', '0004', '7', '2845' 

CREATE     PROCEDURE [I_LU_BasicOptions]
	@SearchTable as VarChar(50),
	@SearchString as VarChar(50),
	@SearchCIHI as VarChar(50),
	@AssociationID as VarChar(10),
	@HospitalID as varchar(100) = '0'
AS 

	DECLARE @SQL VarChar(5000)
	DECLARE @SearchCode as VarChar(12)
	DECLARE @ValidFrom as VarChar(10)
	DECLARE @ValidTo as VarChar(10)

	Set @ValidFrom = convert(VarChar(10), (Select ValidFrom from H_InstitutionProfile where Code = @AssociationID), 111)
	Set @ValidTo = convert(VarChar(10), (Select ValidTo from H_InstitutionProfile where Code = @AssociationID), 111)

	Select @SQL = 'INSERT INTO ' + @SearchTable + ' (
			[Code], 
			[HospitalID],
			[DisplayCode], 
			[UserDescription], 
			[DefaultDescription], 
			[CIHIValue], 
			[ValidFrom], 
			[ValidTo], 
			[InterfaceIn], 
			[AssociationID]) 				
			SELECT (Case WHEN MAX(Code) + 1 > 100000 Then MAX(Code) + 1 Else 100000 END) , ' + 
				@HospitalID + ', 
				''' + @SearchString + ''', 
				''BOP' + right(@SearchTable, 2) + ' Value: ' + @SearchString + ''',
			 	''BOP' + right(@SearchTable, 2) + ' Value: ' + @SearchString + ''', 
				''' + @SearchCIHI + ''', 
				''' + @ValidFrom + ''', 
				''' + @ValidTo + ''', 
				''' + @SearchString + ''', 
				' + @AssociationID + 
			' FROM ' + @SearchTable


	--print '@SearchString: ' + @SearchString
	--print '@SearchCIHI: ' + @SearchCIHI
	Print @SQL
	EXECUTE (@SQL)

	SELECT @SQL = 'SELECT 
			[Code] AS [ ], 
			[DisplayCode] AS [Code Value],
			[UserDescription] AS [Hospital Description], 
			[DefaultDescription] AS [Default Description],
			[CIHIValue] AS [CIHI Value], 
			Convert(VarChar(10), [ValidFrom], 111) as [Valid From],
			Convert(VarChar(10), [ValidTo], 111) as [Valid To] 				
		FROM ' + @SearchTable + ' 
		WHERE [Code] = (SELECT MAX(Code) 
		FROM ' + @SearchTable + ') 
		AND AssociationID = ' + @AssociationID
	EXECUTE (@SQL)
	RETURN 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE     PROCEDURE [I_LU_Borrower]
	(@Code 		[int],
	@DisplayCode		[varchar](50),
	@BorrowerName	[varchar](50),
	@BorrowerAddress	[varchar](255),
	@BorrowerCity		[varchar](50),
	@Validfrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](50),
	@BorrowerProvince	[varchar](50),
	@BorrowerPostal	[varchar](50),
	@BorrowerContact	[varchar](50),
	@BorrowerPhone	[varchar](16),
	@Location		[int],
	@HospitalID		[int],
    @CLRequestPriority int,
    @LUText [varchar](255))
AS 

select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from LoanLU_Borrower)	
insert into LoanLU_Borrower(
		[Code], 
		[DisplayCode],
		[UserDescription],
		[BorrowerAddress],
		[BorrowerCity],		
		[Validfrom],		
		[ValidTo],		
        [LUText], 
		[InterfaceIn],	
		[HospitalID],
		[BorrowerProvince],
		[BorrowerPostal],
		[BorrowerContact],
		[BorrowerPhone],
		[PullLocation],
        CLRequestPriority)			
values(
		@Code, 
		@DisplayCode,
		@BorrowerName,
		@BorrowerAddress,
		@BorrowerCity,		
		@Validfrom,		
		@ValidTo,		
		@LUText,
        @InterfaceIn,	
		@HospitalID,
		@BorrowerProvince,
		@BorrowerPostal,
		@BorrowerContact,
		@BorrowerPhone,
		@Location,
        @CLRequestPriority)

return @Code



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_LU_CC_RT_PROTOCOL]
(   @Code 	[int],
    @DisplayCode 	[varchar](50),
    @UserDescription 	[varchar](255),
    @DefaultDescription 	[varchar](255),
    @CIHIValue 	[varchar](50),
    @Validfrom 	[datetime],
    @ValidTo 	[datetime],
    @InterfaceIn 	[varchar](50),
    @HospitalID 	[int],
    @LUText [varchar](255),
	@RT_CLINICAL_PRTC_GRP [varchar](50),
	@RT_CLINICAL_PRTC_SUB_GRP [varchar](50),
	@Modality [varchar](50),
	@INTENT [varchar](50),
	@DOSE_Gy [varchar](50),
	@DOSE_MIN [varchar](50),
	@DOSE_MAX [varchar](50),
	@FRACTIONATION [varchar](50),
	@NUMBER_OF_FRACTIONS_MIN [varchar](50),
	@NUMBER_OF_FRACTIONS_MAX [varchar](50),
	@DOSE_Gy_PER_FRACTION [varchar](50),
	@DOSE_PER_FRACTION_MIN [varchar](50),
	@DOSE_PER_FRACTION_MAX [varchar](50)
)

AS 
select @Code = (select (case when isnull(max(Code), 0) + 1 > 500000 then max(Code) + 1 else 500001 end)  from LU_CC_RT_PROTOCOL)	
insert into [dbo].LU_CC_RT_PROTOCOL 
(   [Code],
    [DisplayCode],
    [UserDescription],
    [DefaultDescription],
    [CIHIValue],
    [Validfrom],
    [ValidTo],
    [InterfaceIn],
    [HospitalID],
    [LUText], 
	[RT_CLINICAL_PRTC_GRP],
	[RT_CLINICAL_PRTC_SUB_GRP],
	[Modality],
	[INTENT],
	[DOSE_Gy],
	[DOSE_MIN],
	[DOSE_MAX],
	[FRACTIONATION],
	[NUMBER_OF_FRACTIONS_MIN],
	[NUMBER_OF_FRACTIONS_MAX],
	[DOSE_Gy_PER_FRACTION],
	[DOSE_PER_FRACTION_MIN],
	[DOSE_PER_FRACTION_MAX]
) 
values 
(   @Code,
    @DisplayCode,
    @UserDescription,
    @DefaultDescription,
    @CIHIValue,
    @Validfrom,
    @ValidTo,
    @InterfaceIn,
    @HospitalID,
    @LUText,
	@RT_CLINICAL_PRTC_GRP,
	@RT_CLINICAL_PRTC_SUB_GRP,
	@Modality,
	@INTENT,
	@DOSE_Gy,
	@DOSE_MIN,
	@DOSE_MAX,
	@FRACTIONATION,
	@NUMBER_OF_FRACTIONS_MIN,
	@NUMBER_OF_FRACTIONS_MAX,
	@DOSE_Gy_PER_FRACTION,
	@DOSE_PER_FRACTION_MIN,
	@DOSE_PER_FRACTION_MAX
)

	return @Code


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_LU_CCM_BodyRegion]
	(@Code 	[int],
	 @DisplayCode 	[varchar](50),
	 @UserDescription 	[varchar](255),
	 @DefaultDescription 	[varchar](255),
	 @CIHIValue 	[varchar](50),
	 @Validfrom 	[datetime],
	 @ValidTo 	[datetime],
	 @InterfaceIn 	[varchar](50),
	 @HospitalID 	[int],
	 @LUText [varchar](255),
	 @BodyGroup 	[varchar](50) 
)

AS 
select @Code = (select (case when isnull(max(Code), 0) + 1 > 500000 then max(Code) + 1 else 500001 end)  from LU_CCM_BodyRegion)	
insert into [dbo].[LU_CCM_BodyRegion] 
	 ( [Code],
	 [DisplayCode],
	 [UserDescription],
	 [DefaultDescription],
	 [CIHIValue],
	 [Validfrom],
	 [ValidTo],
	 [InterfaceIn],
	 [HospitalID],
   	 [LUText], 
	 [BodyGroup]) 
 
values 
	( @Code,
	 @DisplayCode,
	 @UserDescription,
	 @DefaultDescription,
	 @CIHIValue,
	 @Validfrom,
	 @ValidTo,
	 @InterfaceIn,
	 @HospitalID,
   	 @LUText,
	 @BodyGroup)

	return @Code


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_LU_CCM_NHPIP_Code]
(   @Code 	[int],
    @DisplayCode 	[varchar](50),
    @UserDescription 	[varchar](255),
    @DefaultDescription 	[varchar](255),
    @CIHIValue 	[varchar](50),
    @Validfrom 	[datetime],
    @ValidTo 	[datetime],
    @InterfaceIn 	[varchar](50),
    @HospitalID 	[int],
    @LUText [varchar](255),
    @NHPIP_ACT_TYPE varchar(10),
    @NHPIP_DURATION_UNIT int,
    @NHPIP_MAX_DOES_PF varchar(10),
    @NHPIP_USAGE_CD varchar(10),
    @NHPIP_ACTIVE_STATUS  varchar(10)
)

AS 
select @Code = (select (case when isnull(max(Code), 0) + 1 > 500000 then max(Code) + 1 else 500001 end)  from LU_CCM_NHPIP_Code)	
insert into [dbo].LU_CCM_NHPIP_Code 
(   [Code],
    [DisplayCode],
    [UserDescription],
    [DefaultDescription],
    [CIHIValue],
    [Validfrom],
    [ValidTo],
    [InterfaceIn],
    [HospitalID],
    [LUText], 
    NHPIP_ACT_TYPE,
    NHPIP_DURATION_UNIT,
    NHPIP_MAX_DOES_PF,
    NHPIP_USAGE_CD,
    NHPIP_ACTIVE_STATUS
) 
values 
(   @Code,
    @DisplayCode,
    @UserDescription,
    @DefaultDescription,
    @CIHIValue,
    @Validfrom,
    @ValidTo,
    @InterfaceIn,
    @HospitalID,
    @LUText,
    @NHPIP_ACT_TYPE,
    @NHPIP_DURATION_UNIT,
    @NHPIP_MAX_DOES_PF,
    @NHPIP_USAGE_CD,
    @NHPIP_ACTIVE_STATUS
)

	return @Code

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE      PROCEDURE [I_LU_ChartLocation]
	(@Code 		[int],
	@DisplayCode		[varchar](50),
	@UserDescription	[varchar](255),
	@Validfrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](50),
	@LoanDays		[int],
	@LoanHospital		[int],
	@LoanInOut		[int],
	@HospitalID		[int],
    @CLRequestPriority [int],
    @LUText varchar(255),
	@LocationType		[int])
AS 

select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from LoanLU_Location)	
insert into LoanLU_Location (
		[Code], 
		[DisplayCode], 
		[UserDescription], 
		[Validfrom], 
		[ValidTo], 
        [CLRequestPriority], 
		[InterfaceIn],
		[HospitalID],
		[LoanDays],
		[LoanHospital],
		[InHospital],
        [LUText],
		[LocationType]) 				
values(
		@Code, 
		@DisplayCode,
		@UserDescription, 
		@Validfrom,
		@ValidTo,
		@CLRequestPriority,
        @InterfaceIn,
		@HospitalID,
		@LoanDays,
		@LoanHospital, 
		@LoanInOut,
        @LUText,
	@LocationType)

return @Code

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [I_LU_CJRR_StickerCode]
	(@TableName             [varchar](50),
	 @Code 					[varchar](50),
	 @DisplayCode 			[varchar](50),
	 @UserDescription 		[varchar](255),
	 @DefaultDescription	[varchar](255),
	 @CIHIValue 			[varchar](50),
	 @ValidFrom 			[varchar](50),
	 @ValidTo 				[varchar](50),
	 @InterfaceIn 			[varchar](50),
	 @HospitalID 			[varchar](50),
     @LUText				[varchar](255),
	 @Manufacturer 			[varchar](50),
	 @OtherManufacturer		[varchar](100),
	 @CatalogueNumber		[varchar](50),
	 @LotNumber				[varchar](50)
)
AS 

   declare @SQL varchar(2000)
   
   set @Displaycode = replace(@DisplayCode, '''',  '''''')
   set @UserDescription = replace(@UserDescription, '''',  '''''')
   set @DefaultDescription = replace(@DefaultDescription, '''',  '''''')
   set @InterfaceIn = replace(@InterfaceIn, '''',  '''''')

   set @OtherManufacturer = replace(@OtherManufacturer, '''',  '''''')
   set @CatalogueNumber = replace(@CatalogueNumber, '''',  '''''')
   set @LotNumber = replace(@LotNumber, '''',  '''''')
   
   select @SQL = 'insert into ' + @TableName + '([Code], 
                   [DisplayCode], [UserDescription], [DefaultDescription], [CIHIValue], [Validfrom], [ValidTo], [LUText], [InterfaceIn], [HospitalID], [Manufacturer], [OtherManufacturer], [CatalogueNumber], [LotNumber])                            
                   select (case when max(Code) + 1 > 100000 then max(Code) + 1 else 100000 end) , ''' +
                   @DisplayCode + ''', ''' + @UserDescription + ''', ''' + @DefaultDescription + ''', ''' + @CIHIValue + ''', ''' + @Validfrom + ''', ''' + @ValidTo + ''' , ''' + @LUText + ''' , ''' + @InterfaceIn + ''', ' + @HospitalID + ', ' + @Manufacturer + ', ''' + @OtherManufacturer + ''', ''' + @CatalogueNumber + ''', ''' + @LotNumber + '''' + 
                 'from ' + @TableName
   execute (@SQL)
   select @SQL = 'select isnull(max(Code), 0) from ' + @TableName
   execute (@SQL)

   return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [I_LU_ClinicalPathway]
	(@Code 	[int],
	 @DisplayCode 	[varchar](50),
	 @UserDescription 	[varchar](255),
	 @DefaultDescription 	[varchar](255),
	 @CIHIValue 	[varchar](50),
	 @Validfrom 	[datetime],
	 @ValidTo 	[datetime],
	 @InterfaceIn 	[varchar](50),
	 @HospitalID 	[int],
	 @ClinicalLOS 	[varchar](50),
     	 @LUText [varchar](255))

AS 
select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from LU_ClinicalPathway)	
insert into [dbo].[LU_ClinicalPathway] 
	 ( [Code],
	 [DisplayCode],
	 [UserDescription],
	 [DefaultDescription],
	 [CIHIValue],
	 [Validfrom],
	 [ValidTo],
     	 [LUText], 
	 [InterfaceIn],
	 [HospitalID],
	 [ClinicalLOS]) 
 
values 
	( @Code,
	 @DisplayCode,
	 @UserDescription,
	 @DefaultDescription,
	 @CIHIValue,
	 @Validfrom,
	 @ValidTo,
     	 @LUText,
	 @InterfaceIn,
	 @HospitalID,
	 @ClinicalLOS)

	return @Code


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



-- This is called by the Save Method of the Deficiency Code Look Up Maint Sub-Form
CREATE   PROCEDURE [I_LU_DeficiencyCode] 
	(@Code			as integer,
	@DisplayCode 		as varchar(50),
	@UserDescription 	as varchar(255),
	@Validfrom		AS DATETIME,
	@ValidTo		AS DATETIME,
	@InterfaceIn		as varchar(50),
	@AssociationID		as integer,
	@LinkDefCode		as integer, 
	@DefCountDays	as integer,
	@HospitalID		as integer,
    @LUText        as varchar(255))
AS 
	select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end) from DefLU_DeficiencyCode)	
	insert into DefLU_DeficiencyCode (
		[Code], 
		[DisplayCode], 
		[UserDescription], 
		[Validfrom], 
		[ValidTo], 
		[InterfaceIn],
		[AssociationID],
		[HospitalID],
		[DefCountDays],
		[LinkDefCode],
        [LUText])
	values (
		@Code,
		@DisplayCode,
		@UserDescription, 
		@Validfrom,
		@ValidTo, 
		@InterfaceIn,
		@AssociationID,
		@HospitalID,
		@DefCountDays,
		@LinkDefCode,
        @LUText)
	
	return @Code


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE  PROCEDURE [I_LU_DeficiencyStatus]
	(@Code			[int],
	 @DisplayCode	 	[varchar](50),
	 @UserDescription 	[varchar](255),
	 @Validfrom	 	[datetime],
	 @ValidTo		[datetime],
	 @InterfaceIn	 	[varchar](50),
	 @NumberDays	 	[int],
	 @SuspensionType 	[int],
	 @LetterNameE	 	[varchar](50),
	 @LetterNameF	 	[varchar](50),
	 @LetterNameS	 	[varchar](50),
	 @HospitalID		[int],
     @LUText [varchar](255))

AS 
select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from DefLU_ChartStatus)	
insert into [dbo].[DefLU_ChartStatus] 
	 ([Code],
	 [DisplayCode],
	 [UserDescription],
	 [Validfrom],
	 [ValidTo],
     [LUText], 
	 [InterfaceIn],
	 [HospitalID],
	 [NumberDays],
	 [SuspensionType],
	 [LetterNameE],
	 [LetterNameF],
	 [LetterNameS]) 
 
values 
	(@Code,
	 @DisplayCode,
	 @UserDescription,
	 @Validfrom,
	 @ValidTo,
     @LUText,
	 @InterfaceIn,
	 @HospitalID,
	 @NumberDays,
	 @SuspensionType,
	 @LetterNameE,
	 @LetterNameF,
	 @LetterNameS)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



-- This is called by the Save Method of the Direct Billing Items Look Up Maint Sub-Form
CREATE   PROCEDURE [I_LU_DirectBillFeeCodes]
	(@Code 		[int],
	 @DisplayCode		[varchar](50),
	 @UserDescription	[varchar](255),
	 @DefaultDescription	[varchar](255),
	 @CIHIValue		[varchar](50),
	 @Validfrom 		[datetime],
	 @ValidTo 		[datetime],
	 @InterfaceIn	 	[varchar](50),
	 @ItemPrice		[money],
	 @ItemTaxType		[int],
	 @HospitalID		[int],
     @LUText [varchar](255))
AS 
select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from LU_DirectBillFeeCodes)	
insert into LU_DirectBillFeeCodes (
	[Code], 
	[DisplayCode], 
	[UserDescription], 
	[DefaultDescription], 
	[CIHIValue],	
	[Validfrom], 
	[ValidTo], 
	[LUText], 
    [InterfaceIn],
	[HospitalID],
	[ItemPrice],
	[ItemTaxType]) 				

values(
	@Code,
	@DisplayCode,
	@UserDescription,
	@DefaultDescription,
	@CIHIValue, 
	@Validfrom,
	@ValidTo,
    @LUText,
	@InterfaceIn,
	@HospitalID,
	 @ItemPrice,
	 @ItemTaxType)

return @Code


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE    PROCEDURE [I_LU_General]
   (@TableName             as varchar(50),
   @Code                   as varchar(50),
   @DisplayCode            as varchar(50),
   @UserDescription        as varchar(250),
   @DefaultDescription     as varchar(250),
   @CIHIValue              as varchar(50),
   @Validfrom              as varchar(10),
   @ValidTo                as varchar(10), 
   @InterfaceIn            as varchar(50),
   @HospitalID             as varchar(100),
   @LUText                 as varchar(255))
AS 

   declare @SQL varchar(2000)
   declare @CodeHolding as varchar(50)
   
   set @Displaycode = replace(@DisplayCode, '''',  '''''')
   set @UserDescription = replace(@UserDescription, '''',  '''''')
   set @DefaultDescription = replace(@DefaultDescription, '''',  '''''')
   set @InterfaceIn = replace(@InterfaceIn, '''',  '''''')
   
   if isnumeric(@TableName) <> 0
   begin
           insert into LU_CodeFile ([LookUpID], [Code], 
                           [DisplayCode], [UserDescription], [DefaultDescription], [CIHIValue], [Validfrom], [ValidTo], [LUText], [InterfaceIn], [HospitalID])                            
                           select @TableName, (case when max(Code) + 1 > 500000 then max(Code) + 1 else 500000 end) , 
                           @DisplayCode, @UserDescription, @DefaultDescription, @CIHIValue, @Validfrom, @ValidTo, @LUText, @InterfaceIn, @HospitalID from LU_CodeFile
           select isnull(max(Code), 0) from LU_CodeFile
           --execute (@SQL)
   end

   else
   begin
           select @SQL = 'insert into ' + @TableName + '([Code], 
                           [DisplayCode], [UserDescription], [DefaultDescription], [CIHIValue], [Validfrom], [ValidTo], [LUText], [InterfaceIn], [HospitalID])                            
                           select (case when max(Code) + 1 > 100000 then max(Code) + 1 else 100000 end) , ''' +
                           @DisplayCode + ''', ''' + @UserDescription + ''', ''' + @DefaultDescription + ''', ''' + @CIHIValue + ''', ''' + @Validfrom + ''', ''' + @ValidTo + ''' , ''' + @LUText + ''' , ''' + @InterfaceIn + ''', ' + @HospitalID + 'from ' + @TableName
           execute (@SQL)
           select @SQL = 'select isnull(max(Code), 0) from ' + @TableName
           execute (@SQL)
   end
   return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE    PROCEDURE [I_LU_General_NoCIHI]
	(@TableName 		as varchar(50),
	@Code			as varchar(50),
	@DisplayCode 		as varchar(50),
	@UserDescription 	as varchar(250),
	@Validfrom		as varchar(10),
	@ValidTo		as varchar(10), 
	@InterfaceIn		as varchar(50),
	@HospitalID		as varchar(100),
    @LUText         as varchar(255))
AS 

	declare @SQL varchar(500)
	declare @CodeHolding as varchar(50)

   	set @Displaycode = replace(@DisplayCode, '''',  '''''') 
   	set @UserDescription = replace(@UserDescription, '''',  '''''')
   	set @InterfaceIn = replace(@InterfaceIn, '''',  '''''') --RM [2007/05/29]

	set nocount on	
	select @SQL = 'insert into ' + @TableName + '([Code], 
			[DisplayCode], [UserDescription],
			[Validfrom], [ValidTo], [LUText], [InterfaceIn], [HospitalID]) 				
			select (case when max(Code) + 1 > 100000 then max(Code) + 1 else 100000 end) , ''' +
			@DisplayCode + ''', ''' + @UserDescription + ''', ''' +
			@Validfrom + ''', ''' + @ValidTo + ''' , ''' + @LUText + ''' , ''' + @InterfaceIn + ''', ' + @HospitalID + 'from ' + @TableName
	execute (@SQL)
	select @SQL = 'select isnull(max(Code), 0) from ' + @TableName

	set nocount off
	execute (@SQL)
	return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_LU_GeneralAssoc]
	(@TableName 		as varchar(50),
	@AssocCode		as varchar(50),
	@Code			as varchar(50),
	@DisplayCode 		as varchar(50),
	@UserDescription 	as varchar(250),
	@DefaultDescription	as varchar(250),
	@CIHIValue		as varchar(50),
	@Validfrom		as varchar(10),
	@ValidTo		as varchar(10), 
	@InterfaceIn		as varchar(50),
	@HospitalID		as varchar(100),
    @LUText         as varchar(255))
AS 

	declare @SQL varchar(1000)
	declare @CodeHolding as varchar(50)
	
   	set @Displaycode = replace(@DisplayCode, '''',  '''''')
   	set @UserDescription = replace(@UserDescription, '''',  '''''')
   	set @DefaultDescription = replace(@DefaultDescription, '''',  '''''')
   	set @InterfaceIn = replace(@InterfaceIn, '''',  '''''')

	select @SQL = 'insert into ' + @TableName + '
			([Code], 
			[AssociationID],
			[DisplayCode], 
			[UserDescription], 
			[DefaultDescription], 
			[CIHIValue],	 
			[Validfrom], 
			[ValidTo], 
           			 [LUText], 
			[InterfaceIn],
			[HospitalID]) 				
			select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end) , ''' +
			@AssocCode + ''', ''' + 
			@DisplayCode + ''', ''' + 
			@UserDescription + ''', ''' +
			@DefaultDescription + ''', ''' + 
			@CIHIValue + ''', ''' +
			@Validfrom + ''', ''' + 
			@ValidTo + ''' , ''' + 
            			@LUText + ''' , ''' + 
			@InterfaceIn + ''', ' + 
			@HospitalID + 
			' from ' + @TableName
	execute (@SQL)
	print @SQL

	select @SQL = 'select max(Code) from ' + @TableName
	execute (@SQL)
	--return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE   PROCEDURE [I_LU_ICD10Diag]
	(@Code 		[int],
	@DisplayCode		[varchar](50),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@CIHIValue		[varchar](20),
	@Validfrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](50),
	@IsMain		[varchar](1),
	@ICDGender		[varchar](1),
	@AgeLow		[int],
	@AgeHigh		[int],
	@ICD9			[varchar](10),
	@ICD9CM		[varchar](10),
	@ICDNotes		[varchar](255),
	@ProjectLink 		[int],
	@ICDLink 		[int],
    @LUText        [varchar](255))
AS 

select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from ICD_DiagFile10)	
insert into ICD_DiagFile10 (
		[Code], 
		[DisplayCode], 
		[UserDescription], 
		[DefaultDescription], 
		[CIHIValue],	 
		[Validfrom], 
		[ValidTo], 
        [LUText], 
		[InterfaceIn],
		[MRDxFlag],
		[DiagnosisGender],
		[AgeLow],
		[AgeHigh],
		[ICD9],
		[ICD9CM],
		[ICDNotes],
		[ProjectLink],
	  	[ICDLink]) 				
values(
		@Code, 
		@DisplayCode,
		@UserDescription, 
		@DefaultDescription,
		@CIHIValue,
		@Validfrom,
		@ValidTo,
        @LUText,
        @InterfaceIn,
		@IsMain,
		@ICDGender,
		@AgeLow,
		@AgeHigh,
		@ICD9,
		@ICD9CM,
		@ICDNotes,
		@ProjectLink,
	  	@ICDLink)

update NU_IntCodes set Validfrom = @Validfrom, ValidTo = @ValidTo, ICDNotes = @ICDNotes where CIHIValue =  @CIHIValue

return @Code



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_LU_ICD10DiagCCRS]
	(@Code 		[int],
	@DisplayCode		[varchar](50),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@ShortDescription	[varchar](255),
	@CIHIValue		[varchar](20),
	@Validfrom 		[datetime],
	@ValidTo 		[datetime],
	@ICDGender		[varchar](1),
	@AgeLow		[int],
	@AgeHigh		[int],
	@InterfaceIn	 	[varchar](50),
    @LUText        [varchar](255))
AS 

select @Code = (select (case when isnull(max(Code), 0) + 1 > 500000 then max(Code) + 1 else 500001 end)  from ICD_DiagFileMDS)	
insert into ICD_DiagFileMDS (
		[Code], 
		[DisplayCode], 
		[UserDescription], 
		[DefaultDescription], 
		[ShortDescription],
		[CIHIValue],	 
		[Validfrom], 
		[ValidTo], 
		[DiagnosisGender],
		[AgeLow],
		[AgeHigh],
		[InterfaceIn],
        [LUText] 
) 				
values(
		@Code, 
		@DisplayCode,
		@UserDescription, 
		@DefaultDescription,
		@ShortDescription,
		@CIHIValue,
		@Validfrom,
		@ValidTo,
		@ICDGender,
		@AgeLow,
		@AgeHigh,
        @InterfaceIn,
        @LUText
)
return @Code
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE   PROCEDURE [I_LU_ICD10Interv]
	(@Code 		[int],
	@DisplayCode		[varchar](50),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@CIHIValue		[varchar](20),
	@Validfrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](50),
	@ICDGender		[varchar](1),
	@AgeLow		[int],
	@AgeHigh		[int],
	@ICD9			[varchar](10),
	@ICD9CM		[varchar](10),
	@ICDNotes		[varchar](255),
	@ProjectLink 		[int],
	@ICDLink		[int],
    @LUText [varchar](255))
AS 

select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from ICD_ProcFile10)	
insert into ICD_ProcFile10 (
		[Code], 
		[DisplayCode], 
		[UserDescription], 
		[DefaultDescription], 
		[CIHIValue],	 
		[Validfrom], 
		[ValidTo], 
        [LUText], 
		[InterfaceIn],
		[DiagnosisGender],
		[AgeLow],
		[AgeHigh],
		[ICD9],
		[ICD9CM],
		[ICDNotes],
		[ProjectLink],
		[ICDLink]) 				
values(
		@Code, 
		@DisplayCode,
		@UserDescription, 
		@DefaultDescription,
		@CIHIValue,
		@Validfrom,
		@ValidTo,
        @LUText,
		@InterfaceIn,
		@ICDGender,
		@AgeLow,
		@AgeHigh,
		@ICD9,
		@ICD9CM,
		@ICDNotes,
		@ProjectLink,
		@ICDLink)

update NU_IntCodes set Validfrom = @Validfrom, ValidTo = @ValidTo, ICDNotes = @ICDNotes where CIHIValue =  @CIHIValue

return @Code



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE   PROCEDURE [I_LU_ICD9CMDiag]
	(@Code 		[int],
	@DisplayCode		[varchar](20),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@CIHIValue		[varchar](20),
	@Validfrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](20),
	@IsMain		[varchar](1),
	@ICDGender		[varchar](1),
	@AgeLow		[int],
	@AgeHigh		[int],
    @LUText [varchar](255))
AS 

select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from ICD_DiagFile9cm)	
insert into ICD_DiagFile9cm (
		[Code], 
		[DisplayCode], 
		[UserDescription], 
		[DefaultDescription], 
		[CIHIValue],	 
		[Validfrom], 
		[ValidTo], 
        [LUText], 
		[InterfaceIn],
		[MRDxFlag],
		[DiagnosisGender],
		[AgeLow],
		[AgeHigh]) 				
values(
		@Code, 
		@DisplayCode,
		@UserDescription, 
		@DefaultDescription,
		@CIHIValue,
		@Validfrom,
		@ValidTo,
        @LUText,
		@InterfaceIn,
		@IsMain,
		@ICDGender,
		@AgeLow,
		@AgeHigh)

return @Code



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE   PROCEDURE [I_LU_ICD9CMInterv]
	(@Code 		[int],
	@DisplayCode		[varchar](20),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@CIHIValue		[varchar](20),
	@Validfrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](20),
	@ICDGender		[varchar](1),
	@AgeLow		[int],
	@AgeHigh		[int],
    @LUText [varchar](255))
AS 

select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from ICD_ProcFile9CM)	
insert into ICD_ProcFile9CM (
		[Code], 
		[DisplayCode], 
		[UserDescription], 
		[DefaultDescription], 
		[CIHIValue],	 
		[Validfrom], 
		[ValidTo], 
        [LUText], 
		[InterfaceIn],
		[DiagnosisGender],
		[AgeLow],
		[AgeHigh]) 				
values(
		@Code, 
		@DisplayCode,
		@UserDescription, 
		@DefaultDescription,
		@CIHIValue,
		@Validfrom,
		@ValidTo,
		@LUText,
        @InterfaceIn,
		@ICDGender,
		@AgeLow,
		@AgeHigh)

return @Code


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE   PROCEDURE [I_LU_ICD9Diag]
	(@Code 		[int],
	@DisplayCode		[varchar](20),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@CIHIValue		[varchar](20),
	@Validfrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](20),
	@IsMain		[varchar](1),
	@ICDGender		[varchar](1),
	@AgeLow		[int],
	@AgeHigh		[int],
    @LUText [varchar](255))
AS 

select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from ICD_DiagFile9)	
insert into ICD_DiagFile9 (
		[Code], 
		[DisplayCode], 
		[UserDescription], 
		[DefaultDescription], 
		[CIHIValue],	 
		[Validfrom], 
		[ValidTo], 
        [LUText], 
		[InterfaceIn],
		[MRDxFlag],
		[DiagnosisGender],
		[AgeLow],
		[AgeHigh]) 				
values(
		@Code, 
		@DisplayCode,
		@UserDescription, 
		@DefaultDescription,
		@CIHIValue,
		@Validfrom,
		@ValidTo,
        @LUText, 
		@InterfaceIn,
		@IsMain,
		@ICDGender,
		@AgeLow,
		@AgeHigh)

return @Code


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE   PROCEDURE [I_LU_ICD9Interv]
	(@Code 		[int],
	@DisplayCode		[varchar](20),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@CIHIValue		[varchar](20),
	@Validfrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](20),
	@ICDGender		[varchar](1),
	@AgeLow		[int],
	@AgeHigh		[int],
    @LUText [varchar](255))
AS 

select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from ICD_ProcFile9)	
insert into ICD_ProcFile9 (
		[Code], 
		[DisplayCode], 
		[UserDescription], 
		[DefaultDescription], 
		[CIHIValue],	 
		[Validfrom], 
		[ValidTo], 
        [LUText], 
		[InterfaceIn],
		[DiagnosisGender],
		[AgeLow],
		[AgeHigh]) 				
values(
		@Code, 
		@DisplayCode,
		@UserDescription, 
		@DefaultDescription,
		@CIHIValue,
		@Validfrom,
		@ValidTo,
        @LUText,
        @InterfaceIn,
		@ICDGender,
		@AgeLow,
		@AgeHigh)

return @Code


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



-- This is called by the Save Method of the Institution 10 Look Up Maint Sub-Form
CREATE   PROCEDURE [I_LU_Institution10]
	(@Code 		[int],
	 @DisplayCode		[varchar](50),
	 @UserDescription	[varchar](255),
	 @DefaultDescription	[varchar](255),
	 @CIHIValue		[varchar](12),
	 @Validfrom 		[datetime],
	 @ValidTo 		[datetime],
	 @InterfaceIn	 	[varchar](50),
	 @InstCareType		[varchar](1),
	 @HospitalType		[varchar](2),
	 @HospitalID		[int],
     @LUText [varchar](255),
     @InstitutionType varchar(10)
     )
AS 
    declare @IsAcute int
	
    if isnull(@InstitutionType, '') = ''
    	set @InstitutionType = isnull((select top 1 InstitutionType from LU_Institution_Type where InstitutionNumber = @CIHIValue), '')
	
    if @InstitutionType = '1'
        set @IsAcute = 1
    else if @HospitalType = 'AT'
        set @IsAcute = 1
    --else if isnull(@HospitalType, '') = '' and substring(@CIHIValue, 2, 1) = '0'    
    --    set @IsAcute = 1
    else
        set @IsAcute = 0

select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from LU_Institution_10)	
insert into LU_Institution_10 (
	[Code], 
	[DisplayCode], 
	[UserDescription], 
	[DefaultDescription], 
	[CIHIValue],	
	[Validfrom], 
	[ValidTo], 
    [LUText], 
	[InterfaceIn],
	[HospitalID],
	[InstCareType],
	[HospitalType],
	[InstitutionType],
	[IsAcute]) 				

values(
	@Code,
	@DisplayCode,
	@UserDescription,
	@DefaultDescription,
	@CIHIValue, 
	@Validfrom,
	@ValidTo,
    @LUText,
	@InterfaceIn,
	@HospitalID,
	@InstCareType,
	@HospitalType,
	@InstitutionType,
	@IsAcute)

return @Code


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE      PROCEDURE [I_LU_LoanLocationType]
	(@Code 		[int],
	@DisplayCode		[varchar](50),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@CIHIValue		[varchar](50),
	@Validfrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](50),
	@HospitalID		[int],
    	@LUText 		[varchar](255),
	@LoanDays		[int])
AS 

select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from LoanLU_LocationType)	
insert into LoanLU_LocationType (
		[Code], 
		[DisplayCode], 
		[UserDescription], 
		[DefaultDescription], 
		[CIHIValue], 
		[Validfrom], 
		[ValidTo], 
		[InterfaceIn],
		[HospitalID],
        		[LUText],
		[LoanDays]) 				
values(
		@Code, 
		@DisplayCode,
		@UserDescription, 
		@DefaultDescription, 
		@CIHIValue, 
		@Validfrom,
		@ValidTo,
        		@InterfaceIn,
		@HospitalID,
        		@LUText,
		@LoanDays)
return @Code

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE    PROCEDURE [I_LU_MDAS_Group]
   (@Code                   as int,
   @DisplayCode            as varchar(50),
   @UserDescription        as varchar(250),
   @DefaultDescription     as varchar(250),
   @CIHIValue              as varchar(50),
   @Validfrom              as datetime,
   @ValidTo                as datetime, 
   @InterfaceIn            as varchar(12),
   @HospitalID             as int,
   @LUText                 as varchar(255),
   @SensitivityLevel	   as int)
AS 

   set @Displaycode = replace(@DisplayCode, '''',  '''''')
   set @UserDescription = replace(@UserDescription, '''',  '''''')
   set @DefaultDescription = replace(@DefaultDescription, '''',  '''''')
   
   insert into LU_CodeFile ([LookUpID], [Code], [DisplayCode], [UserDescription], [DefaultDescription], [CIHIValue], [Validfrom], [ValidTo], [LUText], [InterfaceIn], [HospitalID])                            
   	select '71', (case when max(Code) + 1 > 500000 then max(Code) + 1 else 500000 end) , 
                   @DisplayCode, @UserDescription, @DefaultDescription, @CIHIValue, @Validfrom, @ValidTo, @LUText, @InterfaceIn, @HospitalID from LU_CodeFile
   select @Code = isnull(max(Code), 0) from LU_CodeFile
	
   insert into LLU_MDAS_Group_Sensitivity (LUCode, SensitivityLevel) values (@Code, @SensitivityLevel)

   return @Code

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_LU_MISCode]
	(@Code 	[int],
	 @DisplayCode 	[varchar](12),
	 @UserDescription 	[varchar](255),
	 @DefaultDescription 	[varchar](255),
	 @CIHIValue 	[varchar](12),
	 @Validfrom 	[datetime],
	 @ValidTo 	[datetime],
	 @InterfaceIn 	[varchar](12),
	 @HospitalID 	[int],
	 @AMCareType 	[int],
	 @LUText [varchar](255),
	 @AmCareTypeCode [varchar](10),     --ED - 02297
	 @AmCareGroup 	[varchar](50) ,
     @ClinicLite    [int]
)

AS 
--PR - 06065
if isnull(@AMCareType, 0) = 0 and isnull(@AmCareGroup, '') <> ''
    set @AMCareType = (case @AmCareGroup when 'ED' then 15644
                                         when 'DS' then 15643
                                         when 'CL' then 15642
                                         --DI, OT
                                         else 15641 end)

select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from LU_MISCode)	
insert into [dbo].[LU_MISCode] 
	 ( [Code],
	 [DisplayCode],
	 [UserDescription],
	 [DefaultDescription],
	 [CIHIValue],
	 [Validfrom],
	 [ValidTo],
     [LUText], 
	 [InterfaceIn],
	 [HospitalID],
	 [AMCareType],
	 [AmCareTypeCode],
	 [AmCareGroup],
     [ClinicLite]) 
 
values 
	( @Code,
	 @DisplayCode,
	 @UserDescription,
	 @DefaultDescription,
	 @CIHIValue,
	 @Validfrom,
	 @ValidTo,
     @LUText,
	 @InterfaceIn,
	 @HospitalID,
	 @AMCareType,
	 @AmCareTypeCode, 
	 @AmCareGroup,
     @ClinicLite)

	return @Code

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_LU_OR_GeneralLink]
(
    @TableName              as varchar(100),
    @Code                   as varchar(50),
    @DisplayCode            as varchar(50),
    @UserDescription        as varchar(250),
    @DefaultDescription     as varchar(250),
    @CIHIValue              as varchar(50),
    @Validfrom              as varchar(10),
    @ValidTo                as varchar(10), 
    @InterfaceIn            as varchar(50),
    @HospitalID             as varchar(100),
    @LUText                 as varchar(255),
	@AssociationID          as int
)
AS 
    
    declare @SQL varchar(2000)
    declare @CodeHolding as varchar(50)
   
    set @Displaycode = replace(@DisplayCode, '''',  '''''')
    set @UserDescription = replace(@UserDescription, '''',  '''''')
    set @DefaultDescription = replace(@DefaultDescription, '''',  '''''')
    set @InterfaceIn = replace(@InterfaceIn, '''',  '''''')
    if @AssociationID is null set @AssociationID = 0

    select @SQL = 'insert into ' + @TableName + '([Code], 
                   [DisplayCode], [UserDescription], [DefaultDescription], [CIHIValue], [Validfrom], [ValidTo], [LUText], [InterfaceIn], [HospitalID], [AssociationID])                            
                   select (case when max(Code) + 1 > 100000 then max(Code) + 1 else 100000 end) , ''' +
                   @DisplayCode + ''', ''' + @UserDescription + ''', ''' + @DefaultDescription + ''', ''' + @CIHIValue + ''', ''' + @Validfrom + ''', ''' + @ValidTo + ''' , ''' + @LUText + ''' , ''' + @InterfaceIn + ''', ' + @HospitalID + ', ' + cast(@AssociationID as varchar(10)) + ' from ' + @TableName
    execute (@SQL)
    select @SQL = 'select isnull(max(Code), 0) from ' + @TableName
    execute (@SQL)

    return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE    PROCEDURE [I_LU_PatientService]
	(@Code 		[int],
	@DisplayCode		[varchar](50),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@CIHIValue		[varchar](20),
	@Validfrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](50),
	@ProjectLink 		[int],
	@HospitalID		[int],
    @LUText [varchar](255))
AS 

select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from LU_PatientService)	
insert into LU_PatientService (
		[Code], 
		[DisplayCode], 
		[UserDescription], 
		[DefaultDescription], 
		[CIHIValue],	 
		[Validfrom], 
		[ValidTo], 
        [LUText], 
		[InterfaceIn],
		[HospitalID],
		[ProjectLink]) 				
values(
		@Code, 
		@DisplayCode,
		@UserDescription, 
		@DefaultDescription,
		@CIHIValue,
		@Validfrom,
		@ValidTo,
        @LUText,
		@InterfaceIn,
	 	@HospitalID,
		@ProjectLink)

return @Code


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_LU_PostalCode]
	(@Code			as varchar(50),
	@DisplayCode 		as varchar(50),
	@UserDescription 	as varchar(250),
	@DefaultDescription	as varchar(250),
	@CIHIValue		as varchar(50),
	@Validfrom		as varchar(10),
	@ValidTo		as varchar(10), 
	@InterfaceIn		as varchar(50),
	@LinkCode 		as varchar(12),
	@HospitalID		as varchar(100),
    @LUText         as varchar(255))
AS 

	declare @SQL varchar(5000) --PR-01624
	declare @CodeHolding as varchar(50)

   	set @Displaycode = replace(@DisplayCode, '''',  '''''')
   	set @CIHIValue = upper(replace(replace(@CIHIValue, '''',  ''), ' ', '')) --ED - 01714
   	set @InterfaceIn = replace(@InterfaceIn, '''',  '''''')
	set @UserDescription = replace(@UserDescription, '''', '''''') --PR-01277
	set @DefaultDescription = replace(@DefaultDescription, '''', '''''') --PR-01277
	
	select @SQL = 'insert into LU_PostalCode (
				[Code], 
				[DisplayCode], 
				[UserDescription], 
				[DefaultDescription], 
				[CIHIValue],	 
				[Validfrom], 
				[ValidTo], 
                			[LUText], 
				[InterfaceIn],
				[LinkCode],
				[HospitalID]) 				
			select (case when max(Code) + 1 > 100000 then max(Code) + 1 else 100000 end) , ''' +
			@DisplayCode + ''', ''' + 
			@UserDescription + ''', ''' +
			@DefaultDescription + ''', ''' + 
			@CIHIValue + ''', ''' +
			@Validfrom + ''', ''' + 
			@ValidTo + ''' , ''' + 
            			@LUText + ''' , ''' + 
			@InterfaceIn + ''', ''' +
			@LinkCode + ''', ' +
			@HospitalID + '
			from LU_PostalCode'

	execute (@SQL)

	select @SQL = 'select max(Code) from LU_PostalCode'
	execute (@SQL)

	return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE     PROCEDURE [I_LU_Project]
	(@FakeAssocID		[int],
	@Code			[int],
	@DisplayCode 		[varchar](50),
	@UserDescription 	[varchar](250),
	@DefaultDescription	[varchar](250),
	@CIHIValue		[varchar](50),
	@Validfrom		[datetime],
	@ValidTo		[datetime], 
	@InterfaceIn		[varchar](50),
	@QuestionState1 	[int],
	@Question1		[varchar](100),
	@QuestionState2 	[int],
	@Question2		[varchar](100),
	@QuestionState3 	[int],
	@Question3		[varchar](100),
	@QuestionState4 	[int],
	@Question4		[varchar](100),
	@QuestionState5 	[int],
	@Question5		[varchar](100),
	@QuestionState6 	[int],
	@Question6		[varchar](100),
	@QuestionState7 	[int],
	@Question7		[varchar](100),
	@QuestionState8 	[int],
	@Question8		[varchar](100),
	@QuestionState9 	[int],
	@Question9		[varchar](100),
	@QuestionState10 	[int],
	@Question10		[varchar](100),
	@QuestionState11 	[int],
	@Question11		[varchar](100),
	@QuestionState12 	[int],
	@Question12		[varchar](100),
	@QuestionState13 	[int],
	@Question13		[varchar](100),
	@QuestionState14 	[int],
	@Question14	 	[varchar](100),
	@QuestionState15 	[int],
	@Question15 		[varchar](100),
	@QuestionState16 	[int],
	@Question16		[varchar](100),
	@QuestionState17 	[int],
	@Question17	 	[varchar](100),
	@QuestionDefault1 	[int], 
	@QuestionDefault2 	[int], 
	@QuestionDefault3 	[int], 
	@QuestionDefault4 	[int], 
	@QuestionDefault5 	[int], 
	@QuestionDefault6 	[int], 
	@QuestionDefault7 	[int], 
	@QuestionDefault8 	[int], 
	@QuestionDefault9 	[int], 
	@QuestionDefault10 	[int], 
	@QuestionDefault11 	[int], 
	@QuestionDefault12 	[int], 
	@QuestionDefault13 	[int], 
	@QuestionDefault14 	[varchar](10), 
	@QuestionDefault15 	[varchar](10), 
	@QuestionDefault16 	[varchar](10), 
	@QuestionDefault17 	[varchar](10),

	@HospitalID		[int],
   	@LUText [varchar](255),
   	
	@Question18	 	[varchar](100),
	@QuestionState18 	[int],
	@QuestionDefault18 	[varchar](10),
	@Question19	 	[varchar](100),
	@QuestionState19 	[int],
	@QuestionDefault19 	[varchar](10),
	@Question20	 	[varchar](100),
	@QuestionState20 	[int],
	@QuestionDefault20 	[varchar](10),
	@Question21	 	[varchar](100),
	@QuestionState21 	[int],
	@QuestionDefault21 	[varchar](10),
	@Question22	 	[varchar](100),
	@QuestionState22 	[int],
	@QuestionDefault22 	[varchar](10),
	@Question23	 	[varchar](100),
	@QuestionState23 	[int],
	@QuestionDefault23 	[varchar](10),
	@Question24	 	[varchar](100),
	@QuestionState24 	[int],
	@QuestionDefault24 	[varchar](10)
)
AS 

select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from LU_Project)

insert into LU_Project
	([Code], 
	[DisplayCode], 
	[UserDescription], 
	[DefaultDescription], 
	[CIHIValue],	 
	[Validfrom], 
	[ValidTo],
    	[LUText], 
	[InterfaceIn],
	[HospitalID],
	[QuestionState1],
	[Question1],
	[QuestionState2],
	[Question2],
	[QuestionState3],
	[Question3],
	[QuestionState4],
	[Question4],
	[QuestionState5],
	[Question5],
	[QuestionState6],
	[Question6],
	[QuestionState7],
	[Question7],
	[QuestionState8],
	[Question8],
	[QuestionState9],
	[Question9],
	[QuestionState10],
	[Question10],
	[QuestionState11],
	[Question11],
	[QuestionState12],
	[Question12],
	[QuestionState13],
	[Question13],
	[QuestionState14],
	[Question14],
	[QuestionState15],
	[Question15],
	[QuestionState16],
	[Question16],
	[QuestionState17],
	[Question17],
	[QuestionDefault1], 
	[QuestionDefault2], 
	[QuestionDefault3], 
	[QuestionDefault4], 
	[QuestionDefault5], 
	[QuestionDefault6], 
	[QuestionDefault7], 
	[QuestionDefault8], 
	[QuestionDefault9], 
	[QuestionDefault10], 
	[QuestionDefault11], 
	[QuestionDefault12], 
	[QuestionDefault13], 
	[QuestionDefault14], 
	[QuestionDefault15], 
	[QuestionDefault16], 
	[QuestionDefault17]) 				
values
	(@Code,
	@DisplayCode,
	@UserDescription,
	@DefaultDescription,
	@CIHIValue, 
	@Validfrom,
	@ValidTo, 
    	@LUText, 
	@InterfaceIn,
	@HospitalID,
	@QuestionState1,
	 @Question1,
	 @QuestionState2,
	 @Question2,
	 @QuestionState3,
	 @Question3,
	 @QuestionState4,
	 @Question4,
	 @QuestionState5,
	 @Question5,
	 @QuestionState6,
	 @Question6,
	 @QuestionState7,
	 @Question7,
	 @QuestionState8,
	 @Question8,
	 @QuestionState9,
	 @Question9,
	 @QuestionState10,
	 @Question10,
	 @QuestionState11,
	 @Question11,
	 @QuestionState12,
	 @Question12,
	 @QuestionState13,
	 @Question13,
	 @QuestionState14,
	 @Question14,
	 @QuestionState15,
	 @Question15,
	 @QuestionState16,
	 @Question16,
	 @QuestionState17,
	 @Question17,
	 @QuestionDefault1, 
	 @QuestionDefault2, 
	 @QuestionDefault3, 
	 @QuestionDefault4, 
	 @QuestionDefault5, 
	 @QuestionDefault6, 
	 @QuestionDefault7, 
	 @QuestionDefault8, 
	 @QuestionDefault9, 
	 @QuestionDefault10, 
	 @QuestionDefault11, 
	 @QuestionDefault12, 
	 @QuestionDefault13, 
	 @QuestionDefault14, 
	 @QuestionDefault15, 
	 @QuestionDefault16, 
	 @QuestionDefault17)

-- Now update the Questions with the Real Project System Code.
update [LU_ProjectQuestion1] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
update [LU_ProjectQuestion2] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
update [LU_ProjectQuestion3] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
update [LU_ProjectQuestion4] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
update [LU_ProjectQuestion5] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
update [LU_ProjectQuestion6] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
update [LU_ProjectQuestion7] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
update [LU_ProjectQuestion8] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
update [LU_ProjectQuestion9] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
update [LU_ProjectQuestion10] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
update [LU_ProjectQuestion11] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
update [LU_ProjectQuestion12] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
update [LU_ProjectQuestion13] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)

return @Code


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE      PROCEDURE [I_LU_Provider]
	(@FakeAssocID		[int],
	@Code 			[int],
	@DisplayCode		[varchar](50),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@CIHIValue		[varchar](20),
	@Validfrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](50),
	@ProvdrAddress		[varchar](255),
	@ProvdrCity		[varchar](35),
	@ProvdrProvince		[varchar](35),
	@ProvdrPostal		[varchar](7),
	@ProvdrHomePhone	[varchar](15),
	@ProvdrCellPhone	[varchar](15),
	@ProvdrOfficePhone	[varchar](15),
	@ProvdrHospitalPhone	[varchar](15),
	@ProvdrFax		[varchar](15),
	@ProvdrEMail		[varchar](50),
	@ProvdrResident		[integer],
	@ProvdrmaxLetter	[integer],
	@ProvdrCredentials	[varchar](255),
	@ProvdrTitle		[varchar](255),
	@ProvdrState		[varchar](10),
	@ProvdrLanguage		[int],
	@ProvdrBorrower		[int],
	@ProvdrChiefOfStaff	[int],
	@ProvdrLastVisitDate	[datetime],
	@ProvdrMISCode		[int],
	@TransInitials		[varchar](10),
	@ProvdrBillSpecialty	[int],
	@MoHCode 		[varchar](50), 
	@ProgramCode 		[int],
	@HospitalID		[int],
	@ProvdrRequestor 	[int],
	@MinDeficiency		[int],
	@ProvdrAuthent 		[int],
    	@LUText 		[varchar](255),
	@InterfaceIn2	 	[varchar](50),
	@InterfaceIn3	 	[varchar](50),
	@PrefReciept		[int],
	@ProvdrSurName 		[varchar](50), 
	@ProvdrFirstName 	[varchar](50), 
	@ProvdrMiddleName 	[varchar](50), 
	@HCPProgramCode 	[int], 
	@HCPStatus 		[int],
	@CJRRSurgeonID		[varchar](50))
AS 
declare @BCount AS int

set @Displaycode = replace(@displaycode, '''''',  '''') --PR-02563
set @UserDescription = replace(@UserDescription, '''''',  '''') --PR-02563

select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from LU_Provider)	
insert into LU_Provider (
		[Code], 
		[DisplayCode], 
		[UserDescription], 
		[DefaultDescription], 
		[CIHIValue],	 
		[Validfrom], 
		[ValidTo], 
        	[LUText], 
		[InterfaceIn], 
		[InterfaceIn2], 
		[InterfaceIn3], 
	 	[HospitalID],
		[PrefReciept],
		[ProvdrAddress],
		[ProvdrCity],
		[ProvdrProvince],
		[ProvdrPostal],
		[ProvdrHomePhone],
		[ProvdrCellPhone],
		[ProvdrOfficePhone],
		[ProvdrHospitalPhone],
		[ProvdrFax],
		[ProvdrEMail],
		[ProvdrResident],
		[ProvdrmaxLetter],
		[ProvdrCredentials],
		[ProvdrTitle],
		[ProvdrState],
		[ProvdrLanguage],
		[ProvdrBorrower],
		[ProvdrChiefOfStaff],
		[ProvdrLastVisitDate],
		[ProvdrMISCode],
		[TransInitials],
		[ProvdrBillSpecialty],
		[MoHCode], 
		[ProgramCode],
		[ProvdrRequestor], 
	 	[MinDeficiency],
	 	[ProvdrAuthent],
		[ProvdrSurName],
		[ProvdrFirstName],
		[ProvdrMiddleName],
		[HCPProgramCode],
		[HCPStatus],
		[CJRRSurgeonID])
values(
		@Code, 
		@DisplayCode,
		@UserDescription, 
		@DefaultDescription,
		@CIHIValue,
		@Validfrom,
		@ValidTo,
        	@LUText, 
		@InterfaceIn,
		@InterfaceIn2,
		@InterfaceIn3,
		@HospitalID, 
		@PrefReciept,
		@ProvdrAddress,
		@ProvdrCity,
		@ProvdrProvince,
		@ProvdrPostal,
		@ProvdrHomePhone,
		@ProvdrCellPhone,
		@ProvdrOfficePhone,
		@ProvdrHospitalPhone,
		@ProvdrFax,
		@ProvdrEMail,
		@ProvdrResident,
		@ProvdrmaxLetter,
		@ProvdrCredentials,
		@ProvdrTitle,		
		@ProvdrState,
		@ProvdrLanguage,
		@ProvdrBorrower,
		@ProvdrChiefOfStaff,
		@ProvdrLastVisitDate,
		@ProvdrMISCode,
		@TransInitials,
		@ProvdrBillSpecialty,
		@MoHCode, 
		@ProgramCode,
		@ProvdrRequestor, 
	 	@MinDeficiency,
		@ProvdrAuthent,
		@ProvdrSurName,
		@ProvdrFirstName, 
		@ProvdrMiddleName,
		@HCPProgramCode,
		@HCPStatus,
		@CJRRSurgeonID)

-- Now update the Provider Services & Specialty Provider System Code.
--8889
--update [LLU_ProviderServices] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
--update [LLU_ProviderSpecialty] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)

--If there is a Borrower Code
if @ProvdrBorrower > 0
	update [LoanLU_Borrower] set [UserDescription] = @UserDescription, [BorrowerAddress] = @ProvdrAddress, [BorrowerCity] = @ProvdrCity, [Validfrom] = @Validfrom, [ValidTo] = @ValidTo, [BorrowerProvince] = @ProvdrProvince, [BorrowerPostal] = @ProvdrPostal, [BorrowerPhone] = @ProvdrOfficePhone, [HospitalID] = @HospitalID where ([Code] = @ProvdrBorrower)

--If there is a ROI Requestor
if @ProvdrRequestor > 0
	update [LU_ROI_Requesters] set [UserDescription] = @UserDescription, [Validfrom] = @Validfrom, [ValidTo] = @ValidTo,  [Address] = @ProvdrAddress, [PostalCode] = @ProvdrPostal, [Phone] = @ProvdrOfficePhone, [Fax] = @ProvdrFax, [City] = @ProvdrCity, [HospitalID] = @HospitalID where Code = @ProvdrRequestor -- [Province] = @ProvdrProvince, 

return @Code
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE  PROCEDURE [I_LU_Reports]
	(@Code			[int],
	 @UserDescription 	[varchar](50),
	 @ReportPath		[varchar](255),
	 @AppID		[int],
	 @RoleID		[int],
	 @ValidFrom		[datetime],
	 @ValidTo	 	[datetime],
	 @EMailFormat 		[int],
	 @HospitalID		[int],
	 @InstitutionNumber 	[int], 
	 @AutoLaunch 		[int],
	 @AutoLaunchLoad	[int],
	 @DistributeKey 		[int],
	 @IsInterface 		[int], 
	 @InterfaceID 		[int])
AS 
SELECT @Code = (SELECT (CASE WHEN ISNULL(MAX(Code), 0) + 1 > 100000 THEN MAX(Code) + 1 ELSE 100000 END)  FROM LU_Reports)	
INSERT INTO [dbo].[LU_Reports] 
	 ([Code],
	 [UserDescription],
	 [ReportPath],
	 [AppID],
	 [RoleID],
	 [ValidFrom],
	 [ValidTo],
	 [HospitalID],
	 [EMailFormat],
	 [InstitutionNumber],
	 [AutoLaunch],
	 [AutoLaunchLoad],
	 [DistributeKey],
	 [IsInterface], 
	 [InterfaceID]) 
VALUES 
	(@Code,
	 @UserDescription,
	 @ReportPath,
	 @AppID,
	 @RoleID,
	 @ValidFrom,
	 @ValidTo,
	 @HospitalID,
	 @EMailFormat,
	 @InstitutionNumber, 
	 @AutoLaunch,
	 @AutoLaunchLoad,
	 @DistributeKey,
	 @IsInterface, 
	 @InterfaceID)

RETURN @Code

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE     PROCEDURE [I_LU_RequestPriority]
	(
    @Code           as int,
	@DisplayCode 		AS VARCHAR(50),
	@UserDescription 	AS VARCHAR(250),
	@ValidFrom		AS VARCHAR(10),
	@ValidTo		AS VARCHAR(10), 
	@InterfaceIn		AS VARCHAR(50),
	@HospitalID		as varchar(100),
    @Rate   as int)
AS 
    SELECT @Code = (SELECT (Case WHEN isnull(MAX(Code), 0) + 1 > 500000 Then MAX(Code) + 1 Else 500000 END)  FROM LoanLU_RequestPriority)	

    INSERT INTO LoanLU_RequestPriority ([Code], 
			[DisplayCode], [UserDescription],
			[ValidFrom], [ValidTo], [InterfaceIn], [HospitalID], [PriorityRate]) 				
	Values( @Code, 
			@DisplayCode, 
            @UserDescription,
			@ValidFrom,
            @ValidTo, 
            @InterfaceIn, 
            @HospitalID,
            @Rate)
	RETURN @Code



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE    PROCEDURE [I_LU_ResidenceCode]
	(@Code 		[int],
	@DisplayCode		[varchar](50),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@CIHIValue		[varchar](20),
	@Validfrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](50),	
	@HospitalID		[int],
	@LUText 		[varchar](255),
	@ProvinceCode 		[int],
	@RegionCode		[int])
AS 

select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from LU_ResidenceCode)	
insert into LU_ResidenceCode (
		[Code], 
		[DisplayCode], 
		[UserDescription], 
		[DefaultDescription], 
		[CIHIValue],	 
		[Validfrom], 
		[ValidTo], 
        	[LUText], 
		[InterfaceIn],
		[HospitalID],
		[ProvinceCode],
		[RegionCode]) 				
values(
		@Code, 
		@DisplayCode,
		@UserDescription, 
		@DefaultDescription,
		@CIHIValue,
		@Validfrom,
		@ValidTo,
        	@LUText,
		@InterfaceIn,
	 	@HospitalID,
		@ProvinceCode,
		@RegionCode)
return @Code


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE  PROCEDURE [I_LU_ROI_AuthTypes]
	(@Code		 	[int],
	 @DisplayCode	 	[varchar](50),
	 @UserDescription 	[varchar](255),
	 @Validfrom		[datetime],
	 @ValidTo	 	[datetime],
	 @ReportPath		[varchar](255),
	 @InterfaceIn	 	[varchar](50),
	 @HospitalID		[int],
     @LUText         [varchar](255))
AS 
select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from LU_ROI_AuthorizationType)
insert into [dbo].[LU_ROI_AuthorizationType] 
	 ([Code],
	 [DisplayCode],
	 [UserDescription],
	 [ReportPath],
	 [Validfrom],
	 [ValidTo],
     [LUText], 
	 [InterfaceIn],
	 [HospitalID])  
values 
	(@Code,
	 @DisplayCode,
	 @UserDescription,
	 @ReportPath,
	 @Validfrom,
	 @ValidTo,
     @LUText, 
	 @InterfaceIn,
	 @HospitalID)
return @Code


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE  PROCEDURE [I_LU_ROI_Contacts]
	(@AssociationID	 	[int],
	 @Code		 	[int],
	 @DisplayCode	 	[varchar](50),
	 @UserDescription 	[varchar](255),
	 @Validfrom	 	[datetime],
	 @ValidTo		[datetime],
	 @Phone		[varchar](20),
	 @PhoneExt	 	[varchar](10),
	 @Fax		 	[varchar](20),
	 @InterfaceIn	 	[varchar](50),
	 @EMail		[varchar](50),
	 @HospitalID		[int],
     	 @LUText 		[varchar](255))
AS 

select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from LU_ROI_Contacts)
insert into [dbo].[LU_ROI_Contacts] 
	 ([Code],
	 [DisplayCode],
	 [UserDescription],
	 [Validfrom],
	 [ValidTo],
     	 [LUText], 
	 [EMail],
	 [Phone],
	 [PhoneExt],
	 [Fax],
	 [AssociationID],
	 [InterfaceIn],
	 [HospitalID]) 
values 
	(@Code,
	 @DisplayCode,
	 @UserDescription,
	 @Validfrom,
	 @ValidTo,
     	 @LUText,
	 @EMail,
	 @Phone,
	 @PhoneExt,
	 @Fax,
	 @AssociationID,
	 @InterfaceIn,
	 @HospitalID)

return @Code

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [I_LU_ROI_Requesters]
	(@FakeAssocID		[int],
	 @Code 		[int],
	 @DisplayCode		[varchar](50),
	 @UserDescription	[varchar](255),
	 @Validfrom	 	[datetime],
	 @ValidTo		[datetime],
	 @Address		[varchar](255),
	 @PostalCode	 	[varchar](20),
	 @BillingAddress	 	[varchar](255),
	 @BillingPostalCode	[varchar](20),
	 @Phone		[varchar](20),
	 @Fax		 	[varchar](20),
	 @maxTaxLevel 	[int],
	 @RequesterType 	[int],
	 @InterfaceIn	 	[varchar](50),
	 @CostLevel		[int],
	 @City 			[varchar](30), 
	 @Province 		[int], 
	 @Country 		[int],
	 @BillingCity 		[varchar](30), 
	 @BillingProvince 	[int], 
	 @BillingCountry 	[int],
	 @HospitalID		[int],
     @LUText 		[varchar](255),
	 @PhoneExt		[varchar](6))
AS 
select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from LU_ROI_Requesters)
insert into [dbo].[LU_ROI_Requesters] 
	 ([Code],
	 [DisplayCode],
	 [UserDescription],
	 [Validfrom],
	 [ValidTo],
     	 [LUText], 
	 [HospitalID],
	 [Address],
	 [City],
	 [Province], 
	 [Country],
	 [PostalCode],
	 [BillingAddress],
	 [BillingCity], 
	 [BillingProvince], 
	 [BillingCountry], 
	 [BillingPostalCode],
	 [Phone],
	 [PhoneExt],
	 [Fax],
	 [RequesterType],
	 [CostLevel],
	 [maxTaxLevel],
	 [InterfaceIn]) 
 
values 
	(@Code,
	 @DisplayCode,
	 @UserDescription,
	 @Validfrom,
	 @ValidTo,
     	 @LUText,
	 @HospitalID,
	 @Address,
	 @City,
	 @Province, 
	 @Country,
	 @PostalCode,
	 @BillingAddress,
	 @BillingCity, 
	 @BillingProvince, 
	 @BillingCountry, 
	 @BillingPostalCode,
	 @Phone,
	 @PhoneExt,
	 @Fax,
	 @RequesterType,
	 @CostLevel, 
	 @maxTaxLevel,
	 @InterfaceIn)

-- Now update the Contacts with the Real System Code.
update [LU_ROI_Contacts] set AssociationID = @Code where ([AssociationID] = @FakeAssocID)
return @Code
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE  PROCEDURE [I_LU_ROI_RequestTypes]
	(@Code		 	[int],
	 @DisplayCode	 	[varchar](50),
	 @UserDescription 	[varchar](255),
	 @Validfrom		[datetime],
	 @ValidTo	 	[datetime],
	 @Chargeable		[int],
	 @AuthRequired		[int],
	 @InterfaceIn	 	[varchar](50),
	 @HospitalID		[int],
     @LUText [varchar](255))
AS 
select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from LU_ROI_RequestTypes)
insert into [dbo].[LU_ROI_RequestTypes] 
	 ([Code],
	 [DisplayCode],
	 [UserDescription],
	 [Chargeable],
	 [AuthRequired],
	 [Validfrom],
	 [ValidTo],
     [LUText], 
	 [InterfaceIn],
	 [HospitalID])  
values 
	(@Code,
	 @DisplayCode,
	 @UserDescription,
	 @Chargeable,
	 @AuthRequired,
	 @Validfrom,
	 @ValidTo,
     @LUText,
	 @InterfaceIn,
	 @HospitalID)
return @Code


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE  PROCEDURE [I_LU_ROI_SentItemTypes]
	(@Code		 	[int],
	 @DisplayCode	 	[varchar](50),
	 @UserDescription 	[varchar](255),
	 @Validfrom		[datetime],
	 @ValidTo	 	[datetime],
	 @ROIPrice		[money],
	 @TaxType	 	[tinyint],
	 @InterfaceIn	 	[varchar](50),
	 @ROIPrice2		[money],
	 @ROIPrice3		[money],
	 @ROIPrice4		[money],
	 @ROIPrice5		[money],
	 @HospitalID		[int],
     @LUText [varchar](255))
AS 
select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from LU_ROI_SentItemTypes)
insert into [dbo].[LU_ROI_SentItemTypes] 
	 ([Code],
	 [DisplayCode],
	 [UserDescription],
	 [ROIPrice],
	 [ROIPrice2],
	 [ROIPrice3],
	 [ROIPrice4],
	 [ROIPrice5],
	 [TaxType],
	 [Validfrom],
	 [ValidTo],
     [LUText],
	 [InterfaceIn],
	 [HospitalID])  
values 
	(@Code,
	 @DisplayCode,
	 @UserDescription,
	 @ROIPrice,
	 @ROIPrice2,
	 @ROIPrice3,
	 @ROIPrice4,
	 @ROIPrice5,
	 @TaxType,
	 @Validfrom,
	 @ValidTo,
     @LUText, 
	 @InterfaceIn,
	 @HospitalID)
return @Code


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE     PROCEDURE [I_LU_TR_DocumentType]
	(@Code			[int],
	@DisplayCode 		[varchar](50),
	@UserDescription 	[varchar](250),
	@DefaultDescription	[varchar](250),
	@CIHIValue		[varchar](50),
	@Validfrom		[datetime],
	@ValidTo		[datetime], 
	@InterfaceIn		[varchar](12),
	@TemplatePath		[varchar](255),
	@HospitalID		[int],
    @DefCode int,
    @LUText [varchar](255))
AS 
select @Code = (select (case when isnull(max(Code), 0) + 1 > 100000 then max(Code) + 1 else 100000 end)  from LU_TranscriptDocument)

insert into LU_TranscriptDocument
	([Code], 
	[DisplayCode], 
	[UserDescription], 
	[DefaultDescription], 
	[CIHIValue],	 
	[Validfrom], 
	[ValidTo],
    [LUText], 
	[InterfaceIn],
	[HospitalID],
	[TemplatePath],
    DefCode) 				
values
	(@Code,
	@DisplayCode,
	@UserDescription,
	@DefaultDescription,
	@CIHIValue, 
	@Validfrom,
	@ValidTo, 
    @LUText, 
	@InterfaceIn,
	@HospitalID,
	@TemplatePath,
    @DefCode)

return @Code



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE  PROCEDURE [I_M_DBULogging]
(
    @UpdateID int,
    @TicketID int,
    @UpdateName varchar(50),
    @UpdateDescription varchar(255),
    @UserID int,
    @StartTime datetime,
    @EndTime datetime,
    @CreationDate datetime,
    @MachineID varchar(50),
    @HardwareInfo varchar(255),
    @MultiRun bit,
    @ExecPath varchar(255),
    @WRVersion varchar(10),
    @DBSideOnly varchar(10),
    @HospitalID	int
)
AS 

if @StartTime is null set @StartTime = getdate()
if @EndTime is null set @EndTime = getdate()
    
    
delete M_DBULogging where UpdateID = @UpdateID and isnull(multirun, 0) = 0

insert into M_DBULogging 
( 
    UpdateID,
    TicketID,
    UpdateName,
    UpdateDescription,
    UserID,
    StartTime,
    EndTime,
    CreationDate,
    MachineID,
    HardwareInfo,
    MultiRun,
    ExecPath,
    WRVersion,
    DBSideOnly,
    HospitalID
) 
values 
(
    @UpdateID,
    @TicketID,
    @UpdateName,
    @UpdateDescription,
    @UserID,
    @StartTime,
    @EndTime,
    @CreationDate,
    @MachineID,
    @HardwareInfo,
    @MultiRun,
    @ExecPath,
    @WRVersion,
    @DBSideOnly,
    @HospitalID
)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO







CREATE     PROCEDURE [I_NU_CrossReference]
	(@Code		 	[int],
	 @EntryValue		[varchar](50),
	 @SearchValue	 	[varchar](50),
	 @LangID as int)

AS 

-- EBV Added @LangId PARAMETER 

if @LangId=0
begin
	SELECT @Code = (SELECT (CASE WHEN ISNULL(MAX(Code), 0) + 1 > 100000 
		THEN MAX(Code) + 1 ELSE 100000 END)  FROM NU_CrossReference)
	
	INSERT INTO [dbo].[NU_CrossReference] 
		 ([Code],
		 [EntryValue],
		 [SearchValue]) 
	VALUES 
		(@Code,
		 @EntryValue,
		 @SearchValue)
end
if @LangId=10000
begin
        SELECT @Code = (SELECT (CASE WHEN ISNULL(MAX(Code), 0) + 1 > 100000 
		  THEN MAX(Code) + 1 ELSE 100000 END) FROM NU_CrossReferenceFr)

	INSERT INTO [dbo].[NU_CrossReferenceFr] 
		 ([Code],
		 [EntryValue],
		 [SearchValue]) 
	VALUES 
		(@Code,
		 @EntryValue,
		 @SearchValue)
end

	RETURN @Code







GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






CREATE   PROCEDURE [I_NU_DProfile]
@ProfileID as int,
@CodeNum as varchar(12),
@Type as varchar(2),
@TypeCode as int,
@TypeCIHI as varchar(2),
@AST as varchar(2),
@LangID as int

AS

Declare @CodeCIHI varchar(11)
Declare @cnRec int

set @CodeCIHI=''

if @LangID=10000
Begin
	Select top 1 @CodeCIHI=CIHIVALUE from icd_diagfile10Fr where displaycode=@CodeNum


Select @cnRec=count(*) from NU_Profile where profileid=@profileID

if @cnRec>0 
begin
	Insert into NU_DProfile(ProfileID,codenum,CIHIVALUE,Code,Type,Typecode,TypeCIHI,AST)
	Values(@ProfileID,@CodeNum,@CodeCIHI,0,@Type,@Typecode,@TypeCIHI,@AST)
end
else
   RAISERROR ('Insert Failed',16,1)
end
if @LangID=0
Begin
	Select top 1 @CodeCIHI=CIHIVALUE from icd_diagfile10 where displaycode=@CodeNum


Select @cnRec=count(*) from NU_Profile where profileid=@profileID

if @cnRec>0 
begin
	Insert into NU_DProfile(ProfileID,codenum,CIHIVALUE,Code,Type,Typecode,TypeCIHI,AST)
	Values(@ProfileID,@CodeNum,@CodeCIHI,0,@Type,@Typecode,@TypeCIHI,@AST)
end
else
   RAISERROR ('Insert Failed',16,1)
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






CREATE  proc [I_NU_Excludes]

@StrDesc as Varchar(2000),

@Opt as int,
@Ntype as int,

@CodeHeader as int,
@CodeId as int,
@ChapterId as int,
@HeaderId as int,
@SubHeaderId as int,
@SubCodeHeader as int,

@LangID as int
AS
/*
set @Opt=0
set @Ntype=1
set @LangID=10000

set @CodeHeader=0
set @CodeId=0
set @ChapterId =0
set @HeaderId =0
set @SubHeaderId=0
set @SubCodeHeader=0
set @IncludeDesc =0

set @StrDesc='sdf'
*/


declare @StrSQL  varchar(3000)
declare @StrSQL1 varchar(800)

declare @InsID int

set @StrSQL1=''
if @LangId=10000
begin
	if @Ntype=1 --Intervention
	begin
		if @opt=0 -- Include
			begin
			  set @StrSQL= 'Insert into dbo.NU_Includefr(' 
				+ 'CodeHeader,CodeId,ChapterId,HeaderId,SubHeaderId,SubCodeHeader'
				+ ',IncludeDesc'
				+ ') '
				+ ' values(' 

			end
		if @opt=1 --Exclude
			begin
			 select @InsID=isnull(max(ExcludeID),0) + 1 from NU_ExcludeFr
			 set @StrSQL= 'Insert into dbo.NU_ExcludeFr(ExcludeID,' 
				+ 'CodeHeader,CodeId,ChapterId,HeaderId,SubHeaderId,SubCodeHeader'
				+ ',ExcludeDesc'
				+ ') '
				+ ' values(' + convert(varchar(30),@InsID) + ',' 
			end
		if @opt=3 -- Dagger
			begin
			 select @InsID=isnull(max(DaggerID),0) + 1 from NU_DaggerFr
			 set @StrSQL= 'Insert into dbo.NU_DaggerFr(DaggerId,' 
				+ 'CodeHeader,CodeId,ChapterId,HeaderId,SubHeaderId,SubCodeHeader'
				+ ',OptStmtsDesc'
				+ ') '
				+ ' values(' + convert(varchar(30),@InsID) + ','

			 set @StrSQL1='Update NU_CodesFR set Dagger=1 ' 
			 + 'where '
			 + 'codeheader in (0,' + convert(varchar(30),@codeheader) + ') '
			 + 'and codeid in (0,' + convert(varchar(30),@codeid) + ') '
			 + 'and chapterid in (0,' + convert(varchar(30),@chapterid) + ') '
			 + 'and headerid in (0,' + convert(varchar(30),@headerid) + ') '
			 + 'and subheaderid in (0,' + convert(varchar(30),@subheaderID) + ') '
			 + 'and subcodeheader in (0,' + convert(varchar(30),@SubCodeHeader) + ') '

			end
		if @opt=2 -- Asteriks
			begin
			 select @InsID=isnull(max(DaggerID),0) + 1 from NU_DaggerFr
			 set @StrSQL= 'Insert into dbo.NU_DaggerFr(DaggerId,' 
				+ 'CodeHeader,CodeId,ChapterId,HeaderId,SubHeaderId,SubCodeHeader'
				+ ',OptStmtsDesc'
				+ ') '
				+ ' values(' + convert(varchar(30),@InsID) + ','
			 set @StrSQL1='Update NU_CodesFR set Asteriks=1 ' 
			 + 'where '
			 + 'codeheader in (0,' + convert(varchar(30),@codeheader) + ') '
			 + 'and codeid in (0,' + convert(varchar(30),@codeid) + ') '
			 + 'and chapterid in (0,' + convert(varchar(30),@chapterid) + ') '
			 + 'and headerid in (0,' + convert(varchar(30),@headerid) + ') '
			 + 'and subheaderid in (0,' + convert(varchar(30),@subheaderID) + ') '
			 + 'and subcodeheader in (0,' + convert(varchar(30),@SubCodeHeader) + ') '
			end
		if @opt=4  -- Notes
			begin
			 select @InsID=isnull(max(NoteID),0) + 1 from NU_NotesFr
			 set @StrSQL= 'Insert into dbo.NU_NotesFr(NoteID,' 
				+ 'CodeHeader,CodeId,ChapterId,HeaderId,SubHeaderId,SubCodeHeader'
				+ ',NoteDesc'
				+ ') '
				+ ' values(' + convert(varchar(30),@InsID) + ','
			end
	end
	 
	if @Ntype=2
	begin
		if @opt=0 -- Include
			begin
			  set @StrSQL= 'Insert into dbo.NU_IntIncludefr(' 
				+ 'CodeHeader,CodeId,ChapterId,HeaderId,SubHeaderId,SubCodeHeader'
				+ ',IncludeDesc'
				+ ') '
				+ ' values(' 

			end
		if @opt=1 --Exclude
			begin
			 select @InsID=isnull(max(Excludeid),0) + 1 from NU_IntExcludeFr
			 set @StrSQL= 'Insert into dbo.NU_IntExcludeFr(Excludeid,' 
				+ 'CodeHeader,CodeId,ChapterId,HeaderId,SubHeaderId,SubCodeHeader'
				+ ',ExcludeDesc'
				+ ') '
				+ ' values(' + convert(varchar(30),@InsID) + ','
			end
		if @opt=2 -- Dagger
			begin
			 select @InsID=isnull(max(OmitId),0) + 1 from NU_IntOmitCodeFr
			 set @StrSQL= 'Insert into dbo.NU_IntOmitCodeFr(OmitId,' 
				+ 'CodeHeader,CodeId,ChapterId,HeaderId,SubHeaderId,SubCodeHeader'
				+ ',OmitDesc'
				+ ') '
				+ ' values(' + convert(varchar(30),@InsID) + ','
			end
		if @opt=3 -- Also
			begin
			 select @InsID=isnull(max(AlsoId),0) + 1 from NU_IntCodeAlsoFr
			 set @StrSQL= 'Insert into dbo.NU_IntCodeAlsoFr(AlsoId,' 
				+ 'CodeHeader,CodeId,ChapterId,HeaderId,SubHeaderId,SubCodeHeader'
				+ ',AlsoDesc'
				+ ') '
				+ ' values(' + convert(varchar(30),@InsID) + ','
			end
		if @opt=4  -- Notes
			begin
			 select @InsID=isnull(max(NoteId),0) + 1 from NU_IntNotesFr
			 set @StrSQL= 'Insert into dbo.NU_IntNotesFr(NoteId,' 
				+ 'CodeHeader,CodeId,ChapterId,HeaderId,SubHeaderId,SubCodeHeader'
				+ ',NoteDesc'
				+ ') '
				+ ' values(' + convert(varchar(30),@InsID) + ','
			end
	end
	
end

set @StrSQL = @StrSQL + 
convert(varchar(30),@CodeHeader) + ',' +
convert(varchar(30),@CodeId) + ',' +
convert(varchar(30),@ChapterId) + ',' +
convert(varchar(30),@HeaderId) + ',' +
convert(varchar(30),@SubHeaderId) + ',' +
convert(varchar(30),@SubCodeHeader) + ',' +
'''' + @StrDesc + '''' + ')'

--print @STRSQL
execute (@STRSQL)
if len(@STRSQL1)>0 
begin
	execute (@STRSQL1)
	--print @strsql1
end









GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE  PROCEDURE [I_NU_IProfile]
@ProfileID as int,
@CodeNum as varchar(15),
@TypeS as varchar(5),
@TypeL as varchar(5),
@TypeE as varchar(5),
@TypeCodeS as int,
@TypeCodeL as int,
@TypeCodeE as int,
@LangID as int

AS

Declare @CodeCIHI varchar(15)
Declare @cnRec int

set @CodeCIHI=''

if @LangID=10000
Begin
	Select top 1 @CodeCIHI=CIHIVALUE from icd_procfile10Fr where displaycode=@CodeNum


Select @cnRec=count(*) from NU_Profile where profileid=@profileID

if @cnRec>0 
begin
	Insert into NU_IntProfile(ProfileID,codenum,CIHIVALUE,
		TypeS,TypeL,TypeE,
		TypeSCode,TypeLCode,TypeECode)
	Values(@ProfileID,@CodeNum,@CodeCIHI,
		@TypeS,@TypeL,@TypeE,
		@TypeCodeS,@TypeCodeL,@TypeCodeE)
		
end
else
   RAISERROR ('Insert Failed',16,1)
end
if @LangID=0
Begin
	Select top 1 @CodeCIHI=CIHIVALUE from icd_procfile10 where displaycode=@CodeNum


Select @cnRec=count(*) from NU_Profile where profileid=@profileID

if @cnRec>0 
begin
	Insert into NU_IntProfile(ProfileID,codenum,CIHIVALUE,
		TypeS,TypeL,TypeE,
		TypeSCode,TypeLCode,TypeECode)
	Values(@ProfileID,@CodeNum,@CodeCIHI,
		@TypeS,@TypeL,@TypeE,
		@TypeCodeS,@TypeCodeL,@TypeCodeE)
		
end
else
   RAISERROR ('Insert Failed',16,1)
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO









CREATE    PROCEDURE [I_NU_LookUps]
	(@TableName 		AS VARCHAR(50),
	@Code			AS VARCHAR(50),
	@CIHIValue 	AS VARCHAR(255),
    	@PublicNote        as varchar(255))
AS 

---- EBV PR-01850 FIX QUOTATION PROBLEM
DECLARE @NOTES VARCHAR(500)
DECLARE @PT INT
DECLARE @STMP AS VARCHAR(50)

SET @NOTES = @PublicNote


SET @PT=1
SET @STMP=''
WHILE @PT<=LEN(@NOTES)
BEGIN
	SET @STMP=@STMP+SUBSTRING(@NOTES,@PT,1)
	IF SUBSTRING(@NOTES,@PT,1)=CHAR(39)
	BEGIN
		
		WHILE SUBSTRING(@NOTES,@PT+1,1)=CHAR(39) AND @PT<LEN(@NOTES)
		BEGIN
			SET @PT=@PT+1
		END
		
			
	END
	SET @PT=@PT+1
END


SET @STMP=REPLACE(@STMP,CHAR(39),CHAR(39)+CHAR(39))
SET @NOTES=@STMP
SET @PublicNote = @NOTES
--- ends EBV PR-01850

	declare @SQL varchar(500)
	
	select @SQL = 'insert into ' + @TableName + '([Code], [ICDNotes]) 				
			select (case when max(Code) + 1 > 100000 then max(Code) + 1 else 100000 END) , ''' + @PublicNote + ''' from ' + @TableName
	execute (@SQL)
	select @SQL = 'select isnull(max(Code), 0) from ' + @TableName
	execute (@SQL)

	if @TableName = 'NU_IntCodes'
		update ICD_ProcFile10 set ICDNotes = @PublicNote where CIHIValue =  @CIHIValue
	
	else if @TableName = 'NU_Codes'
		update ICD_DiagFile10 set ICDNotes = @PublicNote where CIHIValue =  @CIHIValue

	return 0


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE  PROCEDURE [I_OMH_UpdateHistory] 
	@AbstractID as int,
	@Coder as int,
	@UpdateType as varchar(10) = 'Saved'
AS 

declare @HID as int --NP-00025
select @HID = HospitalID from U_Users where Code = @Coder

insert into OMHRS_UpdateHistory (AbstractID, HospitalID, Coder, Updated, UpdateType) values (@AbstractID, @HID, @Coder, GetDate(), @UpdateType)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO







CREATE PROCEDURE [I_OMHRS_Ancillary]
	(@AbstractID	 	[int],
	 @AncillaryField1 	[int],
	 @AncillaryField2 	[int],
	 @AncillaryField3 	[int],
	 @AncillaryField4 	[int],
	 @AncillaryField5 	[int],
	 @AncillaryField6 	[int],
	 @AncillaryField7 	[int],
	 @AncillaryField8 	[int],
	 @AncillaryField9 	[int],
	 @AncillaryField10 	[int],
	 @AncillaryField11 	[int],
	 @AncillaryField12 	[int],
	 @AncillaryField13 	[int],
	 @AncillaryField14 	[int],
	 @AncillaryField15 	[int],
	 @AncillaryField16 	[int],
	 @AncillaryField17 	[int])
AS 

INSERT INTO [OMHRS_Ancillary] 
	 ( [AbstractID],
	 [AncillaryField1],
	 [AncillaryField2],
	 [AncillaryField3],
	 [AncillaryField4],
	 [AncillaryField5],
	 [AncillaryField6],
	 [AncillaryField7],
	 [AncillaryField8],
	 [AncillaryField9],
	 [AncillaryField10],
	 [AncillaryField11],
	 [AncillaryField12],
	 [AncillaryField13],
	 [AncillaryField14],
	 [AncillaryField15],
	 [AncillaryField16],
	 [AncillaryField17]) 
 
VALUES 
	(@AbstractID,
	 @AncillaryField1,
	 @AncillaryField2,
	 @AncillaryField3,
	 @AncillaryField4,
	 @AncillaryField5,
	 @AncillaryField6,
	 @AncillaryField7,
	 @AncillaryField8,
	 @AncillaryField9,
	 @AncillaryField10,
	 @AncillaryField11,
	 @AncillaryField12,
	 @AncillaryField13,
	 @AncillaryField14,
	 @AncillaryField15,
	 @AncillaryField16,
	 @AncillaryField17)






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_OMHRS_BasicOption]
	(@AbstractID 	[int],
	 @BasicOption1 	[int],
	 @BasicOption2 	[int],
	 @BasicOption3 	[int],
	 @BasicOption4 	[int],
	 @BasicOption5 	[int],
	 @BasicOption6 	[int],
	 @BasicOption7 	[int],
	 @BasicOption8 	[int],
	 @BasicOption9 	[int],
	 @BasicOption10 	[int],
	 @BasicOption11 	[int],
	 @BasicOption12 	[int],
	 @BasicOption13 	[int],
	 @BasicOption14 	[int],
	 @BasicOption15 	[int],
	 @BasicOption16 	[int],
	 @BasicOption17 	[int],
	 @BasicOption18 	[int],
	 @BasicOption19 	[int])
AS 

INSERT INTO [OMHRS_BasicOption] 
	 ([AbstractID],
	 [BasicOption1],
	 [BasicOption2],
	 [BasicOption3],
	 [BasicOption4],
	 [BasicOption5],
	 [BasicOption6],
	 [BasicOption7],
	 [BasicOption8],
	 [BasicOption9],
	 [BasicOption10],
	 [BasicOption11],
	 [BasicOption12],
	 [BasicOption13],
	 [BasicOption14],
	 [BasicOption15],
	 [BasicOption16],
	 [BasicOption17],
	 [BasicOption18],
	 [BasicOption19]) 
 
VALUES 
	(@AbstractID,
	 @BasicOption1,
	 @BasicOption2,
	 @BasicOption3,
	 @BasicOption4,
	 @BasicOption5,
	 @BasicOption6,
	 @BasicOption7,
	 @BasicOption8,
	 @BasicOption9,
	 @BasicOption10,
	 @BasicOption11,
	 @BasicOption12,
	 @BasicOption13,
	 @BasicOption14,
	 @BasicOption15,
	 @BasicOption16,
	 @BasicOption17,
	 @BasicOption18,
	 @BasicOption19)






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [I_OMHRS_Diagnosis_CodeSmart]
	(@AbstractID	 	[int],
	 @cSDiagnosisOccurrence	 	[int],
	 @cSDiagnosisText 	[varchar] (8000))

AS 
insert into [dbo].OMHRS_Diagnosis_CodeSmart 
	 ( [AbstractID],
	 cSDiagnosisOccurrence,
	 cSDiagnosisText) 
 
values
	( @AbstractID,
	 @cSDiagnosisOccurrence,
	 @cSDiagnosisText)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [I_OMHRS_DSM_5]
	(@AbstractID 	[int],
	 @Occurrence 	[int],
	 @Q2 		[int],
	 @Q2Text 	[varchar] (255)
)
AS 
INSERT INTO [OMHRS_DSM_5] 
	 ( [AbstractID],
	 [Occurrence],
	 [Q2Text],
	 [Q2]) 
 
VALUES 
	( @AbstractID,
	 @Occurrence,
	 @Q2Text,
	 @Q2)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_OMHRS_DSM_Diag]
	(@AbstractID 	[int],
	 @Occurrence 	[int],
	 @Q2Text 	[varchar] (255),
	 @Q2 		[int])

AS 
INSERT INTO [OMHRS_DSM_Diag] 
	 ( [AbstractID],
	 [Occurrence],
	 [Q2Text],
	 [Q2]) 
 
VALUES 
	( @AbstractID,
	 @Occurrence,
	 @Q2Text,
	 @Q2)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_OMHRS_DSM_Diag_II]
	(@AbstractID 	[int],
	 @Occurrence 	[int],
	 @Q2d 		[int],
	 @Q2dText 	[varchar] (255)
)
AS 
INSERT INTO [OMHRS_DSM_Diag_II] 
	 ( [AbstractID],
	 [Occurrence],
	 [Q2dText],
	 [Q2d]) 
 
VALUES 
	( @AbstractID,
	 @Occurrence,
	 @Q2dText,
	 @Q2d)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_OMHRS_IAR_CCIM]
	(@AbstractID 			[int]
	,@IAR_ConsentFlag		[int] 
	,@DateConsentGiven		[datetime] 
	,@IAR_CCIM_IsSubmitted	[int] 
	,@DateSubmittedToCCIM	[datetime] 
	,@IAR_CCIM_IsCorrected	[int] 
	,@DateCorrectedToCCIM	[datetime]
	,@TimeConsentGiven      [datetime]
	,@WhoObtainedConsent    [int]
	,@DateInformationEnter  [datetime]
	,@TimeInformationEnter  [datetime]
	,@DateEffected          [datetime]
)
AS 
INSERT INTO [OMHRS_IAR_CCIM] 
	([AbstractID]
	,[IAR_ConsentFlag]
	,[DateConsentGiven]
	,[IAR_CCIM_IsSubmitted]
	,[DateSubmittedToCCIM]
	,[IAR_CCIM_IsCorrected]
	,[DateCorrectedToCCIM]
	,[TimeConsentGiven]
	,[WhoObtainedConsent]
	,[DateInformationEnter]
	,[TimeInformationEnter]
	,[DateEffected]
) VALUES 
	(@AbstractID
	,@IAR_ConsentFlag
	,@DateConsentGiven
	,@IAR_CCIM_IsSubmitted
	,@DateSubmittedToCCIM
	,@IAR_CCIM_IsCorrected
	,@DateCorrectedToCCIM
	,@TimeConsentGiven
	,@WhoObtainedConsent
	,@DateInformationEnter
	,@TimeInformationEnter
	,@DateEffected
)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_OMHRS_Intervention]
	(@AbstractID	 		[int],
	 @IntervOccurrence 		[int],
	 @IntervDate	 		[datetime],
	 @IntervCode	 		[int],
	 @IntervAttribStatus 		[int],
	 @IntervAttribLocation 		[int],
	 @IntervAttribExtent 		[int],
	 @IntervEUL	 		[int],
	 @IntervExtra	 		[int],
	 @IntervOOHIndicator 		[int],
	 @IntervOOHInstitution 		[int],
	 @IntervProviderNumber		[int],
	 @IntervProviderService 		[int],
	 @IntervTissueCode 		[int],
	 @IntervDateIn			[datetime],
	 @IntervTimeIn	 		[datetime],
	 @IntervDateOut 		[datetime],
	 @IntervTimeOut 		[datetime],
	 @IntervTimeMinutes 		[varchar](10),
	 @IntervLocation 		[int],
	 @IntervAnaestID 		[int],
	 @IntervAnaestTechnique	[int],
	 @IntervUnplanReturn		[int],
	 @IntervSuffix			[int],
     @IntervComments        varchar(1000)
     )
AS 

INSERT INTO [OMHRS_Intervention] 
	 ([AbstractID],
	 [IntervOccurrence],
	 [IntervICDType],
	 [IntervDate],
	 [IntervCode],
	 [IntervAttribStatus],
	 [IntervAttribLocation],
	 [IntervAttribExtent],
	 [IntervEUL],
	 [IntervExtra],
	 [IntervOOHIndicator],
	 [IntervOOHInstitution],
	 [IntervProviderNumber],
	 [IntervProviderService],
	 [IntervTissueCode],
	 [IntervDateIn],
	 [IntervTimeIn],
	 [IntervDateOut],
	 [IntervTimeOut],
	 [IntervTimeMinutes],
	 [IntervLocation],
	 [IntervAnaestID],
	 [IntervAnaestTechnique],
	 [IntervUnplanReturn],
	 [IntervSuffix],
     [IntervComments]) 
 
VALUES 
	(@AbstractID,
	 @IntervOccurrence,
	 'T',
	 @IntervDate,
	 @IntervCode,
	 @IntervAttribStatus,
	 @IntervAttribLocation,
	 @IntervAttribExtent,
	 @IntervEUL,
	 @IntervExtra,
	 @IntervOOHIndicator,
	 @IntervOOHInstitution,
	 @IntervProviderNumber,
	 @IntervProviderService,
	 @IntervTissueCode,
	 @IntervDateIn,
	 @IntervTimeIn,
	 @IntervDateOut,
	 @IntervTimeOut,
	 @IntervTimeMinutes,
	 @IntervLocation,
	 @IntervAnaestID,
	 @IntervAnaestTechnique,
	 @IntervUnplanReturn,
	 @IntervSuffix,
     @IntervComments)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [I_OMHRS_Intervention_CodeSmart]
	(@AbstractID	 	[int],
	 @cSInterventionOccurrence	 	[int],
	 @cSInterventionText 	[varchar] (8000))

AS 
insert into [dbo].OMHRS_Intervention_CodeSmart 
	 ( [AbstractID],
	 cSInterventionOccurrence,
	 cSInterventionText) 
 
values
	( @AbstractID,
	 @cSInterventionOccurrence,
	 @cSInterventionText)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_OMHRS_Med_Diag]
	(@AbstractID 	[int],
	 @Occurrence 	[int],
	 @I11	[int])

AS 
INSERT INTO [OMHRS_Med_Diag] 
	 ( [AbstractID],
	 [Occurrence],
	 [I11]) 
 
VALUES 
	( @AbstractID,
	 @Occurrence,
	 @I11)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE  PROCEDURE [I_OMHRS_Medication]
	(@AbstractID 	[int],
	 @Occurrence 	[int],
	 @X1    	 	[int],
	 @X70Text 	[varchar] (255),
	 @X70 		[int],
	 @R2b 		[varchar](20),
	 @R2c 		[int],
	 @R2d 		[int],
	 @R2e 		[int],
	 @R2f		[int])

AS 

if isnull(@X1, 0) = 0 exec @X1 = P_UpdateOMHRS_X1

INSERT INTO [OMHRS_Medication] 
	 ( [AbstractID],
	 [Occurrence],
	 [X1],
	 [X70Text],
	 [X70],
	 [R2b],
	 [R2c],
	 [R2d],
	 [R2e],
	 [R2f])  
VALUES 
	( @AbstractID,
	 @Occurrence,
     	 @X1, 
	 @X70Text,
	 @X70,
	 @R2b,
	 @R2c,
	 @R2d,
	 @R2e,
	 @R2f)

    return @X1

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_OMHRS_MHAPS]
	(@AbstractID 	[int],
	 @Violence 	[int],
	 @SelfHarm 	[int],
	 @AbuseByOthers 	[int],
	 @CriminalActivity 	[int],
	 @SelfCare 	[int],
	 @SocialFunction 	[int],
	 @InterpersonalConflict 	[int],
	 @VocationalRehabilitation 	[int],
	 @SupportSystems 	[int],
	 @EconomicStatus 	[int],
	 @Adherence 	[int],
	 @PsychotropicDrugReview 	[int],
	 @PhysicalRestraintsSeclusions 	[int],
	 @AcuteControlMedication 	[int],
	 @RevolvingDoor 	[int],
	 @DischargeResources 	[int],
	 @AddictiveBehaviours 	[int],
	 @Nutrition 	[int],
	 @Dehydration 	[int],
	 @Polydipsia 	[int],
	 @SkinFootConditions 	[int],
	 @OralHealth 	[int],
	 @Pain 	[int],
	 @BladderBowelFunctioning 	[int],
	 @Cognition 	[int],
	 @CommunicationDisorder 	[int],
	 @BehaviourDisturbance 	[int],
	 @DecisionalIntegrity 	[int],
     @SelfCare_IADL int,
     @SupportSystemsCaregiverStrain int,
     @BladderBowelFunctioning_Bowel int
)

AS 
INSERT INTO [dbo].[OMHRS_MHAPS] 
	 ( [AbstractID],
	 [Violence],
	 [SelfHarm],
	 [AbuseByOthers],
	 [CriminalActivity],
	 [SelfCare],
	 [SocialFunction],
	 [InterpersonalConflict],
	 [VocationalRehabilitation],
	 [SupportSystems],
	 [EconomicStatus],
	 [Adherence],
	 [PsychotropicDrugReview],
	 [PhysicalRestraintsSeclusions],
	 [AcuteControlMedication],
	 [RevolvingDoor],
	 [DischargeResources],
	 [AddictiveBehaviours],
	 [Nutrition],
	 [Dehydration],
	 [Polydipsia],
	 [SkinFootConditions],
	 [OralHealth],
	 [Pain],
	 [BladderBowelFunctioning],
	 [Cognition],
	 [CommunicationDisorder],
	 [BehaviourDisturbance],
	 [DecisionalIntegrity],
     SelfCare_IADL,
     SupportSystemsCaregiverStrain,
     BladderBowelFunctioning_Bowel) 
 
VALUES 
	( @AbstractID,
	 @Violence,
	 @SelfHarm,
	 @AbuseByOthers,
	 @CriminalActivity,
	 @SelfCare,
	 @SocialFunction,
	 @InterpersonalConflict,
	 @VocationalRehabilitation,
	 @SupportSystems,
	 @EconomicStatus,
	 @Adherence,
	 @PsychotropicDrugReview,
	 @PhysicalRestraintsSeclusions,
	 @AcuteControlMedication,
	 @RevolvingDoor,
	 @DischargeResources,
	 @AddictiveBehaviours,
	 @Nutrition,
	 @Dehydration,
	 @Polydipsia,
	 @SkinFootConditions,
	 @OralHealth,
	 @Pain,
	 @BladderBowelFunctioning,
	 @Cognition,
	 @CommunicationDisorder,
	 @BehaviourDisturbance,
	 @DecisionalIntegrity,
     @SelfCare_IADL,
     @SupportSystemsCaregiverStrain,
     @BladderBowelFunctioning_Bowel)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO







CREATE PROCEDURE [I_OMHRS_Project]
	(@AbstractID	 	[int],
	 @ProjectOccurrence	[int],
	 @ProjectNumber	[int],
	 @Question1		[int],
	 @Question2	 	[int],
	 @Question3	 	[int],
	 @Question4	 	[int],
	 @Question5		[int],
	 @Question6		[int],
	 @Question7	 	[int],
	 @Question8	 	[int],
	 @Question9	 	[int],
	 @Question10	 	[int],
	 @Question11	 	[int],
	 @Question12		[int],
	 @Question13	 	[int],
	 @Question14	 	[varchar](10),
	 @Question15	 	[varchar](10),
	 @Question16	 	[varchar](10),
	 @Question17	 	[varchar](10))
AS 

INSERT INTO [OMHRS_Project] 
	 ([AbstractID],
	 [ProjectOccurrence],
	 [ProjectNumber],
	 [Question1],
	 [Question2],
	 [Question3],
	 [Question4],
	 [Question5],
	 [Question6],
	 [Question7],
	 [Question8],
	 [Question9],
	 [Question10],
	 [Question11],
	 [Question12],
	 [Question13],
	 [Question14],
	 [Question15],
	 [Question16],
	 [Question17]) 
 
VALUES 
	(@AbstractID,
	 @ProjectOccurrence,
	 @ProjectNumber,
	 @Question1,
	 @Question2,
	 @Question3,
	 @Question4,
	 @Question5,
	 @Question6,
	 @Question7,
	 @Question8,
	 @Question9,
	 @Question10,
	 @Question11,
	 @Question12,
	 @Question13,
	 @Question14,
	 @Question15,
	 @Question16,
	 @Question17)






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO







CREATE PROCEDURE [I_OMHRS_Provider]
	(@AbstractID	 	[int],
	 @ProviderOccurrence	[int],
	 @ProviderType 	[int],
	 @ProviderNumber 	[int],
	 @ProviderSpecialty	[int])
AS 

INSERT INTO [OMHRS_Provider] 
	 ([AbstractID],
	 [ProviderOccurrence],
	 [ProviderType],
	 [ProviderNumber],
	 [ProviderSpecialty]) 
 
VALUES 
	(@AbstractID,
	 @ProviderOccurrence,
	 @ProviderType,
	 @ProviderNumber,
	 @ProviderSpecialty)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE  PROCEDURE [I_OMHRS_RecInfo]
	(@AbstractID 	[int],
	 @IsCompleted 	[int],
	 @IsValidated 	[int],
	 @IsSubmited 	[int],
	 @IsCorrected 	[int],
	 @InterfaceDate 	[datetime],
	 @InterfaceTime 	[datetime],
	 @InterfaceCoder 	[int],
	 @InputDate 	[datetime],
	 @InputTime 	[datetime],
	 @DataEntryCoder 	[int],
	 @FinishDate	[datetime],
	 @FinishTime 	[datetime],
	 @Secret 	[int])
AS 
If isnull(@IsCorrected, 0) = 0 set @IsCorrected = 1 -- PR - 03723
If isnull(@IsSubmited, 0) = 0  set @IsSubmited = 2  -- PR - 03723

INSERT INTO [OMHRS_RecInfo] 
	 ( [AbstractID],
	 [IsCompleted],
	 [IsValidated],
	 [IsSubmited],
     [IsCorrected],
	 [IsDeleted],
	 [InterfaceDate],
	 [InterfaceTime],
	 [InterfaceCoder],
	 [InputDate],
	 [InputTime],
	 [DataEntryCoder],
	 [FinishDate],
	 [FinishTime],
	 [Secret]) 
 
VALUES 
	( @AbstractID,
	 @IsCompleted,
	 @IsValidated,
	 @IsSubmited,
     @IsCorrected,
	 2,
	 @InterfaceDate,
	 @InterfaceTime,
	 @InterfaceCoder,
	 @InputDate,
	 @InputTime,
	 @DataEntryCoder,
	 @FinishDate,
	 @FinishTime,
	 @Secret)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [I_OMHRS_SecA]
	(@AbstractID 	[int],
	 @A1 			[datetime],
	 @AssessTime	[datetime],
	 @A2 			[int],
	 @A3 			[int],
	 @A4a 			[int],
	 @A4b 			[int],
	 @A4c 			[int],
	 @A4d 			[int],
	 @A5a 			[int],
	 @A5b 			[int],
	 @NextAssessDate [datetime],
	 @LOSDays		[int],
	 @LOSTotal		[int],
	 @SignOff		[int],
     @SignDate		[datetime],
     @SignCoder		[int],
	 @X5a			[int],     -- ED - 01882
	 @X5b			[datetime],-- ED - 01882
	 @A3a			[int],	   -- ED - 01884
	 @A3b			[int],	   -- ED - 01884
	 @X6			[int],	   -- ED - 01891
	 @X200A			[int],	   -- RM: 2011/07/13
	 @X9a			[int],	   -- ED - 02808
	 @X9b			[int],	   -- ED - 02808
	 @ActualNextAssessdate datetime --PR - 06104
)

AS 
INSERT INTO [OMHRS_SecA] 
	 ( [AbstractID],
	 [A1],
	 [AssessTime], 
	 [A2],
	 [A3],
	 [A4a],
	 [A4b],
	 [A4c],
	 [A4d],
	 [A5a],
	 [A5b],
	 [NextAssessDate],
	 [LOSDays],
	 [LOSTotal],
	 [SignOff],
	 [SignDate],
	 [SignCoder],
	 [X5a],
	 [X5b],
 	 [A3a],
	 [A3b],
	 [X6],
	 [X200A],
	 [X9a],
	 [X9b],
	 [ActualNextAssessdate]) 
VALUES 
	( @AbstractID,
	 @A1,
	 @AssessTime,
	 @A2,
	 @A3,
	 @A4a,
	 @A4b,
	 @A4c,
	 @A4d,
	 @A5a,
	 @A5b,
	 @NextAssessDate,
	 @LOSDays,
	 @LOSTotal,
	 @SignOff,
	 @SignDate,
	 @SignCoder,
	 @X5a, 
	 @X5b,
 	 @A3a,
	 @A3b,
	 @X6,
	 @X200A,
	 @X9a,
	 @X9b,
	 @ActualNextAssessdate)
	 
	 --PR - 06104
	 declare @LinkID int
	 declare @PrevA1 datetime
	 set @LinkID = (select LinkID from OMHRS_SecAA where AbstractID = @AbstractID)
	 set @PrevA1 = (select max(A1) from OMHRS_SecAA aa inner join OMHRS_SecA a on aa.AbstractID = a.AbstractID 
	                where aa.LinkID = @LinkID and aa.AbstractID <> @AbstractID and a.A1 < @A1) 
	 if @LinkID <> @AbstractID
	 begin
    	 Update OMHRS_SecA
	     set ActualNextAssessdate = @A1
	     from OMHRS_SecA a
	        inner join OMHRS_SecAA aa on a.AbstractID = aa.AbstractID
	     where aa.LinkID = @LinkID and aa.AbstractID <> @AbstractID and a.A1 = @PrevA1
	 end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






CREATE        PROCEDURE [I_OMHRS_SecAA]
	(
	@AppID		[int],
	@AbstractID 	[int],
	@LinkID        	[int],
	@CareType 	[int],
	@HospitalID	[int],
	@Z1 		[int],
	@X2 		[int],
	@X1 		[int],
	@AdmitDate	[datetime],
	@AdmitTime 	[datetime],
	@LastName 	[varchar] (40), 
	@FirstName 	[varchar] (35), 
	@MiddleName 	[varchar] (15), 
	@X10 		[int],
	@HCNProvince 	[int], 
	@HealthCareNumber 	[varchar] (12), 
	@ChartNumber 	[varchar] (12), 
	@AA3 		[varchar](12),
	@InstitutionNumber	[int],
	@AA5 		[int],    
	@SignOff   	[int],
	@SignDate  	[datetime],
	@SignCoder 	[int],
        @ASignOff 	[int] ,
        @ASignDate 	[datetime],
        @ASignCoder 	[int],
	@EncounterNumber 	[varchar](50), 
	@RegisterNumber 	[varchar](50), 
	@SecondChartRegNumber 	[varchar](50), 
	@MISCode 	[int], 
	@AttendingPhysician 	[int], 
	@RefPhysician 	[int], 
	@AdmittingNurseArea 	[int],
	@X4		[int],
	@FixedChartNumber	[varchar](50),
	@UniversalEpisodeIdentifier [varchar](50),
    @HospitalAccountRecord varchar(50)
)
AS 

--select @AbstractID = (select isnull(max(AbstractID), 0) from OMHRS_SecAA) + 1
exec @AbstractID = P_UpdateOMHRS_X1
if @LinkID = 0 set @LinkID = @AbstractID
if len(isnull(@EncounterNumber, '')) = 0 set @EncounterNumber = @AA3 --PR-04840

update OMHRS_SecAA set IsCurrent = 0 where LinkID = @LinkID
insert into [OMHRS_SecAA] 
	 (
	[AbstractID],
	[AppID],
    [LinkID],
	[CareType],
	[HospitalID],
    [IsCurrent],
	[Z1],
	[X2],
	[X1],
	[AdmitDate],
	[AdmitTime], 
	[LastName], 
	[FirstName], 
	[MiddleName], 
	[X10],
	[HCNProvince], 
	[HealthCareNumber], 
	[ChartNumber], 
	[AA3],
	[InstitutionNumber],
	[AA5],
	[SignOff],
	[SignDate],
	[SignCoder],
    [ASignOff]  ,
    [ASignDate] ,
    [ASignCoder],
	[EncounterNumber],
	[RegisterNumber],
	[SecondChartRegNumber],
	[MISCode],
	[AttendingPhysician],
	[RefPhysician],
	[AdmittingNurseArea],
	[X4],
	[FixedChartNumber],
	[UniversalEpisodeIdentifier],
    [HospitalAccountRecord]
)  
values 
	(
	@AbstractID,
	@AppID,
    @LinkID,
    @CareType,
    @HospitalID,
    1, 
	@Z1,
	@X2,
	 --@X1,
    @AbstractID, 
  	@AdmitDate,
	@AdmitTime, 
	@LastName, 
	@FirstName, 
	@MiddleName, 
	@X10,
	@HCNProvince, 
	@HealthCareNumber, 
	@ChartNumber, 
	@AA3,
	@InstitutionNumber,
	@AA5,
	@SignOff,
	@SignDate,
	@SignCoder,
	@ASignOff,
    @ASignDate,
    @ASignCoder,
	@EncounterNumber,
	@RegisterNumber,
	@SecondChartRegNumber,
	@MISCode,
	@AttendingPhysician,
	@RefPhysician,
	@AdmittingNurseArea,
	@X4,
	@FixedChartNumber,
	@UniversalEpisodeIdentifier,
    @HospitalAccountRecord

)
	return @AbstractID




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE PROCEDURE [I_OMHRS_SecB]
	(@AbstractID 	[int],
	 @B1a 	[int],
	 @B1b 	[int],
	 @B1c 	[int],
	 @B1d 	[int],
	 @B1e 	[int],
	 @B1f	[int],
	 @B1g 	[int],
	 @B1h 	[int],
	 @B1i 	[int],
	 @B1j 	[int],
	 @B1k 	[int],
	 @B1l 	[int],
	 @B1m 	[int],
	 @B1n 	[int],
	 @B1o 	[int],
	 @B1p 	[int],
	 @B1q 	[int],
	 @B1r 	[int],
	 @B1s 	[int],
	 @B1t 	[int],
	 @B1u 	[int],
	 @B1v 	[int],
	 @B1w 	[int],
	 @B1x 	[int],
	 @B1y 	[int],
	 @B1z 	[int],
	 @B1aa 	[int],
	 @B1bb 	[int],
	 @B1cc 	[int],
	 @B1dd 	[int],
	 @B1ee 	[int],
	 @B1ff 	[int],
	 @B1gg 	[int],
	 @B2 	[int],
     @SignOff   [int],
     @SignDate  [datetime],
     @SignCoder [int]
     --@DRS   int
     )
AS 
INSERT INTO [OMHRS_SecB] 
	 ( [AbstractID],
	 [B1a],
	 [B1b],
	 [B1c],
	 [B1d],
	 [B1e],
	 [B1f],
	 [B1g],
	 [B1h],
	 [B1i],
	 [B1j],
	 [B1k],
	 [B1l],
	 [B1m],
	 [B1n],
	 [B1o],
	 [B1p],
	 [B1q],
	 [B1r],
	 [B1s],
	 [B1t],
	 [B1u],
	 [B1v],
	 [B1w],
	 [B1x],
	 [B1y],
	 [B1z],
	 [B1aa],
	 [B1bb],
	 [B1cc],
	 [B1dd],
	 [B1ee],
	 [B1ff],
	 [B1gg],
	 [B2],
     [SignOff],
     [SignDate],
     [SignCoder]
     --[DRS]
     ) 
 
VALUES 
	( @AbstractID,
	 @B1a,
	 @B1b,
	 @B1c,
	 @B1d,
	 @B1e,
	 @B1f,
	 @B1g,
	 @B1h,
	 @B1i,
	 @B1j,
	 @B1k,
	 @B1l,
	 @B1m,
	 @B1n,
	 @B1o,
	 @B1p,
	 @B1q,
	 @B1r,
	 @B1s,
	 @B1t,
	 @B1u,
	 @B1v,
	 @B1w,
	 @B1x,
	 @B1y,
	 @B1z,
	 @B1aa,
	 @B1bb,
	 @B1cc,
	 @B1dd,
	 @B1ee,
	 @B1ff,
	 @B1gg,
	 @B2,
     @SignOff,
     @SignDate,
     @SignCoder
     --@DRS
     )



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE  PROCEDURE [I_OMHRS_SecBB]
	(@AbstractID 	[int],
	 @BB1 	[int],
	 @BB2 	[datetime],
	 @X40 	[int],
	 @BB3 	[int],
	 @BB4 	[int],
	 @BB5 	[int],
	 @BB6a 	[int],
	 @BB6b 	[int],
	 @BB6c 	[int],
	 @BB6d 	[int],
	 @BB6e 	[int],
	 @BB6f 	[int],
	 @BB6g 	[int],
	 @X50a 	[int],
	 @X50b 	[int],
	 @X50c 	[int],
	 @X50d 	[int],
	 @X50e 	[int],
	 @X50f 	[int],
	 @X50g 	[int],
	 @X50h 	[int],
	 @X50i 	[int],
	 @BB7 	[int],
     @AgeCode [int],
	 @AgeNumber [int],
     @SignOff   [int],
     @SignDate  [datetime],
     @SignCoder [int],
	 @BB7a 	[int],
	 @BB7b 	[int],
	 @BB7c 	[int]
	 )
AS 
INSERT INTO [OMHRS_SecBB] 
	 ( [AbstractID],
	 [BB1],
	 [BB2],
	 [X40],
	 [BB3],
	 [BB4],
	 [BB5],
	 [BB6a],
	 [BB6b],
	 [BB6c],
	 [BB6d],
	 [BB6e],
	 [BB6f],
	 [BB6g],
	 [X50a],
	 [X50b],
	 [X50c],
	 [X50d],
	 [X50e],
	 [X50f],
	 [X50g],
	 [X50h],
	 [X50i],
	 [BB7],
     [AgeCode],
     [AgeNumber],
     [SignOff],
     [SignDate],
     [SignCoder],
	 [BB7a],
	 [BB7b],
	 [BB7c]
		) 
VALUES 
	( @AbstractID,
	 @BB1,
	 @BB2,
	 @X40,
	 @BB3,
	 @BB4,
	 @BB5,
	 @BB6a,
	 @BB6b,
	 @BB6c,
	 @BB6d,
	 @BB6e,
	 @BB6f,
	 @BB6g,
	 @X50a,
	 @X50b,
	 @X50c,
	 @X50d,
	 @X50e,
	 @X50f,
	 @X50g,
	 @X50h,
	 @X50i,
	 @BB7,
     @AgeCode,
     @AgeNumber,
     @SignOff,
     @SignDate,
     @SignCoder,
	 @BB7a,
	 @BB7b,
	 @BB7c
		 )



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE PROCEDURE [I_OMHRS_SecC]
	(@AbstractID 	[int],
	 @C1 	[int],
	 @C2a 	[int],
	 @C2b 	[int],
	 @C2c 	[int],
	 @C2d 	[int],
	 @C2e 	[int],
	 @C2f 	[int],
	 @C3 	[int],
	 @C4a 	[int],
	 @C4b 	[int],
	 @C4c 	[int],
	 @C4d 	[int],
	 @C5 	[int],
	 @C6 	[int],
     @SignOff   [int],
     @SignDate  [datetime],
     @SignCoder [int])

AS 
INSERT INTO [OMHRS_SecC] 
	 ( [AbstractID],
	 [C1],
	 [C2a],
	 [C2b],
	 [C2c],
	 [C2d],
	 [C2e],
	 [C2f],
	 [C3],
	 [C4a],
	 [C4b],
	 [C4c],
	 [C4d],
	 [C5],
	 [C6],     
     [SignOff],
     [SignDate],
     [SignCoder]) 
 
VALUES 
	( @AbstractID,
	 @C1,
	 @C2a,
	 @C2b,
	 @C2c,
	 @C2d,
	 @C2e,
	 @C2f,
	 @C3,
	 @C4a,
	 @C4b,
	 @C4c,
	 @C4d,
	 @C5,
	 @C6,
     @SignOff,
     @SignDate,
     @SignCoder)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE  PROCEDURE [I_OMHRS_SecCC]
	(@AbstractID 	[int],
	 @CC2a 	[int],
	 @CC2b 	[int],
	 @CC2c 	[int],
	 @CC2d 	[int],
	 @CC2e 	[int],
	 @CC2f 	[int],
	 @CC2g 	[int],
	 @X60 	[varchar](6),
	 @ResidenceCode [int],
	 @CC3 	[int],
	 @CC4 	[int],
	 @X65 	[int],
	 @CC5 	[int],
     @SignOff   [int],
     @SignDate  [datetime],
     @SignCoder [int],
	 @CC4a 	[int],
	 @CC4b 	[int],
	 @X8 [datetime],
	 @CC2h  [int]
)

AS 
INSERT INTO [OMHRS_SecCC] 
	 ( [AbstractID],
	 [CC2a],
	 [CC2b],
	 [CC2c],
	 [CC2d],
	 [CC2e],
	 [CC2f],
	 [CC2g],
	 [X60],
	 [ResidenceCode],
	 [CC3],
	 [CC4],
	 [X65],
	 [CC5],
     [SignOff],
     [SignDate],
     [SignCoder],
	 [CC4a],
	 [CC4b],
	 [X8],
	 [CC2h]) 
 
VALUES 
	( @AbstractID,
	 @CC2a,
	 @CC2b,
	 @CC2c,
	 @CC2d,
	 @CC2e,
	 @CC2f,
	 @CC2g,
	 @X60,
	 @ResidenceCode,
	 @CC3,
	 @CC4,
	 @X65,
	 @CC5,
     @SignOff,
     @SignDate,
     @SignCoder,
	 @CC4a,
	 @CC4b,
	 @X8,
	 @CC2h)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO







CREATE  PROCEDURE [I_OMHRS_SecD]
	(@AbstractID 	[int],
	 @D1a 	[int],
	 @D1b 	[int],
	 @D1c 	[int],
	 @D1d 	[int],
	 @D2a 	[int],
	 @D2b 	[int],
	 @D2c 	[int],
	 @D3 	[int],
     @SignOff   [int],
     @SignDate  [datetime],
     @SignCoder [int], 
	 @D1da  [int],
	 @D1db  [int])

AS 
INSERT INTO [OMHRS_SecD] 
	 ( [AbstractID],
	 [D1a],
	 [D1b],
	 [D1c],
	 [D1d],
	 [D2a],
	 [D2b],
	 [D2c],
	 [D3],
     [SignOff],
     [SignDate],
     [SignCoder],
	 [D1da],
	 [D1db]) 
 
VALUES 
	( @AbstractID,
	 @D1a,
	 @D1b,
	 @D1c,
	 @D1d,
	 @D2a,
	 @D2b,
	 @D2c,
	 @D3,
     @SignOff,
     @SignDate,
     @SignCoder,
     @D1da,
	 @D1db
)






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE PROCEDURE [I_OMHRS_SecDD]
	(@AbstractID 	[int],
	 @DD1 	[int],
	 @DD2 	[int],
	 @DD3 	[int],
	 @DD4 	[int],
	 @DD5 	[int],
	 @DD6 	[int],
     @SignOff   [int],
     @SignDate  [datetime],
     @SignCoder [int])

AS 
INSERT INTO [OMHRS_SecDD] 
	 ( [AbstractID],
	 [DD1],
	 [DD2],
	 [DD3],
	 [DD4],
	 [DD5],
	 [DD6],
     [SignOff],
     [SignDate],
     [SignCoder]) 
 
VALUES 
	( @AbstractID,
	 @DD1,
	 @DD2,
	 @DD3,
	 @DD4,
	 @DD5,
	 @DD6,
     @SignOff,
     @SignDate,
     @SignCoder)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE PROCEDURE [I_OMHRS_SecE]
	(@AbstractID 	[int],
	 @E1a 	[int],
	 @E1b 	[int],
	 @E1c 	[int],
	 @E1d 	[int],
	 @E1e 	[int],
	 @E1f	[int],
	 @E1g 	[int],
	 @E2 	[int],
     @SignOff   [int],
     @SignDate  [datetime],
     @SignCoder [int]
     -- ,@ABS   int
     )

AS 
INSERT INTO [OMHRS_SecE] 
	 ( [AbstractID],
	 [E1a],
	 [E1b],
	 [E1c],
	 [E1d],
	 [E1e],
	 [E1f],
	 [E1g],
	 [E2],
     [SignOff],
     [SignDate],
     [SignCoder]
     --,[ABS]
     ) 
 
VALUES 
	( @AbstractID,
	 @E1a,
	 @E1b,
	 @E1c,
	 @E1d,
	 @E1e,
	 @E1f,
	 @E1g,
	 @E2,
     @SignOff,
     @SignDate,
     @SignCoder
     --,@ABS
     )



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE PROCEDURE [I_OMHRS_SecF]
	(@AbstractID 	[int],
	 @F1a 	[int],
	 @F1b 	[int],
	 @F2 	[int],
	 @F3a 	[int],
	 @F3b 	[int],
	 @F3c 	[int],
	 @F3d 	[int],
	 @F3e 	[int],
	 @F3f 	[int],
	 @F4 	[int],
     @SignOff   [int],
     @SignDate  [datetime],
     @SignCoder [int]
     --,     @CPS   int
     )

AS 
INSERT INTO [OMHRS_SecF] 
	 ( [AbstractID],
	 [F1a],
	 [F1b],
	 [F2],
	 [F3a],
	 [F3b],
	 [F3c],
	 [F3d],
	 [F3e],
	 [F3f],
	 [F4],
     [SignOff],
     [SignDate],
     [SignCoder]
     --,     [CPS]
     ) 
 
VALUES 
	( @AbstractID,
	 @F1a,
	 @F1b,
	 @F2,
	 @F3a,
	 @F3b,
	 @F3c,
	 @F3d,
	 @F3e,
	 @F3f,
	 @F4,
     @SignOff,
     @SignDate,
     @SignCoder
     --,     @CPS
     )



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE PROCEDURE [I_OMHRS_SecG]
	(@AbstractID 	[int],
	 @G1a 	[int],
	 @G1b 	[int],
	 @G1c 	[int],
	 @G1d 	[int],
	 @G1e 	[int],
	 @G2a 	[int],
	 @G2b 	[int],
	 @G2c 	[int],
	 @G2d 	[int],
	 @G2e 	[int],
	 @G3 	[int],
	 @G4 	[int],
     @SignOff   [int],
     @SignDate  [datetime],
     @SignCoder [int]
     --,     @ADL_S int,
     --@ADL_H int
     )

AS 
INSERT INTO [OMHRS_SecG] 
	 ( [AbstractID],
	 [G1a],
	 [G1b],
	 [G1c],
	 [G1d],
	 [G1e],
	 [G2a],
	 [G2b],
	 [G2c],
	 [G2d],
	 [G2e],
	 [G3],
	 [G4],
     [SignOff],
     [SignDate],
     [SignCoder]
     --,     [ADL_S],
     --[ADL_H]
     ) 
 
VALUES 
	( @AbstractID,
	 @G1a,
	 @G1b,
	 @G1c,
	 @G1d,
	 @G1e,
	 @G2a,
	 @G2b,
	 @G2c,
	 @G2d,
	 @G2e,
	 @G3,
	 @G4,
     @SignOff,
     @SignDate,
     @SignCoder
     ---,     @ADL_S,
     --@ADL_H
     )



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE PROCEDURE [I_OMHRS_SecH]
	(@AbstractID 	[int],
	 @H1 	[int],
	 @H2 	[int],
	 @H3 	[int],
     @SignOff   [int],
     @SignDate  [datetime],
     @SignCoder [int])

AS 
INSERT INTO [OMHRS_SecH] 
	 ( [AbstractID],
	 [H1],
	 [H2],
	 [H3],
     [SignOff],
     [SignDate],
     [SignCoder]) 
 
VALUES 
	( @AbstractID,
	 @H1,
	 @H2,
	 @H3,
     @SignOff,
     @SignDate,
     @SignCoder)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [I_OMHRS_SecI]
	(@AbstractID 	[int],
	 @I1a 	[int],
	 @I1b 	[int],
	 @I1c 	[int],
	 @I1d 	[int],
	 @I1e 	[int],
	 @I1f 	[int],
	 @I1g 	[int],
	 @I1h 	[int],
	 @I1i 	[int],
	 @I1j 	[int],
	 @I1k 	[int],
	 @I1l 	[int],
	 @I1m 	[int],
	 @I1n 	[int],
	 @I1o 	[int],
	 @I1p 	[int],
	 @I1q 	[int],
	 @I2a 	[int],
	 @I2b 	[int],
	 @I2c 	[int],
	 @I2d 	[int],
	 @I2e 	[int],
	 @I2f 	[int],
	 @I2g 	[int],
	 @I3 	[int],
	 @I4 	[int],
	 @I5 	[int],
	 @I6 	[int],
	 @I7 	[int],
	 @I8a 	[int],
	 @I8b 	[int],
	 @I9 	[int],
	 @I10 	[int],
	 @X11  [int],
     @SignOff   [int],
     @SignDate  [datetime],
     @SignCoder [int],
	 @I11a 	[int],
	 @I11b 	[int],
	 @I11c 	[int],
	 @I11d 	[int],
	 @I11e 	[int],
	 @I11f 	[int],
	 @I11g 	[int],
	 @I7a 	[int],
	 @I7b 	[int],
	 @I6aa 	[int],
	 @I6ab 	[int],
	 @I6b 	[int]
)

AS 
INSERT INTO [OMHRS_SecI] 
	 ( [AbstractID],
	 [I1a],
	 [I1b],
	 [I1c],
	 [I1d],
	 [I1e],
	 [I1f],
	 [I1g],
	 [I1h],
	 [I1i],
	 [I1j],
	 [I1k],
	 [I1l],
	 [I1m],
	 [I1n],
	 [I1o],
	 [I1p],
	 [I1q],
	 [I2a],
	 [I2b],
	 [I2c],
	 [I2d],
	 [I2e],
	 [I2f],
	 [I2g],
	 [I3],
	 [I4],
	 [I5],
	 [I6],
	 [I7],
	 [I8a],
	 [I8b],
	 [I9],
	 [I10],
	 [X11],
     [SignOff],
     [SignDate],
     [SignCoder],
     [I11a],
     [I11b],
     [I11c],
     [I11d],
     [I11e],
     [I11f],
     [I11g],
     [I7a],
     [I7b],
     [I6aa],
     [I6ab],
     [I6b]
) 
VALUES 
	( @AbstractID,
	 @I1a,
	 @I1b,
	 @I1c,
	 @I1d,
	 @I1e,
	 @I1f,
	 @I1g,
	 @I1h,
	 @I1i,
	 @I1j,
	 @I1k,
	 @I1l,
	 @I1m,
	 @I1n,
	 @I1o,
	 @I1p,
	 @I1q,
	 @I2a,
	 @I2b,
	 @I2c,
	 @I2d,
	 @I2e,
	 @I2f,
	 @I2g,
	 @I3,
	 @I4,
	 @I5,
	 @I6,
	 @I7,
	 @I8a,
	 @I8b,
	 @I9,
	 @I10,
	 @X11,
     @SignOff,
     @SignDate,
     @SignCoder,
     @I11a,
     @I11b,
     @I11c,
     @I11d,
     @I11e,
     @I11f,
     @I11g,
     @I7a,
     @I7b,
     @I6aa,
     @I6ab,
     @I6b
)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO







CREATE  PROCEDURE [I_OMHRS_SecJ]
	(@AbstractID 	[int],
	 @J1a 	[int],
	 @J1b 	[int],
	 @J1c 	[int],
	 @J1d 	[int],
	 @J1e 	[int],
	 @J1f 	[int],
	 @J1g 	[int],
	 @J1h 	[int],
	 @J1i 	[int],
	 @J1j 	[int],
	 @J1k 	[int],
	 @J1l 	[int],
	 @J1m 	[int],
	 @J1n 	[int],
	 @J1o 	[int],
	 @J1p 	[int],
	 @J2 	[int],
	 @J3a 	[int],
	 @J3b 	[int],
     	@SignOff   [int],
     	@SignDate  [datetime],
     	@SignCoder [int],
   	@J1h_2009 [int], 
	@J1i_2009 [int], 
	@J1j_2009 [int], 
	@J1k_2009 [int], 
	@J1l_2009 [int], 
	@J1m_2009 [int], 
	@J1n_2009 [int], 
	@J1o_2009 [int], 
	@J1p_2009 [int])

AS 
INSERT INTO [OMHRS_SecJ] 
	 ( [AbstractID],
	 [J1a],
	 [J1b],
	 [J1c],
	 [J1d],
	 [J1e],
	 [J1f],
	 [J1g],
	 [J1h],
	 [J1i],
	 [J1j],
	 [J1k],
	 [J1l],
	 [J1m],
	 [J1n],
	 [J1o],
	 [J1p],
	 [J2],
	 [J3a],
	 [J3b],
     [SignOff],
     [SignDate],
     [SignCoder],
   	[J1h_2009], 
	[J1i_2009], 
	[J1j_2009], 
	[J1k_2009], 
	[J1l_2009], 
	[J1m_2009], 
	[J1n_2009], 
	[J1o_2009], 
	[J1p_2009]) 
VALUES 
	( @AbstractID,
	 @J1a,
	 @J1b,
	 @J1c,
	 @J1d,
	 @J1e,
	 @J1f,
	 @J1g,
	 @J1h,
	 @J1i,
	 @J1j,
	 @J1k,
	 @J1l,
	 @J1m,
	 @J1n,
	 @J1o,
	 @J1p,
	 @J2,
	 @J3a,
	 @J3b,
     @SignOff,
     @SignDate,
     @SignCoder,
   	@J1h_2009, 
	@J1i_2009, 
	@J1j_2009, 
	@J1k_2009, 
	@J1l_2009, 
	@J1m_2009, 
	@J1n_2009, 
	@J1o_2009, 
	@J1p_2009)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE PROCEDURE [I_OMHRS_SecK]
	(@AbstractID 	[int],
	 @K1 	[int],
	 @K2 	[int],
	 @K3 	[int],
	 @K4 	[int],
	 @K5 	[int],
	 @K6 	[int],
     @SignOff   [int],
     @SignDate  [datetime],
     @SignCoder [int])

AS 
INSERT INTO [OMHRS_SecK] 
	 ( [AbstractID],
	 [K1],
	 [K2],
	 [K3],
	 [K4],
	 [K5],
	 [K6],
     [SignOff],
     [SignDate],
     [SignCoder]) 
 
VALUES 
	( @AbstractID,
	 @K1,
	 @K2,
	 @K3,
	 @K4,
	 @K5,
	 @K6,
     @SignOff,
     @SignDate,
     @SignCoder)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






CREATE PROCEDURE [I_OMHRS_SecL]
	(@AbstractID 	[int],
	 @L1a 	[int],
	 @L1b 	[int],
	 @L1c 	[int],
	 @L1d 	[int],
	 @L1e 	[int],
	 @L1f	[int],
	 @L1g 	[int],
	 @L1h 	[int],
	 @L2a 	[int],
	 @L2b 	[int],
	 @L2c 	[int],
	 @L2d 	[int],
	 @L3a 	[int],
	 @L3b 	[int],
	 @L3c 	[int],
	 @L3d 	[int],
	 @L4a 	[int],
	 @L4b 	[int],
	 @L4c 	[int],
	 @L4d 	[int],
	 @L4e 	[int],
	 @L4f 	[int],
	 @L4g 	[int],
	 @L4h 	[int],
	 @L4i 	[int],
	 @L4j 	[int],
	 @L4k 	[int],
	 @L4l 	[int],
	 @L5 	[int],
	 @L6 	[int],
     @SignOff   [int],
     @SignDate  [datetime],
     @SignCoder [int])

AS 
INSERT INTO [OMHRS_SecL] 
	 ( [AbstractID],
	 [L1a],
	 [L1b],
	 [L1c],
	 [L1d],
	 [L1e],
	 [L1f],
	 [L1g],
	 [L1h],
	 [L2a],
	 [L2b],
	 [L2c],
	 [L2d],
	 [L3a],
	 [L3b],
	 [L3c],
	 [L3d],
	 [L4a],
	 [L4b],
	 [L4c],
	 [L4d],
	 [L4e],
	 [L4f],
	 [L4g],
	 [L4h],
	 [L4i],
	 [L4j],
	 [L4k],
	 [L4l],
	 [L5],
	 [L6],
     [SignOff],
     [SignDate],
     [SignCoder]) 
 
VALUES 
	( @AbstractID,
	 @L1a,
	 @L1b,
	 @L1c,
	 @L1d,
	 @L1e,
	 @L1f,
	 @L1g,
	 @L1h,
	 @L2a,
	 @L2b,
	 @L2c,
	 @L2d,
	 @L3a,
	 @L3b,
	 @L3c,
	 @L3d,
	 @L4a,
	 @L4b,
	 @L4c,
	 @L4d,
	 @L4e,
	 @L4f,
	 @L4g,
	 @L4h,
	 @L4i,
	 @L4j,
	 @L4k,
	 @L4l,
	 @L5,
	 @L6,
     @SignOff,
     @SignDate,
     @SignCoder)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE PROCEDURE [I_OMHRS_SecM]
	(@AbstractID 	[int],
	 @M1a	[int],
	 @M1b 	[int],
	 @M1c 	[int],
	 @M1d 	[int],
	 @M1e 	[int],
	 @M1f 	[int],
	 @M2a 	[int],
	 @M2b 	[int],
	 @M2c 	[int],
	 @M2d 	[int],
	 @M3 	[int],
	 @M4a 	[int],
	 @M4b	[int],
     @SignOff   [int],
     @SignDate  [datetime],
     @SignCoder [int])

AS 
INSERT INTO [OMHRS_SecM] 
	 ( [AbstractID],
	 [M1a],
	 [M1b],
	 [M1c],
	 [M1d],
	 [M1e],
	 [M1f],
	 [M2a],
	 [M2b],
	 [M2c],
	 [M2d],
	 [M3],
	 [M4a],
	 [M4b],
     [SignOff],
     [SignDate],
     [SignCoder]) 
 
VALUES 
	( @AbstractID,
	 @M1a,
	 @M1b,
	 @M1c,
	 @M1d,
	 @M1e,
	 @M1f,
	 @M2a,
	 @M2b,
	 @M2c,
	 @M2d,
	 @M3,
	 @M4a,
	 @M4b,
     @SignOff,
     @SignDate,
     @SignCoder)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE PROCEDURE [I_OMHRS_SecN]
	(@AbstractID 	[int],
	 @N1a	[int],
	 @N1b 	[int],
	 @N2a 	[int],
	 @N2b 	[int],
	 @N2c 	[int],
	 @N2d 	[int],
	 @N3a 	[int],
	 @N3b 	[int],
	 @N3c 	[int],
	 @N4 	[int],
     @SignOff   [int],
     @SignDate  [datetime],
     @SignCoder [int])

AS 
INSERT INTO [OMHRS_SecN] 
	 ( [AbstractID],
	 [N1a],
	 [N1b],
	 [N2a],
	 [N2b],
	 [N2c],
	 [N2d],
	 [N3a],
	 [N3b],
	 [N3c],
	 [N4],
     [SignOff],
     [SignDate],
     [SignCoder]) 
 
VALUES 
	( @AbstractID,
	 @N1a,
	 @N1b,
	 @N2a,
	 @N2b,
	 @N2c,
	 @N2d,
	 @N3a,
	 @N3b,
	 @N3c,
	 @N4,
     @SignOff,
     @SignDate,
     @SignCoder)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE PROCEDURE [I_OMHRS_SecO]
	(@AbstractID 	[int],
	 @O1 	[int],
	 @O2a 	[int],
	 @O2b 	[int],
	 @O2c 	[int],
	 @O2d 	[int],
	 @O2e 	[int],
	 @O2f 	[int],
	 @O2g 	[int],
	 @O3 	[int],
	 @O4a 	[int],
	 @O4b 	[int],
	 @O4c 	[int],
	 @O4d 	[int],
	 @O5 	[int],
	 @O6a 	[int],
	 @O6b 	[int],
	 @O6c 	[int],
     @SignOff   [int],
     @SignDate  [datetime],
     @SignCoder [int])

AS 
INSERT INTO [OMHRS_SecO] 
	 ( [AbstractID],
	 [O1],
	 [O2a],
	 [O2b],
	 [O2c],
	 [O2d],
	 [O2e],
	 [O2f],
	 [O2g],
	 [O3],
	 [O4a],
	 [O4b],
	 [O4c],
	 [O4d],
	 [O5],
	 [O6a],
	 [O6b],
	 [O6c],
     [SignOff],
     [SignDate],
     [SignCoder]) 
 
VALUES 
	( @AbstractID,
	 @O1,
	 @O2a,
	 @O2b,
	 @O2c,
	 @O2d,
	 @O2e,
	 @O2f,
	 @O2g,
	 @O3,
	 @O4a,
	 @O4b,
	 @O4c,
	 @O4d,
	 @O5,
	 @O6a,
	 @O6b,
	 @O6c,
     @SignOff,
     @SignDate,
     @SignCoder)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_OMHRS_SecP]
	(@AbstractID 	[int],
	 @P1a 	[int],
	 @P1b 	[int],
	 @P1c 	[int],
	 @P1d 	[int],
	 @P2a 	[int],
	 @P2b 	[int],
	 @P3 	[int],
	 @P4 	[int],
	 @P5 	[int],
	 @X140 	[int],
     @SignOff   [int],
     @SignDate  [datetime],
     @SignCoder [int],
   	 @X141 	[int]
)

AS 
INSERT INTO [OMHRS_SecP] 
	 ( [AbstractID],
	 [P1a],
	 [P1b],
	 [P1c],
	 [P1d],
	 [P2a],
	 [P2b],
	 [P3],
	 [P4],
	 [P5],
	 [X140],
     [SignOff],
     [SignDate],
     [SignCoder],
     [X141]
	 ) 
 
VALUES 
	( @AbstractID,
	 @P1a,
	 @P1b,
	 @P1c,
	 @P1d,
	 @P2a,
	 @P2b,
	 @P3,
	 @P4,
	 @P5,
	 @X140,
     @SignOff,
     @SignDate,
     @SignCoder,
     @X141
	 )





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_OMHRS_SecQ]
	(@AbstractID 	[int],
	 @Q1a 	[int],
	 @Q1b 	[int],
	 @Q1c 	[int],
	 @Q1d 	[int],
	 @Q1e 	[int],
	 @Q1f 	[int],
	 @Q1g 	[int],
	 @Q1h 	[int],
	 @Q1i 	[int],
	 @Q1j 	[int],
	 @Q1k 	[int],
	 @Q1l 	[int],
	 @Q1m 	[int],
	 @Q1n 	[int],
	 @Q1o 	[int],
	 @Q1p 	[int],
	 --@Q2dText [varchar] (255) ,   --ED - 02279
	 --@Q2d  [int],
	 @Q3 	[int],
	 @Q4 	[int],
	 @Q5 	[int],
     @SignOff   [int],
     @SignDate  [datetime],
     @SignCoder [int],
	 @Q1q   [int],
	 @X7	[int],
	 @Q1a2016 	[int],
	 @Q1b2016 	[int],
	 @Q1c2016 	[int],
	 @Q1d2016 	[int],
	 @Q1e2016 	[int],
	 @Q1f2016 	[int],
	 @Q1g2016 	[int],
	 @Q1h2016 	[int],
	 @Q1i2016 	[int],
	 @Q1j2016 	[int],
	 @Q1k2016 	[int],
	 @Q1l2016 	[int],
	 @Q1m2016 	[int],
	 @Q1n2016 	[int],
	 @Q1o2016 	[int],
	 @Q1p2016 	[int],
	 @Q1q2016 	[int],
	 @Q1r2016 	[int],
	 @Q1s2016 	[int],
	 @Q1t2016 	[int],
	 @Q1u2016 	[int],
	 @Q1v2016 	[int],
   	 @X160 	[int],
   	 @X161 	[int],
   	 @X162 	[int],
   	 @X163 	[int],
   	 @X164 	[int]
	 )

AS
INSERT INTO [OMHRS_SecQ] 
	 ( [AbstractID],
	 [Q1a],
	 [Q1b],
	 [Q1c],
	 [Q1d],
	 [Q1e],
	 [Q1f],
	 [Q1g],
	 [Q1h],
	 [Q1i],
	 [Q1j],
	 [Q1k],
	 [Q1l],
	 [Q1m],
	 [Q1n],
	 [Q1o],
	 [Q1p],
	 --[Q2dText],
	 --[Q2d],
	 [Q3],
	 [Q4],
	 [Q5],
     [SignOff],
     [SignDate],
     [SignCoder],
	[Q1q],
	[X7],
	 [Q1a2016],
	 [Q1b2016],
	 [Q1c2016],
	 [Q1d2016],
	 [Q1e2016],
	 [Q1f2016],
	 [Q1g2016],
	 [Q1h2016],
	 [Q1i2016],
	 [Q1j2016],
	 [Q1k2016],
	 [Q1l2016],
	 [Q1m2016],
	 [Q1n2016],
	 [Q1o2016],
	 [Q1p2016],
	 [Q1q2016],
	 [Q1r2016],
	 [Q1s2016],
	 [Q1t2016],
	 [Q1u2016],
	 [Q1v2016],
     [X160],
     [X161],
     [X162],
     [X163],
     [X164]
	 ) 
 
VALUES 
	( @AbstractID,
	 @Q1a,
	 @Q1b,
	 @Q1c,
	 @Q1d,
	 @Q1e,
	 @Q1f,
	 @Q1g,
	 @Q1h,
	 @Q1i,
	 @Q1j,
	 @Q1k,
	 @Q1l,
	 @Q1m,
	 @Q1n,
	 @Q1o,
	 @Q1p,
	 --@Q2dText,
	 --@Q2d,
	 @Q3,
	 @Q4,
	 @Q5,
     @SignOff,
     @SignDate,
     @SignCoder,
	@Q1q,
	@X7,
	@Q1a2016,
	@Q1b2016,
	@Q1c2016,
	@Q1d2016,
	@Q1e2016,
	@Q1f2016,
	@Q1g2016,
	@Q1h2016,
	@Q1i2016,
	@Q1j2016,
	@Q1k2016,
	@Q1l2016,
	@Q1m2016,
	@Q1n2016,
	@Q1o2016,
	@Q1p2016,
	@Q1q2016,
	@Q1r2016,
	@Q1s2016,
	@Q1t2016,
	@Q1u2016,
	@Q1v2016,
     @X160,
     @X161,
     @X162,
     @X163,
     @X164
	 )



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE PROCEDURE [I_OMHRS_SecR]
	(@AbstractID 	[int],
	 @R1 	[int],
     @SignOff   [int],
     @SignDate  [datetime],
     @SignCoder [int])

AS 
INSERT INTO [OMHRS_SecR] 
	 ( [AbstractID],
	 [R1],
     [SignOff],
     [SignDate],
     [SignCoder]) 
 
VALUES 
	( @AbstractID,
	 @R1,
     @SignOff,
     @SignDate,
     @SignCoder)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_OMHRS_SecS]
	(@AbstractID 	[int],
	 @X75 		[int],
	 @X80 		[datetime],
	 @DischargeTime [datetime],
	 @X90 		[int],
	 @X130 	    [int],
     @SignOff   [int],
     @SignDate  [datetime],
     @SignCoder [int],     
     @X121a		[int],
	 @X121b		[int],
	 @X121c		[int],
	 @X121d		[int],
	 @X121e		[int],
	 @X121f		[int],
	 @X121g		[int],
	 @X121h		[int],
	 @X8a		[int],
	 @X8b		[int],
	 @X8c		[datetime],
	 @X131		[int],
	 @X150		[int],
	 @X151		[int]
	 )

AS 
INSERT INTO [OMHRS_SecS] 
	 ( [AbstractID],
	 [X75],
	 [X80],
	 [DischargeTime],
	 [X90],
	 [X130],
     [SignOff],
     [SignDate],
     [SignCoder],
     [X121a],
	 [X121b],
	 [X121c],
	 [X121d],
	 [X121e],
	 [X121f],
	 [X121g],
	 [X121h],
	 [X8a],
	 [X8b],
	 [X8c],
	 [X131],
	 [X150],
	 [X151]
	 ) 
 
VALUES 
	( @AbstractID,
	 @X75,
	 @X80,
	 @DischargeTime,
	 @X90,
	 @X130,
     @SignOff,
     @SignDate,
     @SignCoder,
     @X121a,
	 @X121b,
	 @X121c,
	 @X121d,
	 @X121e,
	 @X121f,
	 @X121g,
	 @X121h,
	 @X8a,
	 @X8b,
	 @X8c,
	 @X131,
	 @X150,
	 @X151
)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_OMHRS_Serv_Interrupt]
	(@AbstractID 	[int],
	 @Occurrence 	[int],
	 @X100 	[datetime],
	 @X110 	[datetime],
	 @X120 	[int],
	 @InteruptLOS	[int]
	 --@X122  [int] ED - 02808 CIHI requested and dropped
)
AS
--PR - 04398 reverse ED-01561
--ED-01561 
INSERT INTO [OMHRS_Serv_Interrupt] ( [AbstractID], [Occurrence], [X100], [X110], [X120], [InteruptLOS]) --, X122) 
VALUES ( @AbstractID, @Occurrence, @X100, @X110, @X120, @InteruptLOS) --, @X122)

--insert into  [OMHRS_Serv_Interrupt] 
--	 ([AbstractID],
--	 [Occurrence],
--	 [X100],
--	 [X110],
--	 [X120],
--	 [InteruptLOS]) 
--select AbstractID,
--	 @Occurrence,
--	 @X100,
--	 @X110,
--	 @X120,
--	 @InteruptLOS
--from OMHRS_SecAA where LinkID = @AbstractID

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_OMHRS_UDFieldsDate]
	(@AbstractID 	[int],
	 @UDDate6 	[datetime],
	 @UDDate7 	[datetime],
	 @UDDate8 	[datetime],
	 @UDDate9 	[datetime],
	 @UDDate10 	[datetime],
	 @UDDate11 	[datetime],
	 @UDDate12 	[datetime],
	 @UDDate13 	[datetime],
	 @UDDate14 	[datetime],
	 @UDDate15 	[datetime],
	 @UDDate16 	[datetime],
	 @UDDate17 	[datetime],
	 @UDDate18 	[datetime],
	 @UDDate19 	[datetime],
	 @UDDate20 	[datetime],
	 @UDDate21 	[datetime],
	 @UDDate22 	[datetime],
	 @UDDate23 	[datetime],
	 @UDDate24 	[datetime],
	 @UDDate25 	[datetime])
as 
insert into [dbo].[OMHRS_UDFieldsDate] 
	 ([AbstractID],
	 [UDDate6],
	 [UDDate7],
	 [UDDate8],
	 [UDDate9],
	 [UDDate10],
	 [UDDate11],
	 [UDDate12],
	 [UDDate13],
	 [UDDate14],
	 [UDDate15],
	 [UDDate16],
	 [UDDate17],
	 [UDDate18],
	 [UDDate19],
	 [UDDate20],
	 [UDDate21],
	 [UDDate22],
	 [UDDate23],
	 [UDDate24],
	 [UDDate25]) 
values
	(@AbstractID,
	 @UDDate6,
	 @UDDate7,
	 @UDDate8,
	 @UDDate9,
	 @UDDate10,
	 @UDDate11,
	 @UDDate12,
	 @UDDate13,
	 @UDDate14,
	 @UDDate15,
	 @UDDate16,
	 @UDDate17,
	 @UDDate18,
	 @UDDate19,
	 @UDDate20,
	 @UDDate21,
	 @UDDate22,
	 @UDDate23,
	 @UDDate24,
	 @UDDate25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_OMHRS_UDFieldsInteger]
	(@AbstractID 	[int],
	 @UDInteger6 	[varchar](50),
	 @UDInteger7 	[varchar](50),
	 @UDInteger8 	[varchar](50),
	 @UDInteger9 	[varchar](50),
	 @UDInteger10 	[varchar](50),
	 @UDInteger11 	[varchar](50),
	 @UDInteger12 	[varchar](50),
	 @UDInteger13 	[varchar](50),
	 @UDInteger14 	[varchar](50),
	 @UDInteger15 	[varchar](50),
	 @UDInteger16 	[varchar](50),
	 @UDInteger17 	[varchar](50),
	 @UDInteger18 	[varchar](50),
	 @UDInteger19 	[varchar](50),
	 @UDInteger20 	[varchar](50),
	 @UDInteger21 	[varchar](50),
	 @UDInteger22 	[varchar](50),
	 @UDInteger23 	[varchar](50),
	 @UDInteger24 	[varchar](50),
	 @UDInteger25 	[varchar](50))
as 
insert into [dbo].[OMHRS_UDFieldsInteger] 
	 ([AbstractID],
	 [UDInteger6],
	 [UDInteger7],
	 [UDInteger8],
	 [UDInteger9],
	 [UDInteger10],
	 [UDInteger11],
	 [UDInteger12],
	 [UDInteger13],
	 [UDInteger14],
	 [UDInteger15],
	 [UDInteger16],
	 [UDInteger17],
	 [UDInteger18],
	 [UDInteger19],
	 [UDInteger20],
	 [UDInteger21],
	 [UDInteger22],
	 [UDInteger23],
	 [UDInteger24],
	 [UDInteger25]) 
values
	(@AbstractID,
	 @UDInteger6,
	 @UDInteger7,
	 @UDInteger8,
	 @UDInteger9,
	 @UDInteger10,
	 @UDInteger11,
	 @UDInteger12,
	 @UDInteger13,
	 @UDInteger14,
	 @UDInteger15,
	 @UDInteger16,
	 @UDInteger17,
	 @UDInteger18,
	 @UDInteger19,
	 @UDInteger20,
	 @UDInteger21,
	 @UDInteger22,
	 @UDInteger23,
	 @UDInteger24,
	 @UDInteger25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_OMHRS_UDFieldsLookUp]
	(@AbstractID 	[int],
	 @UDLookUp6 	[int],
	 @UDLookUp7 	[int],
	 @UDLookUp8 	[int],
	 @UDLookUp9 	[int],
	 @UDLookUp10 	[int],
	 @UDLookUp11 	[int],
	 @UDLookUp12 	[int],
	 @UDLookUp13 	[int],
	 @UDLookUp14 	[int],
	 @UDLookUp15 	[int],
	 @UDLookUp16 	[int],
	 @UDLookUp17 	[int],
	 @UDLookUp18 	[int],
	 @UDLookUp19 	[int],
	 @UDLookUp20 	[int],
	 @UDLookUp21 	[int],
	 @UDLookUp22 	[int],
	 @UDLookUp23 	[int],
	 @UDLookUp24 	[int],
	 @UDLookUp25 	[int])
as 
insert into [dbo].[OMHRS_UDFieldsLookUp] 
	 ([AbstractID],
	 [UDLookUp6],
	 [UDLookUp7],
	 [UDLookUp8],
	 [UDLookUp9],
	 [UDLookUp10],
	 [UDLookUp11],
	 [UDLookUp12],
	 [UDLookUp13],
	 [UDLookUp14],
	 [UDLookUp15],
	 [UDLookUp16],
	 [UDLookUp17],
	 [UDLookUp18],
	 [UDLookUp19],
	 [UDLookUp20],
	 [UDLookUp21],
	 [UDLookUp22],
	 [UDLookUp23],
	 [UDLookUp24],
	 [UDLookUp25]) 
values
	(@AbstractID,
	 @UDLookUp6,
	 @UDLookUp7,
	 @UDLookUp8,
	 @UDLookUp9,
	 @UDLookUp10,
	 @UDLookUp11,
	 @UDLookUp12,
	 @UDLookUp13,
	 @UDLookUp14,
	 @UDLookUp15,
	 @UDLookUp16,
	 @UDLookUp17,
	 @UDLookUp18,
	 @UDLookUp19,
	 @UDLookUp20,
	 @UDLookUp21,
	 @UDLookUp22,
	 @UDLookUp23,
	 @UDLookUp24,
	 @UDLookUp25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_OMHRS_UDFieldsSmallText]
	(@AbstractID 	[int],
	 @UDSmallText6 	[varchar](50),
	 @UDSmallText7 	[varchar](50),
	 @UDSmallText8 	[varchar](50),
	 @UDSmallText9 	[varchar](50),
	 @UDSmallText10 	[varchar](50),
	 @UDSmallText11 	[varchar](50),
	 @UDSmallText12 	[varchar](50),
	 @UDSmallText13 	[varchar](50),
	 @UDSmallText14 	[varchar](50),
	 @UDSmallText15 	[varchar](50),
	 @UDSmallText16 	[varchar](50),
	 @UDSmallText17 	[varchar](50),
	 @UDSmallText18 	[varchar](50),
	 @UDSmallText19 	[varchar](50),
	 @UDSmallText20 	[varchar](50),
	 @UDSmallText21 	[varchar](50),
	 @UDSmallText22 	[varchar](50),
	 @UDSmallText23 	[varchar](50),
	 @UDSmallText24 	[varchar](50),
	 @UDSmallText25 	[varchar](50))
as 
insert into [dbo].[OMHRS_UDFieldsSmallText] 
	 ([AbstractID],
	 [UDSmallText6],
	 [UDSmallText7],
	 [UDSmallText8],
	 [UDSmallText9],
	 [UDSmallText10],
	 [UDSmallText11],
	 [UDSmallText12],
	 [UDSmallText13],
	 [UDSmallText14],
	 [UDSmallText15],
	 [UDSmallText16],
	 [UDSmallText17],
	 [UDSmallText18],
	 [UDSmallText19],
	 [UDSmallText20],
	 [UDSmallText21],
	 [UDSmallText22],
	 [UDSmallText23],
	 [UDSmallText24],
	 [UDSmallText25]) 
values
	(@AbstractID,
	 @UDSmallText6,
	 @UDSmallText7,
	 @UDSmallText8,
	 @UDSmallText9,
	 @UDSmallText10,
	 @UDSmallText11,
	 @UDSmallText12,
	 @UDSmallText13,
	 @UDSmallText14,
	 @UDSmallText15,
	 @UDSmallText16,
	 @UDSmallText17,
	 @UDSmallText18,
	 @UDSmallText19,
	 @UDSmallText20,
	 @UDSmallText21,
	 @UDSmallText22,
	 @UDSmallText23,
	 @UDSmallText24,
	 @UDSmallText25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_OMHRS_UDFieldsText]
	(@AbstractID 	[int],
	 @UDText6 	[varchar](255),
	 @UDText7 	[varchar](255),
	 @UDText8 	[varchar](255),
	 @UDText9 	[varchar](255),
	 @UDText10 	[varchar](255),
	 @UDText11 	[varchar](255),
	 @UDText12 	[varchar](255),
	 @UDText13 	[varchar](255),
	 @UDText14 	[varchar](255),
	 @UDText15 	[varchar](255),
	 @UDText16 	[varchar](255),
	 @UDText17 	[varchar](255),
	 @UDText18 	[varchar](255),
	 @UDText19 	[varchar](255),
	 @UDText20 	[varchar](255),
	 @UDText21 	[varchar](255),
	 @UDText22 	[varchar](255),
	 @UDText23 	[varchar](255),
	 @UDText24 	[varchar](255),
	 @UDText25 	[varchar](255))
as 
insert into [dbo].[OMHRS_UDFieldsText] 
	 ([AbstractID],
	 [UDText6],
	 [UDText7],
	 [UDText8],
	 [UDText9],
	 [UDText10],
	 [UDText11],
	 [UDText12],
	 [UDText13],
	 [UDText14],
	 [UDText15],
	 [UDText16],
	 [UDText17],
	 [UDText18],
	 [UDText19],
	 [UDText20],
	 [UDText21],
	 [UDText22],
	 [UDText23],
	 [UDText24],
	 [UDText25]) 
values
	(@AbstractID,
	 @UDText6,
	 @UDText7,
	 @UDText8,
	 @UDText9,
	 @UDText10,
	 @UDText11,
	 @UDText12,
	 @UDText13,
	 @UDText14,
	 @UDText15,
	 @UDText16,
	 @UDText17,
	 @UDText18,
	 @UDText19,
	 @UDText20,
	 @UDText21,
	 @UDText22,
	 @UDText23,
	 @UDText24,
	 @UDText25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_OMHRS_UDFieldsTime]
	(@AbstractID 	[int],
	 @UDTime6 	[datetime],
	 @UDTime7 	[datetime],
	 @UDTime8 	[datetime],
	 @UDTime9 	[datetime],
	 @UDTime10 	[datetime],
	 @UDTime11 	[datetime],
	 @UDTime12 	[datetime],
	 @UDTime13 	[datetime],
	 @UDTime14 	[datetime],
	 @UDTime15 	[datetime],
	 @UDTime16 	[datetime],
	 @UDTime17 	[datetime],
	 @UDTime18 	[datetime],
	 @UDTime19 	[datetime],
	 @UDTime20 	[datetime],
	 @UDTime21 	[datetime],
	 @UDTime22 	[datetime],
	 @UDTime23 	[datetime],
	 @UDTime24 	[datetime],
	 @UDTime25 	[datetime])
as 
insert into [dbo].[OMHRS_UDFieldsTime] 
	 ([AbstractID],
	 [UDTime6],
	 [UDTime7],
	 [UDTime8],
	 [UDTime9],
	 [UDTime10],
	 [UDTime11],
	 [UDTime12],
	 [UDTime13],
	 [UDTime14],
	 [UDTime15],
	 [UDTime16],
	 [UDTime17],
	 [UDTime18],
	 [UDTime19],
	 [UDTime20],
	 [UDTime21],
	 [UDTime22],
	 [UDTime23],
	 [UDTime24],
	 [UDTime25]) 
values
	(@AbstractID,
	 @UDTime6,
	 @UDTime7,
	 @UDTime8,
	 @UDTime9,
	 @UDTime10,
	 @UDTime11,
	 @UDTime12,
	 @UDTime13,
	 @UDTime14,
	 @UDTime15,
	 @UDTime16,
	 @UDTime17,
	 @UDTime18,
	 @UDTime19,
	 @UDTime20,
	 @UDTime21,
	 @UDTime22,
	 @UDTime23,
	 @UDTime24,
	 @UDTime25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO







CREATE  PROCEDURE [I_OMHRS_UserDefined]
	(@AbstractID 	[int],
	 @UDDate1 	[datetime],
	 @UDDate2 	[datetime],
	 @UDDate3 	[datetime],
	 @UDDate4 	[datetime],
	 @UDTime1 	[datetime],
	 @UDTime2 	[datetime],
	 @UDTime3 	[datetime],
	 @UDTime4 	[datetime],
	 @UDLookup1 	[int],
	 @UDLookup2 	[int],
	 @UDLookup3 	[int],
	 @UDLookup4 	[int],
	 @UDInteger1 	[int],
	 @UDInteger2 	[int],
	 @UDInteger3 	[int],
	 @UDInteger4 	[int],
	 @UDText1 	[varchar](255),
	 @UDText2 	[varchar](255),
	 @UDText3 	[varchar](255),
	 @UDText4 	[varchar](255),
	 @UDSmallText1 [varchar](50), 
	 @UDSmallText2 [varchar](50), 
	 @UDSmallText3 [varchar](50), 
	 @UDSmallText4 [varchar](50),
	 @UDDate5 	[datetime], 
	 @UDTime5 	[datetime], 
	 @UDLookup5 	[int], 
	 @UDInteger5 	[varchar](50), 
	 @UDText5 	[varchar](255), 
 	 @UDSmallText5 	[varchar](50))
AS 
INSERT INTO [dbo].[OMHRS_UserDefined] 
	 ([AbstractID],
	 [UDDate1],
	 [UDDate2],
	 [UDDate3],
	 [UDDate4],
	 [UDTime1],
	 [UDTime2],
	 [UDTime3],
	 [UDTime4],
	 [UDLookup1],
	 [UDLookup2],
	 [UDLookup3],
	 [UDLookup4],
	 [UDInteger1],
	 [UDInteger2],
	 [UDInteger3],
	 [UDInteger4],
	 [UDText1],
	 [UDText2],
	 [UDText3],
	 [UDText4],
	 [UDSmallText1], 
	 [UDSmallText2], 
	 [UDSmallText3], 
	 [UDSmallText4],
	 [UDDate5], 
	 [UDTime5], 
	 [UDLookup5], 
	 [UDInteger5], 
	 [UDText5], 
 	 [UDSmallText5]) 
VALUES 
	(@AbstractID,
	 @UDDate1,
	 @UDDate2,
	 @UDDate3,
	 @UDDate4,
	 @UDTime1,
	 @UDTime2,
	 @UDTime3,
	 @UDTime4,
	 @UDLookup1,
	 @UDLookup2,
	 @UDLookup3,
	 @UDLookup4,
	 @UDInteger1,
	 @UDInteger2,
	 @UDInteger3,
	 @UDInteger4,
	 @UDText1,
	 @UDText2,
	 @UDText3,
	 @UDText4,
	 @UDSmallText1, 
	 @UDSmallText2, 
	 @UDSmallText3, 
	 @UDSmallText4,
	 @UDDate5, 
	 @UDTime5, 
	 @UDLookup5, 
	 @UDInteger5, 
	 @UDText5, 
 	 @UDSmallText5)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [I_REC_Notes]
	(@LogID 	[int],
	 @AppID 	[int],
	 @FldID		[int],
	 @RecordID 	[int],
	 @LogNote 	[varchar](2500),
	 @LogDate 	[datetime],
	 @LogTime 	[datetime],
	 @LogCoder 	[int])

AS
SELECT @LogID = (SELECT ISNULL(MAX(LogID), 0) FROM REC_Notes) + 1
INSERT INTO [dbo].[REC_Notes] 
	 ([LogID],
	 [AppID],
	 [FieldID],
	 [RecordID],
	 [LogNote],
	 [LogDate],
	 [LogTime],
	 [LogCoder]) 
 
VALUES 
	(@LogID,
	 @AppID,
	 @FldID,
	 @RecordID,
	 @LogNote,
	 @LogDate,
	 @LogTime,
	 @LogCoder)

RETURN @LogID



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [I_REC_Notes_OMHRS_Reporting]
    @AbstractID int
as
    delete from REC_Notes_OMHRS_Reporting where AbstractID = @AbstractID

    Create table #zzREC_Notes_OMHRS_Reporting(
        RecordID int, 
        FieldID  int, 
        LogNote  varchar(2500) COLLATE Latin1_General_CI_AS NULL ,
        LogDate  datetime, 
        LogTime  datetime, 
        LogBy    varchar(250) COLLATE Latin1_General_CI_AS NULL ,
        code     int identity(1, 1),
        occurrence int default 0)

    insert into #zzREC_Notes_OMHRS_Reporting(RecordID, FieldID, LogNote, LogDate, LogTime, LogBy)
    select RecordID, FieldID, LogNote, LogDate, LogTime, 
        LogBy = isnull(u.DisplayCode, '') + ' - ' + isnull(u.userdescription, '')
    from dbo.REC_Notes n
        left join u_users u on n.LogCoder = u.code
    where FieldID in (8528,8534,8522,8506,8554,8548,8550,8552,8508,8556,8538,8532,8520,8514,8536,8544,
        8546,8526,8540,8524,8530,8510,8504,8542,8512,8518,8502,8516)
        and AppID between 650 and 654
        and RecordID = @AbstractID
    order by FieldID, LogDate, LogTime

    update #zzREC_Notes_OMHRS_Reporting
    set occurrence = code - minid + 1
    from #zzREC_Notes_OMHRS_Reporting z
        inner join (select RecordID, FieldID, min(code) as minid
                from #zzREC_Notes_OMHRS_Reporting
                group by RecordID, FieldID) m on z.RecordID = m.RecordID and z.FieldID = m.FieldID

    insert into dbo.REC_Notes_OMHRS_Reporting(AcuteControlMedicationNotes, AcuteControlMedicationLogDate, AcuteControlMedicationLogTime, AcuteControlMedicationLogBy, AddictiveBehavioursNotes, AddictiveBehavioursLogDate, AddictiveBehavioursLogTime, AddictiveBehavioursLogBy, AdherenceNotes, AdherenceLogLogDate, AdherenceLogLogTime, AdherenceLogLogBy, AbuseByOthersNotes, AbuseByOthersLogDate, AbuseByOthersLogTime, AbuseByOthersLogBy, 
        BehaviourDisturbanceNotes, BehaviourDisturbanceLogDate, BehaviourDisturbanceLogTime, BehaviourDisturbanceLogBy, BladderBowelFunctioningNotes, BladderBowelFunctioningLogDate, BladderBowelFunctioningLogTime, BladderBowelFunctioningLogBy, CognitionNotes, CognitionLogDate, CognitionLogtime, CognitionLogBy, CommunicationDisorderNotes, CommunicationDisorderLogDate, CommunicationDisorderLogTime, CommunicationDisorderLogBy, 
        CriminalActivityNotes, CriminalActivityLogDate, CriminalActivityLogTime, CriminalActivityLogBy, DecisionalIntegrityNotes, DecisionalIntegrityLogDate, DecisionalIntegrityLogTime, DecisionalIntegrityLogBy, DehydrationNotes, DehydrationLogDate, DehydrationLogTime, DehydrationLogBy, DischargeResourcesNotes, DischargeResourcesLogDate, DischargeResourcesLogTime, DischargeResourcesLogBy, 
        EconomicStatusNotes, EconomicStatusLogDate, EconomicStatusLogTime, EconomicStatusLogBy, InterpersonalConflictNotes, InterpersonalConflictLogDate, InterpersonalConflictLogtime, InterpersonalConflictLogBy, NutritionNotes, NutritionLogDate, NutritionLogTime, NutritionLogBy, OralHealthNotes, OralHealthLogDate, OralHealthLogTime, OralHealthLogBy, PainNotes, PainLogDate, PainLogTime, PainLogBy, 
        PhysicalRestraintSeclusionNote, PhysicalRestraintSeclusionDate, PhysicalRestraintSeclusionTime, PhysicalRestraintSeclusionBy, PolydipsiaNotes, PolydipsiaLogDate, PolydipsiaLogTime, PolydipsiaLogBy, PsychotropicDrugReviewNotes, PsychotropicDrugReviewLogDate, PsychotropicDrugReviewLogTime, PsychotropicDrugReviewLogBy, RevolvingDoorNotes, RevolvingDoorLogDate, RevolvingDoorLogTime, RevolvingDoorLogBy, 
        SelfCareNotes, SelfCareLogDate, SelfCareLogTime, SelfCareLogBy, SelfHarmNotes, SelfHarmLogDate, SelfHarmLogTime, SelfHarmLogBy, SkinFootConditionsNotes, SkinFootConditionsLogDate, SkinFootConditionsLogTime, SkinFootConditionsLogBy, SocialFunctionNotes, SocialFunctionLogDate, SocialFunctionLogTime, SocialFunctionLogBy, SupportSystemsNotes, SupportSystemsLogDate, SupportSystemsLogTime, SupportSystemsLogBy, 
        ViolenceNotes, ViolenceLogDate, ViolenceLogTime, ViolenceLogBy, VocationalRehabilitationNotes, VocationalRehabilitationDate, VocationalRehabilitationTime, VocationalRehabilitationBy, AbstractID, Occurrence)
    select
        AcuteControlMedicationNotes   = LU_AcuteControlMedicationNotes.LogNote,
        AcuteControlMedicationLogDate = LU_AcuteControlMedicationNotes.LogDate,
        AcuteControlMedicationLogTime = LU_AcuteControlMedicationNotes.LogTime,
        AcuteControlMedicationLogBy   = LU_AcuteControlMedicationNotes.LogBy,
    
        AddictiveBehavioursNotes      = LU_AddictiveBehavioursNotes.LogNote,
        AddictiveBehavioursLogDate    = LU_AddictiveBehavioursNotes.LogDate,
        AddictiveBehavioursLogTime    = LU_AddictiveBehavioursNotes.LogTime,
        AddictiveBehavioursLogBy      = LU_AddictiveBehavioursNotes.LogBy,
    
        AdherenceNotes                = LU_AdherenceNotes.LogNote,
        AdherenceLogLogDate           = LU_AdherenceNotes.LogDate,
        AdherenceLogLogTime           = LU_AdherenceNotes.LogTime,
        AdherenceLogLogBy             = LU_AdherenceNotes.LogBy,
    
        AbuseByOthersNotes            = LU_AbuseByOthersNotes.LogNote,
        AbuseByOthersLogDate          = LU_AbuseByOthersNotes.LogDate,
        AbuseByOthersLogTime          = LU_AbuseByOthersNotes.LogTime,
        AbuseByOthersLogBy            = LU_AbuseByOthersNotes.LogBy,
    
        BehaviourDisturbanceNotes     = LU_BehaviourDisturbanceNotes.LogNote,
        BehaviourDisturbanceLogDate   = LU_BehaviourDisturbanceNotes.LogDate,
        BehaviourDisturbanceLogTime   = LU_BehaviourDisturbanceNotes.LogTime,
        BehaviourDisturbanceLogBy     = LU_BehaviourDisturbanceNotes.LogBy,
    
        BladderBowelFunctioningNotes  = LU_BladderBowelFunctioningNotes.LogNote,
        BladderBowelFunctioningLogDate= LU_BladderBowelFunctioningNotes.LogDate,
        BladderBowelFunctioningLogTime= LU_BladderBowelFunctioningNotes.LogTime,
        BladderBowelFunctioningLogBy  = LU_BladderBowelFunctioningNotes.LogBy,
    
        CognitionNotes                = LU_CognitionNotes.LogNote,
        CognitionLogDate              = LU_CognitionNotes.LogDate,
        CognitionLogtime              = LU_CognitionNotes.LogTime,
        CognitionLogtime              = LU_CognitionNotes.LogBy,
    
        CommunicationDisorderNotes    = LU_CommunicationDisorderNotes.LogNote,
        CommunicationDisorderLogDate  = LU_CommunicationDisorderNotes.LogDate,
        CommunicationDisorderLogTime  = LU_CommunicationDisorderNotes.LogTime,
        CommunicationDisorderLogBy    = LU_CommunicationDisorderNotes.LogBy,
    
        CriminalActivityNotes         = LU_CriminalActivityNotes.LogNote,
        CriminalActivityLogDate       = LU_CriminalActivityNotes.LogDate,
        CriminalActivityLogTime       = LU_CriminalActivityNotes.LogTime,
        CriminalActivityLogBy         = LU_CriminalActivityNotes.LogBy,
    
        DecisionalIntegrityNotes      = LU_DecisionalIntegrityNotes.LogNote,
        DecisionalIntegrityLogDate    = LU_DecisionalIntegrityNotes.LogDate,
        DecisionalIntegrityLogTime    = LU_DecisionalIntegrityNotes.LogTime,
        DecisionalIntegrityLogBy      = LU_DecisionalIntegrityNotes.LogBy,
    
        DehydrationNotes              = LU_DehydrationNotes.LogNote,
        DehydrationLogDate            = LU_DehydrationNotes.LogDate,
        DehydrationLogTime            = LU_DehydrationNotes.LogTime,
        DehydrationLogBy              = LU_DehydrationNotes.LogBy,
    
        DischargeResourcesNotes       = LU_DischargeResourcesNotes.LogNote,
        DischargeResourcesLogDate     = LU_DischargeResourcesNotes.LogDate,
        DischargeResourcesLogTime     = LU_DischargeResourcesNotes.LogTime,
        DischargeResourcesLogBy       = LU_DischargeResourcesNotes.LogBy,
    
        EconomicStatusNotes           = LU_EconomicStatusNotes.LogNote,
        EconomicStatusLogDate         = LU_EconomicStatusNotes.LogDate,
        EconomicStatusLogTime         = LU_EconomicStatusNotes.LogTime,
        EconomicStatusLogBy           = LU_EconomicStatusNotes.LogBy,
    
        InterpersonalConflictNotes    = LU_InterpersonalConflictNotes.LogNote,
        InterpersonalConflictLogDate  = LU_InterpersonalConflictNotes.LogDate,
        InterpersonalConflictLogtime  = LU_InterpersonalConflictNotes.LogTime,
        InterpersonalConflictLogBy    = LU_InterpersonalConflictNotes.LogBy,
    
        NutritionNotes                = LU_NutritionNotes.LogNote,
        NutritionLogDate              = LU_NutritionNotes.LogDate,
        NutritionLogTime              = LU_NutritionNotes.LogTime,
        NutritionLogBy                = LU_NutritionNotes.LogBy,
    
        OralHealthNotes               = LU_OralHealthNotes.LogNote,
        OralHealthLogDate             = LU_OralHealthNotes.LogDate,
        OralHealthLogTime             = LU_OralHealthNotes.LogTime,
        OralHealthLogBy               = LU_OralHealthNotes.LogBy,
    
        PainNotes                     = LU_PainNotes.LogNote,
        PainLogDate                   = LU_PainNotes.LogDate,
        PainLogTime                   = LU_PainNotes.LogTime,
        PainLogBy                     = LU_PainNotes.LogBy,
    
        PhysicalRestraintSeclusionNote= LU_PhysicalRestraintSeclusionNote.LogNote,
        PhysicalRestraintSeclusionDate= LU_PhysicalRestraintSeclusionNote.LogDate,
        PhysicalRestraintSeclusionTime= LU_PhysicalRestraintSeclusionNote.LogTime,
        PhysicalRestraintSeclusionBy  = LU_PhysicalRestraintSeclusionNote.LogBy,
    
        PolydipsiaNotes               = LU_PolydipsiaNotes.LogNote,
        PolydipsiaLogDate             = LU_PolydipsiaNotes.LogDate,
        PolydipsiaLogTime             = LU_PolydipsiaNotes.LogTime,
        PolydipsiaLogBy               = LU_PolydipsiaNotes.LogBy,
    
        PsychotropicDrugReviewNotes   = LU_PsychotropicDrugReviewNotes.LogNote,
        PsychotropicDrugReviewLogDate = LU_PsychotropicDrugReviewNotes.LogDate,
        PsychotropicDrugReviewLogTime = LU_PsychotropicDrugReviewNotes.LogTime,
         PsychotropicDrugReviewLogBy  = LU_PsychotropicDrugReviewNotes.LogBy,
    
        RevolvingDoorNotes            = LU_RevolvingDoorNotes.LogNote,
        RevolvingDoorLogDate          = LU_RevolvingDoorNotes.LogDate,
        RevolvingDoorLogTime          = LU_RevolvingDoorNotes.LogTime,
        RevolvingDoorLogBy            = LU_RevolvingDoorNotes.LogBy,
    
        SelfCareNotes                 = LU_SelfCareNotes.LogNote,
        SelfCareLogDate               = LU_SelfCareNotes.LogDate,
        SelfCareLogTime               = LU_SelfCareNotes.LogTime,
        SelfCareLogBy                 = LU_SelfCareNotes.LogBy,
    
        SelfHarmNotes                 = LU_SelfHarmNotes.LogNote,
        SelfHarmLogDate               = LU_SelfHarmNotes.LogDate,
        SelfHarmLogTime               = LU_SelfHarmNotes.LogTime,
        SelfHarmLogBy                 = LU_SelfHarmNotes.LogBy,
    
        SkinFootConditionsNotes       = LU_SkinFootConditionsNotes.LogNote,
        SkinFootConditionsLogDate     = LU_SkinFootConditionsNotes.LogDate,
        SkinFootConditionsLogTime     = LU_SkinFootConditionsNotes.LogTime,
        SkinFootConditionsLogBy       = LU_SkinFootConditionsNotes.LogBy,
    
        SocialFunctionNotes           = LU_SocialFunctionNotes.LogNote,
        SocialFunctionLogDate         = LU_SocialFunctionNotes.LogDate,
        SocialFunctionLogTime         = LU_SocialFunctionNotes.LogTime,
        SocialFunctionLogBy           = LU_SocialFunctionNotes.LogBy,
    
        SupportSystemsNotes           = LU_SupportSystemsNotes.LogNote,
        SupportSystemsLogDate         = LU_SupportSystemsNotes.LogDate,
        SupportSystemsLogTime         = LU_SupportSystemsNotes.LogTime,
        SupportSystemsLogBy           = LU_SupportSystemsNotes.LogBy,
    
        ViolenceNotes                 = LU_ViolenceNotes.LogNote,
        ViolenceLogDate               = LU_ViolenceNotes.LogDate,
        ViolenceLogTime               = LU_ViolenceNotes.LogTime,
        ViolenceLogBy                 = LU_ViolenceNotes.LogBy,
    
        VocationalRehabilitationNotes = LU_VocationalRehabilitationNotes.LogNote,
        VocationalRehabilitationDate  = LU_VocationalRehabilitationNotes.LogDate,
        VocationalRehabilitationTime  = LU_VocationalRehabilitationNotes.LogTime,
        VocationalRehabilitationBy    = LU_VocationalRehabilitationNotes.LogBy,
        r.AbstractID, r.Occurrence
    from (select distinct AbstractID = RecordID, Occurrence from #zzREC_Notes_OMHRS_Reporting) r left join
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8528) lu_AcuteControlMedicationNotes on r.AbstractID = lu_AcuteControlMedicationNotes.RecordID and r.occurrence = lu_AcuteControlMedicationNotes.occurrence left join
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8534) lu_AddictiveBehavioursNotes on LU_AddictiveBehavioursNotes.RecordID = r.AbstractID and r.occurrence = LU_AddictiveBehavioursNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8522) lu_AdherenceNotes on lu_AdherenceNotes.RecordID = r.AbstractID and r.occurrence = lu_AdherenceNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8506) lu_AbuseByOthersNotes on lu_AbuseByOthersNotes.RecordID = r.AbstractID and r.occurrence = lu_AbuseByOthersNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8554) lu_BehaviourDisturbanceNotes on lu_BehaviourDisturbanceNotes.RecordID = r.AbstractID and r.occurrence = lu_BehaviourDisturbanceNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8548) lu_BladderBowelFunctioningNotes on lu_BladderBowelFunctioningNotes.RecordID = r.AbstractID and r.occurrence = lu_BladderBowelFunctioningNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8550) lu_CognitionNotes on lu_CognitionNotes.RecordID = r.AbstractID and r.occurrence = lu_CognitionNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8552) lu_CommunicationDisorderNotes on LU_CommunicationDisorderNotes.RecordID = r.AbstractID and r.occurrence = lu_CommunicationDisorderNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8508) lu_CriminalActivityNotes on lu_CriminalActivityNotes.RecordID = r.AbstractID and r.occurrence = lu_CriminalActivityNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8556) lu_DecisionalIntegrityNotes on lu_DecisionalIntegrityNotes.RecordID = r.AbstractID and r.occurrence = lu_DecisionalIntegrityNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8538) lu_DehydrationNotes on lu_DehydrationNotes.RecordID = r.AbstractID and r.occurrence = lu_DehydrationNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8532) lu_DischargeResourcesNotes on lu_DischargeResourcesNotes.RecordID = r.AbstractID and r.occurrence = lu_DischargeResourcesNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8520) lu_EconomicStatusNotes on lu_EconomicStatusNotes.RecordID = r.AbstractID and r.occurrence = lu_EconomicStatusNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8514) lu_InterpersonalConflictNotes on lu_InterpersonalConflictNotes.RecordID = r.AbstractID and r.occurrence = lu_InterpersonalConflictNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8536) lu_NutritionNotes on lu_NutritionNotes.RecordID = r.AbstractID and r.occurrence = lu_NutritionNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8544) lu_OralHealthNotes on lu_OralHealthNotes.RecordID = r.AbstractID and r.occurrence = lu_OralHealthNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8546) lu_PainNotes on lu_PainNotes.RecordID = r.AbstractID and r.occurrence = lu_PainNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8526) lu_PhysicalRestraintSeclusionNote on lu_PhysicalRestraintSeclusionNote.RecordID = r.AbstractID and r.occurrence = lu_PhysicalRestraintSeclusionNote.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8540) LU_PolydipsiaNotes on LU_PolydipsiaNotes.RecordID = r.AbstractID and r.occurrence = LU_PolydipsiaNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8524) lu_PsychotropicDrugReviewNotes on LU_PsychotropicDrugReviewNotes.RecordID = r.AbstractID and r.occurrence = lu_PsychotropicDrugReviewNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8530) lu_RevolvingDoorNotes on lu_RevolvingDoorNotes.RecordID = r.AbstractID and r.occurrence = lu_RevolvingDoorNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8510) lu_SelfCareNotes on lu_SelfCareNotes.RecordID = r.AbstractID and r.occurrence = lu_SelfCareNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8504) lu_SelfHarmNotes on lu_SelfHarmNotes.RecordID = r.AbstractID and r.occurrence = lu_SelfHarmNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8542) lu_SkinFootConditionsNotes on lu_SkinFootConditionsNotes.RecordID = r.AbstractID and r.occurrence = lu_SkinFootConditionsNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8512) lu_SocialFunctionNotes on lu_SocialFunctionNotes.RecordID = r.AbstractID and r.occurrence = lu_SocialFunctionNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8518) lu_SupportSystemsNotes on lu_SupportSystemsNotes.RecordID = r.AbstractID and r.occurrence = lu_SupportSystemsNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8502) lu_ViolenceNotes on lu_ViolenceNotes.RecordID = r.AbstractID and r.occurrence = lu_ViolenceNotes.occurrence left join 
    (select * from #zzREC_Notes_OMHRS_Reporting where FieldID = 8516) lu_VocationalRehabilitationNotes on lu_VocationalRehabilitationNotes.RecordID = r.AbstractID and r.occurrence = lu_VocationalRehabilitationNotes.occurrence

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_REC_Purge]
	(@AppID        [int],
	 @RecordID     	[int],
	 @CareType    	[varchar](50),
	 @ICDType     	[varchar](50),
	 @InstNumber 	[varchar](50),
	 @ChartNumber 	[varchar](50),
	 @FullName     	[varchar](100),
	 @EncounterNumber 	    [varchar](50),
	 @EncounterSequence 	[varchar](50),
	 @VisitDate    	[datetime],
	 @VisitTime    	[datetime],
	 @CIHIDateSent  [datetime], 
	 @BatchYear 		[varchar](50), 
	 @BatchPeriod 		[varchar](50), 
	 @BatchNumber 	[varchar](50), 
	 @AbstNumber 		[varchar](50), 
	 @IsCompleted 		[varchar](50), 
	 @IsValidated 		[varchar](50), 
	 @IsSubmitted 		[varchar](50), 
	 @IsCorrected 		[varchar](50),
	 @DeleteCoder   [varchar](50),
	 @DeleteDate 	[datetime],
	 @DeleteTime 	[datetime],
	 @PurgeCoder 	[varchar](50),
	 @PurgeDate 	[datetime],
	 @PurgeTime 	[datetime])
AS 
INSERT INTO [dbo].[REC_Purge] 
	 ([AppID],
	 [RecordID],
	 [CareType],
	 [ICDType],
	 [InstNumber],
	 [ChartNumber],
	 [FullName],
	 [EncounterNumber],
	 [EncounterSequence],
	 [VisitDate],
	 [VisitTime],
	 [CIHIDateSent], 
	 [BatchYear], 
	 [BatchPeriod], 
	 [BatchNumber], 
	 [AbstNumber], 
	 [IsCompleted], 
	 [IsValidated], 
	 [IsSubmitted], 
	 [IsCorrected],
	 [DeleteCoder],
	 [DeleteDate],
	 [DeleteTime],
	 [PurgeCoder],
	 [PurgeDate],
	 [PurgeTime]) 
VALUES 
	(@AppID,
	 @RecordID,
	 @CareType,
	 @ICDType,
	 @InstNumber,
	 @ChartNumber,
	 @FullName,
	 @EncounterNumber,
	 @EncounterSequence,
	 @VisitDate,
	 @VisitTime,
	 @CIHIDateSent, 
	 @BatchYear, 
	 @BatchPeriod, 
	 @BatchNumber, 
	 @AbstNumber, 
	 @IsCompleted, 
	 @IsValidated, 
	 @IsSubmitted, 
	 @IsCorrected,
	 @DeleteCoder,
	 @DeleteDate,
	 @DeleteTime,
	 @PurgeCoder,
	 @PurgeDate,
	 @PurgeTime)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [I_RH_Activity]
    @AbstractID           int,
    @Eating               int,
    @Grooming             int,
    @Bathing              int,
    @DressUpper           int,
    @DressLower           int,
    @Toileting            int,
    @Bladder              int,
    @Bowel                int,
    @BedTransfer          int,
    @ToiletTransfer       int,
    @ShowerTransfer       int,
    @Walk                 int,
    @WalkMode             int,
    @Stairs               int,
    @Comprehension        int,
    @ComprehensionMode    int,
    @Expression           int,
    @ExpressionMode       int,
    @SocialInteract       int,
    @ProblemSolve         int,
    @Memory               int,
    @PainPresence         int,
    @PainIntensity        int,
    @PainImpact           int,
    @MealPreparation      int,
    @HouseworkLight       int,
    @HouseworkHeavy       int,
    @ImpairmentPresence   int,
    @VerbalCom            int,
    @WrittenCom           int,
    @AuditoryCom          int,
    @ReadingCom           int,
    @FinanceMange         int,
    @Orientation          int,
    @HealthStatRespondent int,
    @HealthStatus         int,
    @PainScale            int,
    @GlassHear 		int	

AS 
INSERT INTO dbo.RH_Activity (
    AbstractID,
    Eating,
    Grooming,
    Bathing,
    DressUpper,
    DressLower,
    Toileting,
    Bladder,
    Bowel,
    BedTransfer,
    ToiletTransfer,
    ShowerTransfer,
    Walk,
    WalkMode,
    Stairs,
    Comprehension,
    ComprehensionMode,
    Expression,
    ExpressionMode,
    SocialInteract,
    ProblemSolve,
    Memory,
    PainPresence,
    PainIntensity,
    PainImpact,
    MealPreparation,
    HouseworkLight,
    HouseworkHeavy,
    ImpairmentPresence,
    VerbalCom,
    WrittenCom,
    AuditoryCom,
    ReadingCom,
    FinanceManage,
    Orientation,
    HealthStatRespondent,
    HealthStatus,
    PainScale,
    GlassHear
) VALUES (
    @AbstractID,
    @Eating,
    @Grooming,
    @Bathing,
    @DressUpper,
    @DressLower,
    @Toileting,
    @Bladder,
    @Bowel,
    @BedTransfer,
    @ToiletTransfer,
    @ShowerTransfer,
    @Walk,
    @WalkMode,
    @Stairs,
    @Comprehension,
    @ComprehensionMode,
    @Expression,
    @ExpressionMode,
    @SocialInteract,
    @ProblemSolve,
    @Memory,
    @PainPresence,
    @PainIntensity,
    @PainImpact,
    @MealPreparation,
    @HouseworkLight,
    @HouseworkHeavy,
    @ImpairmentPresence,
    @VerbalCom,
    @WrittenCom,
    @AuditoryCom,
    @ReadingCom,
    @FinanceMange,
    @Orientation,
    @HealthStatRespondent,
    @HealthStatus,
    @PainScale,
    @GlassHear 
)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [I_RH_Administrative]
	(@AbstractID		[int],
	 @AdmitClass		[int],
	 @ReAdmit		[int],
	 @PlanReAdmit	 	[int],
	 @ReadyAdmitKnown 	[int],
	 @ReadyAdmitDate 	[datetime],
	 @DateReadyDischarge 	[datetime],
	 @DischReason 	[int],
	 @ReferredFrom 	[int],
	 @ReferralProvince 	[int],
	 @InstitutionFrom 	[int],
	 @ReferredTo	 	[int],
	 @ReferredProvince 	[int],
	 @InstitutionTo	 	[int],
	 @TherapyDate 		[datetime],
	 @RP_ProvincePlan 	[int],
	 @RP_WCB_WSIB 	[int],
	 @RP_OtherProvince 	[int],
	 @RP_Fed_DVA 	[int],
	 @RP_Fed_FNIHB 	[int],
	 @RP_Fed_Other 	[int],
	 @RP_CanadaSelf 	[int],
	 @RP_CanadaInsure 	[int],
	 @RP_OtherSelf 	[int],
	 @RP_ProvinceDefinition 	[int],
	 @PrimaryReasonWaiting  int,
	 @SecondaryReasonWaiting int)

AS INSERT INTO [dbo].[RH_Administrative] 
	 ([AbstractID],
	 [AdmitClass],
	 [ReAdmit],
	 [PlanReAdmit],
	 [ReadyAdmitKnown],
	 [ReadyAdmitDate],
	 [DateReadyDischarge],
	 [DischReason],
	 [ReferredFrom],
	 [ReferralProvince],
	 [InstitutionFrom],
	 [ReferredTo],
	 [ReferredProvince],
	 [InstitutionTo],
	 [TherapyDate],
	 [RP_ProvincePlan],
	 [RP_WCB_WSIB],
	 [RP_OtherProvince],
	 [RP_Fed_DVA],
	 [RP_Fed_FNIHB],
	 [RP_Fed_Other],
	 [RP_CanadaSelf],
	 [RP_CanadaInsure],
	 [RP_OtherSelf],
	 [RP_ProvinceDefinition],
	 [PrimaryReasonWaiting],
	 [SecondaryReasonWaiting]) 
 
VALUES 
	(@AbstractID,
	 @AdmitClass,
	 @ReAdmit,
	 @PlanReAdmit,
	 @ReadyAdmitKnown,
	 @ReadyAdmitDate,
	 @DateReadyDischarge,
	 @DischReason,
	 @ReferredFrom,
	 @ReferralProvince,
	 @InstitutionFrom,
	 @ReferredTo,
	 @ReferredProvince,
	 @InstitutionTo,
	 @TherapyDate,
	 @RP_ProvincePlan,
	 @RP_WCB_WSIB,
	 @RP_OtherProvince,
	 @RP_Fed_DVA,
	 @RP_Fed_FNIHB,
	 @RP_Fed_Other,
	 @RP_CanadaSelf,
	 @RP_CanadaInsure,
	 @RP_OtherSelf,
	 @RP_ProvinceDefinition,
	 @PrimaryReasonWaiting,
	 @SecondaryReasonWaiting)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_RH_Ancillary]
	(@AbstractID	 	[int],
	 @AncillaryField1 	[int],
	 @AncillaryField2 	[int],
	 @AncillaryField3 	[int],
	 @AncillaryField4 	[int],
	 @AncillaryField5 	[int],
	 @AncillaryField6 	[int],
	 @AncillaryField7 	[int],
	 @AncillaryField8 	[int],
	 @AncillaryField9 	[int],
	 @AncillaryField10 	[int],
	 @AncillaryField11 	[int],
	 @AncillaryField12 	[int],
	 @AncillaryField13 	[int],
	 @AncillaryField14 	[int],
	 @AncillaryField15 	[int],
	 @AncillaryField16 	[int],
	 @AncillaryField17 	[int])
AS 

INSERT INTO [RH_Ancillary] 
	 ( [AbstractID],
	 [AncillaryField1],
	 [AncillaryField2],
	 [AncillaryField3],
	 [AncillaryField4],
	 [AncillaryField5],
	 [AncillaryField6],
	 [AncillaryField7],
	 [AncillaryField8],
	 [AncillaryField9],
	 [AncillaryField10],
	 [AncillaryField11],
	 [AncillaryField12],
	 [AncillaryField13],
	 [AncillaryField14],
	 [AncillaryField15],
	 [AncillaryField16],
	 [AncillaryField17]) 
 
VALUES 
	(@AbstractID,
	 @AncillaryField1,
	 @AncillaryField2,
	 @AncillaryField3,
	 @AncillaryField4,
	 @AncillaryField5,
	 @AncillaryField6,
	 @AncillaryField7,
	 @AncillaryField8,
	 @AncillaryField9,
	 @AncillaryField10,
	 @AncillaryField11,
	 @AncillaryField12,
	 @AncillaryField13,
	 @AncillaryField14,
	 @AncillaryField15,
	 @AncillaryField16,
	 @AncillaryField17)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_RH_BasicOption]
	(@AbstractID 	[int],
	 @BasicOption1 	[int],
	 @BasicOption2 	[int],
	 @BasicOption3 	[int],
	 @BasicOption4 	[int],
	 @BasicOption5 	[int],
	 @BasicOption6 	[int],
	 @BasicOption7 	[int],
	 @BasicOption8 	[int],
	 @BasicOption9 	[int],
	 @BasicOption10 	[int],
	 @BasicOption11 	[int],
	 @BasicOption12 	[int],
	 @BasicOption13 	[int],
	 @BasicOption14 	[int],
	 @BasicOption15 	[int],
	 @BasicOption16 	[int],
	 @BasicOption17 	[int],
	 @BasicOption18 	[int],
	 @BasicOption19 	[int])
AS 

INSERT INTO [RH_BasicOption] 
	 ([AbstractID],
	 [BasicOption1],
	 [BasicOption2],
	 [BasicOption3],
	 [BasicOption4],
	 [BasicOption5],
	 [BasicOption6],
	 [BasicOption7],
	 [BasicOption8],
	 [BasicOption9],
	 [BasicOption10],
	 [BasicOption11],
	 [BasicOption12],
	 [BasicOption13],
	 [BasicOption14],
	 [BasicOption15],
	 [BasicOption16],
	 [BasicOption17],
	 [BasicOption18],
	 [BasicOption19]) 
 
VALUES 
	(@AbstractID,
	 @BasicOption1,
	 @BasicOption2,
	 @BasicOption3,
	 @BasicOption4,
	 @BasicOption5,
	 @BasicOption6,
	 @BasicOption7,
	 @BasicOption8,
	 @BasicOption9,
	 @BasicOption10,
	 @BasicOption11,
	 @BasicOption12,
	 @BasicOption13,
	 @BasicOption14,
	 @BasicOption15,
	 @BasicOption16,
	 @BasicOption17,
	 @BasicOption18,
	 @BasicOption19)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE   PROCEDURE [I_RH_ClientInfo]
	(@AbstractID 		[int],
	 @ICDType 		[char](1), 
	 @CareType 		[int],
	 @HospitalID		[int], 
	 @LinkID		[int],
	 @InstitutionNumber 	[int],
	 @AssessmentType 	[int],
	 @ProgramType 	[int],
	 @ChartNumber	 	[varchar](10),
	 @HealthCareNumber 	[varchar](12),
	 @HCNProvince		[int],
	 @AdmitDate	 	[datetime],
	 @DischargeDate 	[datetime],
	 @FollowUpDate 	[datetime],
	 @RespondentType 	[int],
	 @IsCompleted 		[int], 
	 @IsValidated 		[int], 
	 @IsSubmited 		[int], 
	 @IsCorrected 		[int], 
	 @IsDeleted 		[int], 
	 @CIHIDateSent 	[datetime], 
	 @BatchYear 		[int], 
	 @BatchPeriod 		[int], 
	 @AbstractNumber 	[int],
	 @EncounterNumber 	[varchar](20), 
	 @RegisterNumber 	[varchar](8),
	 @SiteNumber 		[int], 
	 @CoderNumber 	[int],
	 @LOSDays 		[int],
	 @HCNVersion 		[varchar](2),
	 @InterfaceDate 	[datetime], 
	 @InterfaceTime 	[datetime], 
	 @InterfaceCoder 	[int], 
	 @InputDate 		[datetime], 
	 @InputTime 		[datetime], 
	 @DataEntryCoder 	[int], 
	 @FinishDate 		[datetime], 
	 @FinishTime 		[datetime],
	 @Secret 		[int], 
	 @TSIDate 		[datetime], 
 	 @TSITime 		[datetime], 
	 @TSICoder 		[int],
	 @NextAssessDate	[datetime],
	 @SecondChartRegNumber [varchar](50), 
	 @MISCode 		[int], 
	 @AttendingPhysician 	[int], 
	 @RefPhysician 		[int], 
	 @AdmittingNurseArea 	[int],
	 @FixedChartNumber		[varchar](50),
	 @UniversalEpisodeIdentifier [varchar] (50),
	 @HospitalAccountRecord varchar(50)
	)
AS 
If isnull(@IsDeleted, 0) = 0   set @IsDeleted = 2   -- PR - 03723
If isnull(@IsCorrected, 0) = 0 set @IsCorrected = 1 -- PR - 03723
If isnull(@IsSubmited, 0) = 0  set @IsSubmited = 2  -- PR - 03723

SELECT @AbstractID = (SELECT ISNULL(MAX(AbstractID), 0) FROM RH_ClientInfo) + 1
IF @LinkID = 0 SET @LinkID = @AbstractID
INSERT INTO [dbo].[RH_ClientInfo] 
	 ([AbstractID],
	 [LinkID],
	 [HospitalID],
	 [ICDType], 
	 [CareType], 
	 [IsCorrected], 
	 [IsSubmited], 
	 [IsValidated], 
	 [IsCompleted], 
	 [IsDeleted], 
	 [CIHIDateSent], 
	 [BatchYear], 
	 [BatchPeriod], 
	 [AbstractNumber],
	 [InstitutionNumber],
	 [SiteNumber], 
	 [CoderNumber],
	 [AssessmentType],
	 [ProgramType],
	 [ChartNumber],
	 [HealthCareNumber],
	 [HCNVersion],
	 [HCNProvince],
	 [AdmitDate],
	 [DischargeDate],
	 [FollowUpDate],
	 [LOSDays],	
	 [RespondentType],
	 [EncounterNumber], 
	 [RegisterNumber],
	 [InterfaceDate], 
	 [InterfaceTime], 
 	 [InterfaceCoder], 
 	 [InputDate], 
	 [InputTime], 
	 [DataEntryCoder], 
	 [FinishDate], 
	 [FinishTime], 
	 [Secret], 
	 [TSIDate], 
	 [TSITime], 
	 [TSICoder],
	 [NextAssessDate],
	 [SecondChartRegNumber],
	 [MISCode],
	 [AttendingPhysician],
	 [RefPhysician],
	 [AdmittingNurseArea],
	 [FixedChartNumber],
	 [UniversalEpisodeIdentifier],
	 [HospitalAccountRecord]
	) 
VALUES 
	(@AbstractID,
	 @LinkID, 
	 @HospitalID,
	 @ICDType, 
	 @CareType, 
	 1, 
	 2, 
	 @IsValidated, 
	 @IsCompleted, 
	 2, 
	 @CIHIDateSent, 
	 @BatchYear, 
	 @BatchPeriod, 
	 @AbstractNumber,
	 @InstitutionNumber,
	 @SiteNumber, 
	 @CoderNumber,
	 @AssessmentType,
	 @ProgramType,
	 @ChartNumber,
	 @HealthCareNumber,
	 @HCNVersion,
	 @HCNProvince,
	 @AdmitDate,
	 @DischargeDate,
	 @FollowUpDate,
	 @LOSDays,	 
	 @RespondentType,
	 @EncounterNumber, 
	 @RegisterNumber,
	 @InterfaceDate, 
	 @InterfaceTime, 
	 @InterfaceCoder, 
	 @InputDate, 
	 @InputTime,
	 @DataEntryCoder, 	
	 @FinishDate, 
	 @FinishTime, 
	 @Secret, 
	 @TSIDate, 
	 @TSITime,
	 @TSICoder,
	 @NextAssessDate,
	 @SecondChartRegNumber,
	 @MISCode,
	 @AttendingPhysician,
	 @RefPhysician,
	 @AdmittingNurseArea,
	 @FixedChartNumber,
	 @UniversalEpisodeIdentifier,
	 @HospitalAccountRecord
	)

RETURN @AbstractID
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [I_RH_Demographic]
   (@AbstractID            [int],
    @Gender                [int],
    @BirthDate             [datetime],
    @BirthDateEstimated    [int],
    @LanguageCode  [int],
    @ResidenceCountry      [int],
    @PostalCode            [varchar](7),
    @Province              [int],
    @LivingSpouse  [int],
    @LivingFamily          [int],
    @LivingUnPaid  [int],
    @LivingPaid            [int],
    @LivingAlone           [int],
    @LivingHospital        [int],
    @LivingOther           [int],
    @LivingTemp            [int],
    @LivingSetting         [int],
    @InformalSupport       [int],
    @PaidFullTime          [int],
    @PaidPartTime  [int],
    @PaidAdjusted          [int],
    @UnPaidFullTime        [int],
    @UnPaidPartTime        [int],
    @UnPaidAdjusted        [int],
    @StudentFullTime       [int],
    @StudentPartTime       [int],
    @StudentAdjusted       [int],
    @UnEmployed            [int],
    @RetiredAge            [int],
    @RetiredDisable        [int],
    @VocationNone  [int],
    @MaidenName            [varchar](35),
    @LastName              [varchar](40),
    @MiddleName            [varchar](15),
    @FirstName             [varchar](35),
    @AgeCode               [int],
    @AgeNumber             [int],
    @LivingAcute 	[int],
    @LanguageISO 	[int],
    @AboriginalStatus [int],
    @ResidenceCode  [int])

AS 
INSERT INTO [dbo].[RH_Demographic] 
    ([AbstractID],
    [MaidenName],
    [LastName],
    [MiddleName],
    [FirstName],           
    [Gender],
    [BirthDate],
    [BirthDateEstimated],
    [AgeCode],
    [AgeNumber],
    [LanguageCode],
    [ResidenceCountry],
    [PostalCode],
    [Province],
    [LivingSpouse],
    [LivingFamily],
    [LivingUnPaid],
    [LivingPaid],
    [LivingAlone],
    [LivingHospital],
    [LivingOther],
    [LivingTemp],
    [LivingSetting],
    [InformalSupport],
    [PaidFullTime],
    [PaidPartTime],
    [PaidAdjusted],
    [UnPaidFullTime],
    [UnPaidPartTime],
    [UnPaidAdjusted],
    [StudentFullTime],
    [StudentPartTime],
    [StudentAdjusted],
    [UnEmployed],
    [RetiredAge],
    [RetiredDisable],
    [VocationNone],
    [LivingAcute],
    [LanguageISO],
    [AboriginalStatus],
    [ResidenceCode]) 
 
VALUES 
   (@AbstractID,
    @MaidenName,
    @LastName,
    @MiddleName,
    @FirstName,            
    @Gender,
    @BirthDate,
    @BirthDateEstimated,
    @AgeCode,
    @AgeNumber,
    @LanguageCode,
    @ResidenceCountry,
    @PostalCode,
    @Province,
    @LivingSpouse,
    @LivingFamily,
    @LivingUnPaid,
    @LivingPaid,
    @LivingAlone,
    @LivingHospital,
    @LivingOther,
    @LivingTemp,
    @LivingSetting,
    @InformalSupport,
    @PaidFullTime,
    @PaidPartTime,
    @PaidAdjusted,
    @UnPaidFullTime,
    @UnPaidPartTime,
    @UnPaidAdjusted,
    @StudentFullTime,
    @StudentPartTime,
    @StudentAdjusted,
    @UnEmployed,
    @RetiredAge,
    @RetiredDisable,
    @VocationNone,
    @LivingAcute,
    @LanguageISO,
    @AboriginalStatus,
    @ResidenceCode)

--PR-03507
	declare @LID as int 

	select @LID = LinkID from RH_ClientInfo where AbstractID = @AbstractID
	if @LID <> @AbstractID
	begin 
		select 
    			@MaidenName = [MaidenName],
    			@LastName = [LastName],
    			@MiddleName = [MiddleName],
    			@FirstName = [FirstName],           
    			@Gender = [Gender],
    			@BirthDate = [BirthDate],
    			@BirthDateEstimated = [BirthDateEstimated],
    			@AgeCode = [AgeCode],
    			@AgeNumber = [AgeNumber],
    			@LanguageCode = [LanguageCode],
    			@ResidenceCountry = [ResidenceCountry],
    			@PostalCode = [PostalCode], 
    			@Province = [Province], 
    			@LanguageISO = [LanguageISO],
    			@ResidenceCode = [ResidenceCode]
		from [RH_Demographic] 
		where AbstractID = @LID
	end

	update [RH_Demographic] set
		[MaidenName] = @MaidenName,
    		[LastName] = @LastName,
    		[MiddleName] = @MiddleName,
    		[FirstName] = @FirstName,           
    		[Gender] = @Gender,
    		[BirthDate] = @BirthDate,
    		[BirthDateEstimated] = @BirthDateEstimated,
    		[AgeCode] = @AgeCode,
    		[AgeNumber] = @AgeNumber,
    		[LanguageCode] = @LanguageCode,
    		[ResidenceCountry] = @ResidenceCountry,
    		--[PostalCode] = @PostalCode, --ED-02118
    		--[Province] = @Province, --ED-02118
    		[LanguageISO] = @LanguageISO
	where AbstractID in (select AbstractID from RH_ClientInfo where LinkID = @LID)

	--ED-02118 (exclude Follow-Up)
	update [RH_Demographic] 
	set		[PostalCode] = @PostalCode, 
    		[Province] = @Province,
    		[ResidenceCode] = @ResidenceCode
	where AbstractID in (select AbstractID from RH_ClientInfo where AssessmentType <> 136 and LinkID = @LID)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_RH_Diagnosis]
	(@AbstractID	 	[int],
	 @DiagnosisOccurrence 	[int],
	 @DiagnosisCode 	[int],
	 @DiagnosisType 	[int],
	 @DiagnosisICD 	[int])

AS 
INSERT INTO [dbo].[RH_Diagnosis] 
	 ([AbstractID],
	 [DiagnosisOccurrence],
	 [DiagnosisCode],
	 [DiagnosisType],
	 [DiagnosisICD]) 
VALUES 
	(@AbstractID,
	 @DiagnosisOccurrence,
	 @DiagnosisCode,
	 @DiagnosisType,
	 @DiagnosisICD)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_RH_FollowUpAssess]
	(@AbstractID 		[int],
	 @LivingQuarters 	[int],
	 @Community		[int],
	 @TownTrips	 	[int],
	 @SelfCare		[int],
	 @WorkActivity	 	[int],
	 @Recreational	 	[int],
	 @SocialActivity	 	[int],
	 @FamilyRole		[int],
	 @PersonalRelation 	[int],
	 @PersonalComfort 	[int],
	 @LifeEvents	 	[int])

AS 
INSERT INTO [dbo].[RH_FollowUpAssess] 
	 ([AbstractID],
	 [LivingQuarters],
	 [Community],
	 [TownTrips],
	 [SelfCare],
	 [WorkActivity],
	 [Recreational],
	 [SocialActivity],
	 [FamilyRole],
	 [PersonalRelation],
	 [PersonalComfort],
	 [LifeEvents]) 
 
VALUES 
	(@AbstractID,
	 @LivingQuarters,
	 @Community,
	 @TownTrips,
	 @SelfCare,
	 @WorkActivity,
	 @Recreational,
	 @SocialActivity,
	 @FamilyRole,
	 @PersonalRelation,
	 @PersonalComfort,
	 @LifeEvents)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_RH_Health]
	(@AbstractID		[int],
	 @ClientGroup	 	[int],
	 @ASIAScale		[int],
	 @DateOnset		[datetime],
	 @Height	 	[varchar](7),
	 @Weight		[varchar](7),
	 @HospDischarge 	[int],
	 @HospDays	 	[int],
	 @WrittenConditionMain 	[varchar](50),
	 @WrittenCondition1 	[varchar](50),
	 @WrittenCondition2 	[varchar](50),
	 @WrittenCondition3 	[varchar](50),
	 @WrittenConditionTrans	[varchar](50))

AS 
INSERT INTO [dbo].[RH_Health] 
	 ([AbstractID],
	 [ClientGroup],
	 [ASIAScale],
	 [DateOnset],
	 [Height],
	 [Weight],
	 [HospDischarge],
	 [HospDays],
	 [WrittenConditionMain],
	 [WrittenCondition1],
	 [WrittenCondition2],
	 [WrittenCondition3],
	 [WrittenConditionTrans]) 
 
VALUES 
	(@AbstractID,
	 @ClientGroup,
	 @ASIAScale,
	 @DateOnset,
	 @Height,
	 @Weight,
	 @HospDischarge,
	 @HospDays,
	 @WrittenConditionMain,
	 @WrittenCondition1,
	 @WrittenCondition2,
	 @WrittenCondition3,
	 @WrittenConditionTrans)
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [I_RH_Intervention]
	(@AbstractID	 		[int],
	 @IntervICDType 		[varchar](1),
	 @IntervOccurrence 		[int],
	 @IntervDate	 		[datetime],
	 @IntervCode	 		[int],
	 @IntervAttribStatus 		[int],
	 @IntervAttribLocation 		[int],
	 @IntervAttribExtent 		[int],
	 @IntervOOHIndicator 		[int],
	 @IntervOOHInstitution 		[int],
	 @IntervProviderNumber		[int],
	 @IntervProviderService 		[int],
	 @IntervTissueCode 		[int],
	 @IntervDateIn			[datetime],
	 @IntervTimeIn	 		[datetime],
	 @IntervDateOut 		[datetime],
	 @IntervTimeOut 		[datetime],
	 @IntervTimeMinutes 		[varchar](10),
	 @IntervLocation 		[int],
	 @IntervAnaestID 		[int],
	 @IntervAnaestTechnique	[int],
	 @IntervUnplanReturn		[int])
AS 

INSERT INTO [RH_Intervention] 
	 ([AbstractID],
	 [IntervOccurrence],
	 [IntervICDType],
	 [IntervDate],
	 [IntervCode],
	 [IntervAttribStatus],
	 [IntervAttribLocation],
	 [IntervAttribExtent],
	 [IntervOOHIndicator],
	 [IntervOOHInstitution],
	 [IntervProviderNumber],
	 [IntervProviderService],
	 [IntervTissueCode],
	 [IntervDateIn],
	 [IntervTimeIn],
	 [IntervDateOut],
	 [IntervTimeOut],
	 [IntervTimeMinutes],
	 [IntervLocation],
	 [IntervAnaestID],
	 [IntervAnaestTechnique],
	 [IntervUnplanReturn]) 
 
VALUES 
	(@AbstractID,
	 @IntervOccurrence,
	 @IntervICDType,
	 @IntervDate,
	 @IntervCode,
	 @IntervAttribStatus,
	 @IntervAttribLocation,
	 @IntervAttribExtent,
	 @IntervOOHIndicator,
	 @IntervOOHInstitution,
	 @IntervProviderNumber,
	 @IntervProviderService,
	 @IntervTissueCode,
	 @IntervDateIn,
	 @IntervTimeIn,
	 @IntervDateOut,
	 @IntervTimeOut,
	 @IntervTimeMinutes,
	 @IntervLocation,
	 @IntervAnaestID,
	 @IntervAnaestTechnique,
	 @IntervUnplanReturn)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_RH_Project]
	(@AbstractID	 	[int],
	 @ProjectOccurrence	[int],
	 @ProjectNumber	[int],
	 @Question1		[int],
	 @Question2	 	[int],
	 @Question3	 	[int],
	 @Question4	 	[int],
	 @Question5		[int],
	 @Question6		[int],
	 @Question7	 	[int],
	 @Question8	 	[int],
	 @Question9	 	[int],
	 @Question10	 	[int],
	 @Question11	 	[int],
	 @Question12		[int],
	 @Question13	 	[int],
	 @Question14	 	[varchar](10),
	 @Question15	 	[varchar](10),
	 @Question16	 	[varchar](10),
	 @Question17	 	[varchar](10))
AS 

INSERT INTO [RH_Project] 
	 ([AbstractID],
	 [ProjectOccurrence],
	 [ProjectNumber],
	 [Question1],
	 [Question2],
	 [Question3],
	 [Question4],
	 [Question5],
	 [Question6],
	 [Question7],
	 [Question8],
	 [Question9],
	 [Question10],
	 [Question11],
	 [Question12],
	 [Question13],
	 [Question14],
	 [Question15],
	 [Question16],
	 [Question17]) 
 
VALUES 
	(@AbstractID,
	 @ProjectOccurrence,
	 @ProjectNumber,
	 @Question1,
	 @Question2,
	 @Question3,
	 @Question4,
	 @Question5,
	 @Question6,
	 @Question7,
	 @Question8,
	 @Question9,
	 @Question10,
	 @Question11,
	 @Question12,
	 @Question13,
	 @Question14,
	 @Question15,
	 @Question16,
	 @Question17)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_RH_Provider]
	(@AbstractID	 	[int],
	 @ProviderOccurrence 	[int],
	 @ProviderType 	[int],
	 @ProviderNumber 	[int])

AS 
INSERT INTO [dbo].[RH_Provider] 
	 ([AbstractID],
	 [ProviderOccurrence],
	 [ProviderType],
	 [ProviderNumber]) 
VALUES 
	(@AbstractID,
	 @ProviderOccurrence,
	 @ProviderType,
	 @ProviderNumber)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_RH_Rehabilitation]
	(@AbstractID	 	[int],
	 @ST_Screening 	[int],
	 @SD_Screening 	[int],
	 @ST_Initial	 	[int],
	 @SD_Initial	 	[int],
	 @ST_ReAssess 	[int],
	 @SD_ReAssess 	[int],
	 @ST_Planning	 	[int],
	 @SD_Planning	 	[int],
	 @ST_Cognitive 	[int],
	 @SD_Cognitive 	[int],
	 @ST_Communicate 	[int],
	 @SD_Communicate 	[int],
	 @ST_Nutrition	 	[int],
	 @SD_Nutrition	 	[int],
	 @ST_Physical	 	[int],
	 @SD_Physical	 	[int],
	 @ST_PsychoSocial 	[int],
	 @SD_PsychoSocial 	[int],
	 @ST_Vocational 	[int],
	 @SD_Vocational 	[int],
	 @ST_Manual	 	[int],
	 @SD_Manual	 	[int],
	 @ST_Modalities 	[int],
	 @SD_Modalities 	[int],
	 @ST_Injections 	[int],
	 @SD_Injections 	[int],
	 @ST_Social	 	[int],
	 @SD_Social	 	[int],
	 @ST_Equipment 	[int],
	 @SD_Equipment 	[int],
	 @ST_Education	[int],
	 @SD_Education	[int],
	 @ST_Consultation 	[int],
	 @SD_Consultation 	[int])

AS 
INSERT INTO [dbo].[RH_Rehabilitation] 
	 ([AbstractID],
	 [ST_Screening],
	 [SD_Screening],
	 [ST_Initial],
	 [SD_Initial],
	 [ST_ReAssess],
	 [SD_ReAssess],
	 [ST_Planning],
	 [SD_Planning],
	 [ST_Cognitive],
	 [SD_Cognitive],
	 [ST_Communicate],
	 [SD_Communicate],
	 [ST_Nutrition],
	 [SD_Nutrition],
	 [ST_Physical],
	 [SD_Physical],
	 [ST_PsychoSocial],
	 [SD_PsychoSocial],
	 [ST_Vocational],
	 [SD_Vocational],
	 [ST_Manual],
	 [SD_Manual],
	 [ST_Modalities],
	 [SD_Modalities],
	 [ST_Injections],
	 [SD_Injections],
	 [ST_Social],
	 [SD_Social],
	 [ST_Equipment],
	 [SD_Equipment],
	 [ST_Education],
	 [SD_Education],
	 [ST_Consultation],
	 [SD_Consultation]) 
 
VALUES 
	(@AbstractID,
	 @ST_Screening,
	 @SD_Screening,
	 @ST_Initial,
	 @SD_Initial,
	 @ST_ReAssess,
	 @SD_ReAssess,
	 @ST_Planning,
	 @SD_Planning,
	 @ST_Cognitive,
	 @SD_Cognitive,
	 @ST_Communicate,
	 @SD_Communicate,
	 @ST_Nutrition,
	 @SD_Nutrition,
	 @ST_Physical,
	 @SD_Physical,
	 @ST_PsychoSocial,
	 @SD_PsychoSocial,
	 @ST_Vocational,
	 @SD_Vocational,
	 @ST_Manual,
	 @SD_Manual,
	 @ST_Modalities,
	 @SD_Modalities,
	 @ST_Injections,
	 @SD_Injections,
	 @ST_Social,
	 @SD_Social,
	 @ST_Equipment,
	 @SD_Equipment,
	 @ST_Education,
	 @SD_Education,
	 @ST_Consultation,
	 @SD_Consultation)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE  PROCEDURE [I_RH_ServiceInterupt]
	(@AbstractID	 	[int],
	 @InteruptOccurrence 	[int],
	 @InteruptStartDate 	[datetime],
	 @InteruptReturnDate 	[datetime],
	 @InteruptReason	[int],
	 @InteruptTransfer 	[int],
	 @InteruptLOS 		[int],
	 @InteruptReasonICD 	[int])

AS 

--ED-01557
--INSERT INTO [dbo].[RH_ServiceInterupt] ([AbstractID], [InteruptOccurrence], [InteruptStartDate], [InteruptReturnDate], [InteruptReason], [InteruptTransfer], [InteruptLOS], [InteruptReasonICD]) VALUES (@AbstractID, @InteruptOccurrence, @InteruptStartDate, @InteruptReturnDate, @InteruptReason, @InteruptTransfer, @InteruptLOS, @InteruptReasonICD)

insert into [dbo].[RH_ServiceInterupt] 
	 ([AbstractID],
	 [InteruptOccurrence],
	 [InteruptStartDate],
	 [InteruptReturnDate],
	 [InteruptReason],
	 [InteruptTransfer],
	 [InteruptLOS],
	 [InteruptReasonICD]) 
select AbstractID, 
	 @InteruptOccurrence,
	 @InteruptStartDate,
	 @InteruptReturnDate,
	 @InteruptReason,
	 @InteruptTransfer,
	 @InteruptLOS,
	 @InteruptReasonICD
from RH_ClientInfo where LinkID = @AbstractID
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE PROCEDURE [I_RH_Therapy] (
    @AbstractID [int],
    @TherapyTimeOT int,
    @TherapyTimePT int,
    @TherapyTimeSLP int,
    @TherapyTimeOTA int,
    @TherapyTimePTA int,
    @TherapyTimeCDA int  
    )
AS
 
    insert into [RH_Therapy](
        AbstractID,
        TherapyTimeOT,
        TherapyTimePT,
        TherapyTimeSLP,
        TherapyTimeOTA,
        TherapyTimePTA,
        TherapyTimeCDA
        )
    values(
        @AbstractID,
        @TherapyTimeOT,
        @TherapyTimePT,
        @TherapyTimeSLP,
        @TherapyTimeOTA,
        @TherapyTimePTA,
        @TherapyTimeCDA  
    )


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE  PROCEDURE [I_RH_UDAbstracting]
	(@AbstractID 	[int],
	 @UDDate1 	[datetime],
	 @UDDate2 	[datetime],
	 @UDDate3 	[datetime],
	 @UDDate4 	[datetime],
	 @UDTime1 	[datetime],
	 @UDTime2 	[datetime],
	 @UDTime3 	[datetime],
	 @UDTime4 	[datetime],
	 @UDLookup1 	[int],
	 @UDLookup2 	[int],
	 @UDLookup3 	[int],
	 @UDLookup4 	[int],
	 @UDInteger1 	[int],
	 @UDInteger2 	[int],
	 @UDInteger3 	[int],
	 @UDInteger4 	[int],
	 @UDText1 	[varchar](255),
	 @UDText2 	[varchar](255),
	 @UDText3 	[varchar](255),
	 @UDText4 	[varchar](255),
	 @UDSmallText1 [varchar](50), 
	 @UDSmallText2 [varchar](50), 
	 @UDSmallText3 [varchar](50), 
	 @UDSmallText4 [varchar](50),
	 @UDDate5 	[datetime], 
	 @UDTime5 	[datetime], 
	 @UDLookup5 	[int], 
	 @UDInteger5 	[varchar](50), 
	 @UDText5 	[varchar](255), 
 	 @UDSmallText5 	[varchar](50))
AS 
INSERT INTO [dbo].[RH_UDAbstracting] 
	 ([AbstractID],
	 [UDDate1],
	 [UDDate2],
	 [UDDate3],
	 [UDDate4],
	 [UDTime1],
	 [UDTime2],
	 [UDTime3],
	 [UDTime4],
	 [UDLookup1],
	 [UDLookup2],
	 [UDLookup3],
	 [UDLookup4],
	 [UDInteger1],
	 [UDInteger2],
	 [UDInteger3],
	 [UDInteger4],
	 [UDText1],
	 [UDText2],
	 [UDText3],
	 [UDText4],
	 [UDSmallText1], 
	 [UDSmallText2], 
	 [UDSmallText3], 
	 [UDSmallText4],
	 [UDDate5], 
	 [UDTime5], 
	 [UDLookup5], 
	 [UDInteger5], 
	 [UDText5], 
 	 [UDSmallText5]) 
VALUES 
	(@AbstractID,
	 @UDDate1,
	 @UDDate2,
	 @UDDate3,
	 @UDDate4,
	 @UDTime1,
	 @UDTime2,
	 @UDTime3,
	 @UDTime4,
	 @UDLookup1,
	 @UDLookup2,
	 @UDLookup3,
	 @UDLookup4,
	 @UDInteger1,
	 @UDInteger2,
	 @UDInteger3,
	 @UDInteger4,
	 @UDText1,
	 @UDText2,
	 @UDText3,
	 @UDText4,
	 @UDSmallText1, 
	 @UDSmallText2, 
	 @UDSmallText3, 
	 @UDSmallText4,
	 @UDDate5, 
	 @UDTime5, 
	 @UDLookup5, 
	 @UDInteger5, 
	 @UDText5, 
 	 @UDSmallText5)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_RH_UDFieldsDate]
	(@AbstractID 	[int],
	 @UDDate6 	[datetime],
	 @UDDate7 	[datetime],
	 @UDDate8 	[datetime],
	 @UDDate9 	[datetime],
	 @UDDate10 	[datetime],
	 @UDDate11 	[datetime],
	 @UDDate12 	[datetime],
	 @UDDate13 	[datetime],
	 @UDDate14 	[datetime],
	 @UDDate15 	[datetime],
	 @UDDate16 	[datetime],
	 @UDDate17 	[datetime],
	 @UDDate18 	[datetime],
	 @UDDate19 	[datetime],
	 @UDDate20 	[datetime],
	 @UDDate21 	[datetime],
	 @UDDate22 	[datetime],
	 @UDDate23 	[datetime],
	 @UDDate24 	[datetime],
	 @UDDate25 	[datetime])
as 
insert into [dbo].[RH_UDFieldsDate] 
	 ([AbstractID],
	 [UDDate6],
	 [UDDate7],
	 [UDDate8],
	 [UDDate9],
	 [UDDate10],
	 [UDDate11],
	 [UDDate12],
	 [UDDate13],
	 [UDDate14],
	 [UDDate15],
	 [UDDate16],
	 [UDDate17],
	 [UDDate18],
	 [UDDate19],
	 [UDDate20],
	 [UDDate21],
	 [UDDate22],
	 [UDDate23],
	 [UDDate24],
	 [UDDate25]) 
values
	(@AbstractID,
	 @UDDate6,
	 @UDDate7,
	 @UDDate8,
	 @UDDate9,
	 @UDDate10,
	 @UDDate11,
	 @UDDate12,
	 @UDDate13,
	 @UDDate14,
	 @UDDate15,
	 @UDDate16,
	 @UDDate17,
	 @UDDate18,
	 @UDDate19,
	 @UDDate20,
	 @UDDate21,
	 @UDDate22,
	 @UDDate23,
	 @UDDate24,
	 @UDDate25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_RH_UDFieldsInteger]
	(@AbstractID 	[int],
	 @UDInteger6 	[varchar](50),
	 @UDInteger7 	[varchar](50),
	 @UDInteger8 	[varchar](50),
	 @UDInteger9 	[varchar](50),
	 @UDInteger10 	[varchar](50),
	 @UDInteger11 	[varchar](50),
	 @UDInteger12 	[varchar](50),
	 @UDInteger13 	[varchar](50),
	 @UDInteger14 	[varchar](50),
	 @UDInteger15 	[varchar](50),
	 @UDInteger16 	[varchar](50),
	 @UDInteger17 	[varchar](50),
	 @UDInteger18 	[varchar](50),
	 @UDInteger19 	[varchar](50),
	 @UDInteger20 	[varchar](50),
	 @UDInteger21 	[varchar](50),
	 @UDInteger22 	[varchar](50),
	 @UDInteger23 	[varchar](50),
	 @UDInteger24 	[varchar](50),
	 @UDInteger25 	[varchar](50))
as 
insert into [dbo].[RH_UDFieldsInteger] 
	 ([AbstractID],
	 [UDInteger6],
	 [UDInteger7],
	 [UDInteger8],
	 [UDInteger9],
	 [UDInteger10],
	 [UDInteger11],
	 [UDInteger12],
	 [UDInteger13],
	 [UDInteger14],
	 [UDInteger15],
	 [UDInteger16],
	 [UDInteger17],
	 [UDInteger18],
	 [UDInteger19],
	 [UDInteger20],
	 [UDInteger21],
	 [UDInteger22],
	 [UDInteger23],
	 [UDInteger24],
	 [UDInteger25]) 
values
	(@AbstractID,
	 @UDInteger6,
	 @UDInteger7,
	 @UDInteger8,
	 @UDInteger9,
	 @UDInteger10,
	 @UDInteger11,
	 @UDInteger12,
	 @UDInteger13,
	 @UDInteger14,
	 @UDInteger15,
	 @UDInteger16,
	 @UDInteger17,
	 @UDInteger18,
	 @UDInteger19,
	 @UDInteger20,
	 @UDInteger21,
	 @UDInteger22,
	 @UDInteger23,
	 @UDInteger24,
	 @UDInteger25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_RH_UDFieldsLookUp]
	(@AbstractID 	[int],
	 @UDLookUp6 	[int],
	 @UDLookUp7 	[int],
	 @UDLookUp8 	[int],
	 @UDLookUp9 	[int],
	 @UDLookUp10 	[int],
	 @UDLookUp11 	[int],
	 @UDLookUp12 	[int],
	 @UDLookUp13 	[int],
	 @UDLookUp14 	[int],
	 @UDLookUp15 	[int],
	 @UDLookUp16 	[int],
	 @UDLookUp17 	[int],
	 @UDLookUp18 	[int],
	 @UDLookUp19 	[int],
	 @UDLookUp20 	[int],
	 @UDLookUp21 	[int],
	 @UDLookUp22 	[int],
	 @UDLookUp23 	[int],
	 @UDLookUp24 	[int],
	 @UDLookUp25 	[int])
as 
insert into [dbo].[RH_UDFieldsLookUp] 
	 ([AbstractID],
	 [UDLookUp6],
	 [UDLookUp7],
	 [UDLookUp8],
	 [UDLookUp9],
	 [UDLookUp10],
	 [UDLookUp11],
	 [UDLookUp12],
	 [UDLookUp13],
	 [UDLookUp14],
	 [UDLookUp15],
	 [UDLookUp16],
	 [UDLookUp17],
	 [UDLookUp18],
	 [UDLookUp19],
	 [UDLookUp20],
	 [UDLookUp21],
	 [UDLookUp22],
	 [UDLookUp23],
	 [UDLookUp24],
	 [UDLookUp25]) 
values
	(@AbstractID,
	 @UDLookUp6,
	 @UDLookUp7,
	 @UDLookUp8,
	 @UDLookUp9,
	 @UDLookUp10,
	 @UDLookUp11,
	 @UDLookUp12,
	 @UDLookUp13,
	 @UDLookUp14,
	 @UDLookUp15,
	 @UDLookUp16,
	 @UDLookUp17,
	 @UDLookUp18,
	 @UDLookUp19,
	 @UDLookUp20,
	 @UDLookUp21,
	 @UDLookUp22,
	 @UDLookUp23,
	 @UDLookUp24,
	 @UDLookUp25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_RH_UDFieldsSmallText]
	(@AbstractID 	[int],
	 @UDSmallText6 	[varchar](50),
	 @UDSmallText7 	[varchar](50),
	 @UDSmallText8 	[varchar](50),
	 @UDSmallText9 	[varchar](50),
	 @UDSmallText10 	[varchar](50),
	 @UDSmallText11 	[varchar](50),
	 @UDSmallText12 	[varchar](50),
	 @UDSmallText13 	[varchar](50),
	 @UDSmallText14 	[varchar](50),
	 @UDSmallText15 	[varchar](50),
	 @UDSmallText16 	[varchar](50),
	 @UDSmallText17 	[varchar](50),
	 @UDSmallText18 	[varchar](50),
	 @UDSmallText19 	[varchar](50),
	 @UDSmallText20 	[varchar](50),
	 @UDSmallText21 	[varchar](50),
	 @UDSmallText22 	[varchar](50),
	 @UDSmallText23 	[varchar](50),
	 @UDSmallText24 	[varchar](50),
	 @UDSmallText25 	[varchar](50))
as 
insert into [dbo].[RH_UDFieldsSmallText] 
	 ([AbstractID],
	 [UDSmallText6],
	 [UDSmallText7],
	 [UDSmallText8],
	 [UDSmallText9],
	 [UDSmallText10],
	 [UDSmallText11],
	 [UDSmallText12],
	 [UDSmallText13],
	 [UDSmallText14],
	 [UDSmallText15],
	 [UDSmallText16],
	 [UDSmallText17],
	 [UDSmallText18],
	 [UDSmallText19],
	 [UDSmallText20],
	 [UDSmallText21],
	 [UDSmallText22],
	 [UDSmallText23],
	 [UDSmallText24],
	 [UDSmallText25]) 
values
	(@AbstractID,
	 @UDSmallText6,
	 @UDSmallText7,
	 @UDSmallText8,
	 @UDSmallText9,
	 @UDSmallText10,
	 @UDSmallText11,
	 @UDSmallText12,
	 @UDSmallText13,
	 @UDSmallText14,
	 @UDSmallText15,
	 @UDSmallText16,
	 @UDSmallText17,
	 @UDSmallText18,
	 @UDSmallText19,
	 @UDSmallText20,
	 @UDSmallText21,
	 @UDSmallText22,
	 @UDSmallText23,
	 @UDSmallText24,
	 @UDSmallText25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_RH_UDFieldsText]
	(@AbstractID 	[int],
	 @UDText6 	[varchar](255),
	 @UDText7 	[varchar](255),
	 @UDText8 	[varchar](255),
	 @UDText9 	[varchar](255),
	 @UDText10 	[varchar](255),
	 @UDText11 	[varchar](255),
	 @UDText12 	[varchar](255),
	 @UDText13 	[varchar](255),
	 @UDText14 	[varchar](255),
	 @UDText15 	[varchar](255),
	 @UDText16 	[varchar](255),
	 @UDText17 	[varchar](255),
	 @UDText18 	[varchar](255),
	 @UDText19 	[varchar](255),
	 @UDText20 	[varchar](255),
	 @UDText21 	[varchar](255),
	 @UDText22 	[varchar](255),
	 @UDText23 	[varchar](255),
	 @UDText24 	[varchar](255),
	 @UDText25 	[varchar](255))
as 
insert into [dbo].[RH_UDFieldsText] 
	 ([AbstractID],
	 [UDText6],
	 [UDText7],
	 [UDText8],
	 [UDText9],
	 [UDText10],
	 [UDText11],
	 [UDText12],
	 [UDText13],
	 [UDText14],
	 [UDText15],
	 [UDText16],
	 [UDText17],
	 [UDText18],
	 [UDText19],
	 [UDText20],
	 [UDText21],
	 [UDText22],
	 [UDText23],
	 [UDText24],
	 [UDText25]) 
values
	(@AbstractID,
	 @UDText6,
	 @UDText7,
	 @UDText8,
	 @UDText9,
	 @UDText10,
	 @UDText11,
	 @UDText12,
	 @UDText13,
	 @UDText14,
	 @UDText15,
	 @UDText16,
	 @UDText17,
	 @UDText18,
	 @UDText19,
	 @UDText20,
	 @UDText21,
	 @UDText22,
	 @UDText23,
	 @UDText24,
	 @UDText25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_RH_UDFieldsTime]
	(@AbstractID 	[int],
	 @UDTime6 	[datetime],
	 @UDTime7 	[datetime],
	 @UDTime8 	[datetime],
	 @UDTime9 	[datetime],
	 @UDTime10 	[datetime],
	 @UDTime11 	[datetime],
	 @UDTime12 	[datetime],
	 @UDTime13 	[datetime],
	 @UDTime14 	[datetime],
	 @UDTime15 	[datetime],
	 @UDTime16 	[datetime],
	 @UDTime17 	[datetime],
	 @UDTime18 	[datetime],
	 @UDTime19 	[datetime],
	 @UDTime20 	[datetime],
	 @UDTime21 	[datetime],
	 @UDTime22 	[datetime],
	 @UDTime23 	[datetime],
	 @UDTime24 	[datetime],
	 @UDTime25 	[datetime])
as 
insert into [dbo].[RH_UDFieldsTime] 
	 ([AbstractID],
	 [UDTime6],
	 [UDTime7],
	 [UDTime8],
	 [UDTime9],
	 [UDTime10],
	 [UDTime11],
	 [UDTime12],
	 [UDTime13],
	 [UDTime14],
	 [UDTime15],
	 [UDTime16],
	 [UDTime17],
	 [UDTime18],
	 [UDTime19],
	 [UDTime20],
	 [UDTime21],
	 [UDTime22],
	 [UDTime23],
	 [UDTime24],
	 [UDTime25]) 
values
	(@AbstractID,
	 @UDTime6,
	 @UDTime7,
	 @UDTime8,
	 @UDTime9,
	 @UDTime10,
	 @UDTime11,
	 @UDTime12,
	 @UDTime13,
	 @UDTime14,
	 @UDTime15,
	 @UDTime16,
	 @UDTime17,
	 @UDTime18,
	 @UDTime19,
	 @UDTime20,
	 @UDTime21,
	 @UDTime22,
	 @UDTime23,
	 @UDTime24,
	 @UDTime25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE  PROCEDURE [I_RH_UpdateHistory] 
	@AbstractID as int,
	@Coder as int,
    	@UpdateType as varchar(10) = 'Saved'
AS 

declare @HID as int --NP-00025
select @HID = HospitalID from U_Users where Code = @Coder

insert into RH_UpdateHistory (AbstractID, HospitalID, Coder, Updated, UpdateType) 
values (@AbstractID, @HID, @Coder, GetDate(), @UpdateType)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






CREATE PROCEDURE [I_ROI_Actions]
	(@ROIID 		[int],
	 @OccurrenceNumber 	[int],
	 @ActionType		[int],
	 @ActionDate 		[datetime],
	 @ActionTime 		[datetime],
	 @ActionCoder 		[int],
	 @ActionFollowUpDays 	[int],
	 @NextAction	 	[int],
	 @ActionHLink 		[int],
	 @ActionsComments	[varchar](255) )

AS INSERT INTO [ROI_Actions] 
	 ([ROIID],
	 [OccurrenceNumber],
	 [ActionHLink],
	 [ActionType],
	 [ActionDate],
	 [ActionTime],
	 [ActionCoder],
	 [ActionFollowUpDays],
	 [NextAction],
	 [ActionsComments]) 
 
VALUES 
	(@ROIID,
	 @OccurrenceNumber,
	 @ActionHLink,
	 @ActionType,
	 @ActionDate,
	 @ActionTime,
	 @ActionCoder,
	 @ActionFollowUpDays,
	 @NextAction,
	 @ActionsComments)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [I_ROI_Document]
	(@ROIID [int], 
	@OccurrenceNumber int, 
	@DocumentStartDate datetime, 
	@DocumentEndDate datetime, 
	@DocumentCode int, 
	@DocumentComments varchar(4000)
)
AS 
    insert into [ROI_Document](ROIID, OccurrenceNumber, DocumentStartDate, DocumentEndDate, DocumentCode, DocumentComments)
    values(@ROIID, @OccurrenceNumber, @DocumentStartDate, @DocumentEndDate, @DocumentCode, @DocumentComments)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [I_ROI_Main]
   (@HospitalID	[int],
    @ROIID         [int],
    @RequestNumber         [varchar](15),
    @ChartNumber           [varchar](10),
    @RequestDate           [datetime],
    @RequestReceivedTime   [datetime],
    @RequestCoder  [int],
    @RequesterID           [int],
    @RequesterType         [int],
    @RequestMethod         [int],
    @RequestReceived       [datetime],
    @RequestType   [int],
    @RequestChargeable     [int],
    @RequestDuration       [int],
    @ContactID             [int],
    @ContactEMail  [varchar](50),
    @ContactPhone  [varchar](15),
    @ContactExtention      [varchar](20),
    @ContactFax            [varchar](15),
    @AuthRequired  [int],
    @AuthReceived  [int],
    @AuthSignedID  [int],
    @ROIStatus             [int],
    @SentDate              [datetime],
    @SentTime              [datetime],
    @SentCoder             [int],
    @SentBy                [int],
    @TrackingNumber        [varchar](75),
    @SpecialHandling       [varchar](1000),
    @InvoiceNumber         [varchar](30),
    @InvoiceDate           [datetime],
    @InvoiceTime           [datetime],
    @InvoiceTotal          [money],
    @AccountNumber         [varchar](30),
    @GSTNumber             [varchar](30),
    @AmountPaid            [money],
    @AmountOwed    [money],
    @DueDate               [datetime],
    @AuthType              [int],
    @CostLevel             [int],
    @Comment               [varchar](255),
    @LastName              [varchar](40), 
    @FirstName             [varchar](35),
    @RequestUrgency  [int],
    @SiteNumber 	[int],
    @ROITaxRate1 	[int], 
    @ROITaxRate2 	[int],
    @Confidential   [int],
    @ExtensionNoticeRequired int,
    @ExtensionDays int,
    @AgeCode int,
    @AgeNumber int,
    @Birthdate datetime  )

AS 
SELECT @ROIID = (SELECT isnull(MAX(ROIID), 0) FROM ROI_Main) + 1
INSERT INTO [ROI_Main] 
    ([HospitalID],
    [ROIID],
    [RequestNumber],
    [SiteNumber],
    [ChartNumber],
    [LastName], 
    [FirstName],
    [RequestDate],
    [RequestReceivedTime],
    [RequestCoder],
    [RequesterID],
    [RequesterType],
    [RequestMethod],
    [RequestReceived],
    [RequestType],
    [RequestChargeable],
    [CostLevel],
    [RequestDuration],
    [ContactID],
    [ContactEMail],
    [ContactPhone],
    [ContactExtention],
    [ContactFax],
    [AuthorizationRequired],
    [AuthorizationReceived],
    [AuthorizationType],
    [AuthorizationSignedID],
    [ROIStatus],
    [SentDate],
    [SentTime],
    [SentCoder],
    [SentBy],
    [TrackingNumber],
    [SpecialHandling],
    [InvoiceNumber],
    [InvoiceDate],
    [InvoiceTime],
    [InvoiceTotal],
    [AccountNumber],
    [GSTNumber],
    [AmountPaid],
    [AmountOwed],
    [DueDate],
    [RequestComments],
    [IsDeleted],
    [RequestUrgency],
    [ROITaxRate1],
    [ROITaxRate2],
    [Confidential],
    [ExtensionNoticeRequired],
    [ExtensionDays],
    [AgeCode],
    [AgeNumber],
    [Birthdate] ) 

VALUES 
   (@HospitalID,
    @ROIID,
    @RequestNumber,
    @SiteNumber,
    @ChartNumber,
    @LastName, 
    @FirstName,
    @RequestDate,
    @RequestReceivedTime,
    @RequestCoder,
    @RequesterID,
    @RequesterType,
    @RequestMethod,
    @RequestReceived,
    @RequestType,
    @RequestChargeable,
    @CostLevel,
    @RequestDuration,
    @ContactID,
    @ContactEMail,
    @ContactPhone,
    @ContactExtention,
    @ContactFax,
    @AuthRequired,
    @AuthReceived,
    @AuthType,
    @AuthSignedID,
    @ROIStatus,
    @SentDate,
    @SentTime,
    @SentCoder,
    @SentBy,
    @TrackingNumber,
    @SpecialHandling,
    @InvoiceNumber,
    @InvoiceDate,
    @InvoiceTime,
    @InvoiceTotal,
    @AccountNumber,
    @GSTNumber,
    @AmountPaid,
    @AmountOwed,
    @DueDate,
    @Comment,
    2,
    @RequestUrgency,
    @ROITaxRate1, 
    @ROITaxRate2,
    @Confidential,
    @ExtensionNoticeRequired,
    @ExtensionDays,
    @AgeCode,
    @AgeNumber,
    @Birthdate)

   RETURN @ROIID
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






CREATE PROCEDURE [I_ROI_Payments]
	(@ROIID	 	[int],
	 @OccurrenceNumber 	[int],
	 @PaymentDate		[datetime],
	 @PaymentTime 	[datetime],
	 @PaymentMethod 	[int],
	 @PaymentAmount 	[money],
     @PaymentCheque     [varchar](50),
     @PaymentComments	[varchar](255)  )

AS INSERT INTO [ROI_Payments] 
	 ([ROIID],
	 [OccurrenceNumber],
	 [PaymentDate],
	 [PaymentTime],
	 [PaymentMethod],
	 [PaymentAmount],
     [PaymentCheque],
     [PaymentComments]) 
VALUES 
	(@ROIID,
	 @OccurrenceNumber,
	 @PaymentDate,
	 @PaymentTime,
	 @PaymentMethod,
	 @PaymentAmount,
     @PaymentCheque,
     @PaymentComments)
     
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [I_ROI_RequesterInfo]
	(@ROIID 	[int],
	 @Address 	[varchar](255),
	 @PostalCode 	[varchar](50),
	 @City		[varchar](50),
	 @Province 	[int],
	 @Country 	[int],
	 @BillingAddress 	[varchar](255),
	 @BillingPostalCode 	[varchar](50),
	 @BillingCity 	[varchar](50),
	 @BillingProvince 	[int],
	 @BillingCountry 	[int],
	 @Phone 	[varchar](50),
	 @PhoneExt 	[varchar](50),
	 @Fax	 	[varchar](50))

AS INSERT INTO [dbo].[ROI_RequesterInfo] 
	 ( [ROIID],
	 [Address],
	 [PostalCode],
	 [City],
	 [Province],
	 [Country],
	 [BillingAddress],
	 [BillingPostalCode],
	 [BillingCity],
	 [BillingProvince],
	 [BillingCountry],
	 [Phone],
	 [PhoneExt],
	 [Fax]) 
 
VALUES 
	( @ROIID,
	 @Address,
	 @PostalCode,
	 @City,
	 @Province,
	 @Country,
	 @BillingAddress,
	 @BillingPostalCode,
	 @BillingCity,
	 @BillingProvince,
	 @BillingCountry,
	 @Phone,
	 @PhoneExt,
	 @Fax)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






CREATE PROCEDURE [I_ROI_SentItems]
	(@ROIID	 	[int],
	 @OccurrenceNumber 	[int],
	 @SentDate	 	[datetime],
	 @Quantity	 	[int],
	 @ItemCode	 	[int],
	 @Price		 	[money],
	 @TaxCode		[int],
	 @Amount		[money],
	 @SentComments 	[varchar](255))

AS INSERT INTO [ROI_SentItems] 
	 ([ROIID],
	 [OccurrenceNumber],
	 [SentDate],
	 [Quantity],
	 [ItemCode],
	 [Price],
	 [TaxCode],
	 [Amount],
	 [SentComments]) 
VALUES 
	(@ROIID,
	 @OccurrenceNumber,
	 @SentDate,
	 @Quantity,
	 @ItemCode,
	 @Price,
	 @TaxCode,
	 @Amount,
	 @SentComments)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_ROI_UDFieldsDate]
	(@ROIID 	[int],
	 @UDDate6 	[datetime],
	 @UDDate7 	[datetime],
	 @UDDate8 	[datetime],
	 @UDDate9 	[datetime],
	 @UDDate10 	[datetime],
	 @UDDate11 	[datetime],
	 @UDDate12 	[datetime],
	 @UDDate13 	[datetime],
	 @UDDate14 	[datetime],
	 @UDDate15 	[datetime],
	 @UDDate16 	[datetime],
	 @UDDate17 	[datetime],
	 @UDDate18 	[datetime],
	 @UDDate19 	[datetime],
	 @UDDate20 	[datetime],
	 @UDDate21 	[datetime],
	 @UDDate22 	[datetime],
	 @UDDate23 	[datetime],
	 @UDDate24 	[datetime],
	 @UDDate25 	[datetime])
as 
insert into [dbo].[ROI_UDFieldsDate] 
	 ([ROIID],
	 [UDDate6],
	 [UDDate7],
	 [UDDate8],
	 [UDDate9],
	 [UDDate10],
	 [UDDate11],
	 [UDDate12],
	 [UDDate13],
	 [UDDate14],
	 [UDDate15],
	 [UDDate16],
	 [UDDate17],
	 [UDDate18],
	 [UDDate19],
	 [UDDate20],
	 [UDDate21],
	 [UDDate22],
	 [UDDate23],
	 [UDDate24],
	 [UDDate25]) 
values
	(@ROIID,
	 @UDDate6,
	 @UDDate7,
	 @UDDate8,
	 @UDDate9,
	 @UDDate10,
	 @UDDate11,
	 @UDDate12,
	 @UDDate13,
	 @UDDate14,
	 @UDDate15,
	 @UDDate16,
	 @UDDate17,
	 @UDDate18,
	 @UDDate19,
	 @UDDate20,
	 @UDDate21,
	 @UDDate22,
	 @UDDate23,
	 @UDDate24,
	 @UDDate25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_ROI_UDFieldsInteger]
	(@ROIID 	[int],
	 @UDInteger6 	[varchar](50),
	 @UDInteger7 	[varchar](50),
	 @UDInteger8 	[varchar](50),
	 @UDInteger9 	[varchar](50),
	 @UDInteger10 	[varchar](50),
	 @UDInteger11 	[varchar](50),
	 @UDInteger12 	[varchar](50),
	 @UDInteger13 	[varchar](50),
	 @UDInteger14 	[varchar](50),
	 @UDInteger15 	[varchar](50),
	 @UDInteger16 	[varchar](50),
	 @UDInteger17 	[varchar](50),
	 @UDInteger18 	[varchar](50),
	 @UDInteger19 	[varchar](50),
	 @UDInteger20 	[varchar](50),
	 @UDInteger21 	[varchar](50),
	 @UDInteger22 	[varchar](50),
	 @UDInteger23 	[varchar](50),
	 @UDInteger24 	[varchar](50),
	 @UDInteger25 	[varchar](50))
as 
insert into [dbo].[ROI_UDFieldsInteger] 
	 ([ROIID],
	 [UDInteger6],
	 [UDInteger7],
	 [UDInteger8],
	 [UDInteger9],
	 [UDInteger10],
	 [UDInteger11],
	 [UDInteger12],
	 [UDInteger13],
	 [UDInteger14],
	 [UDInteger15],
	 [UDInteger16],
	 [UDInteger17],
	 [UDInteger18],
	 [UDInteger19],
	 [UDInteger20],
	 [UDInteger21],
	 [UDInteger22],
	 [UDInteger23],
	 [UDInteger24],
	 [UDInteger25]) 
values
	(@ROIID,
	 @UDInteger6,
	 @UDInteger7,
	 @UDInteger8,
	 @UDInteger9,
	 @UDInteger10,
	 @UDInteger11,
	 @UDInteger12,
	 @UDInteger13,
	 @UDInteger14,
	 @UDInteger15,
	 @UDInteger16,
	 @UDInteger17,
	 @UDInteger18,
	 @UDInteger19,
	 @UDInteger20,
	 @UDInteger21,
	 @UDInteger22,
	 @UDInteger23,
	 @UDInteger24,
	 @UDInteger25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_ROI_UDFieldsLookUp]
	(@ROIID 	[int],
	 @UDLookUp6 	[int],
	 @UDLookUp7 	[int],
	 @UDLookUp8 	[int],
	 @UDLookUp9 	[int],
	 @UDLookUp10 	[int],
	 @UDLookUp11 	[int],
	 @UDLookUp12 	[int],
	 @UDLookUp13 	[int],
	 @UDLookUp14 	[int],
	 @UDLookUp15 	[int],
	 @UDLookUp16 	[int],
	 @UDLookUp17 	[int],
	 @UDLookUp18 	[int],
	 @UDLookUp19 	[int],
	 @UDLookUp20 	[int],
	 @UDLookUp21 	[int],
	 @UDLookUp22 	[int],
	 @UDLookUp23 	[int],
	 @UDLookUp24 	[int],
	 @UDLookUp25 	[int])
as 
insert into [dbo].[ROI_UDFieldsLookUp] 
	 ([ROIID],
	 [UDLookUp6],
	 [UDLookUp7],
	 [UDLookUp8],
	 [UDLookUp9],
	 [UDLookUp10],
	 [UDLookUp11],
	 [UDLookUp12],
	 [UDLookUp13],
	 [UDLookUp14],
	 [UDLookUp15],
	 [UDLookUp16],
	 [UDLookUp17],
	 [UDLookUp18],
	 [UDLookUp19],
	 [UDLookUp20],
	 [UDLookUp21],
	 [UDLookUp22],
	 [UDLookUp23],
	 [UDLookUp24],
	 [UDLookUp25]) 
values
	(@ROIID,
	 @UDLookUp6,
	 @UDLookUp7,
	 @UDLookUp8,
	 @UDLookUp9,
	 @UDLookUp10,
	 @UDLookUp11,
	 @UDLookUp12,
	 @UDLookUp13,
	 @UDLookUp14,
	 @UDLookUp15,
	 @UDLookUp16,
	 @UDLookUp17,
	 @UDLookUp18,
	 @UDLookUp19,
	 @UDLookUp20,
	 @UDLookUp21,
	 @UDLookUp22,
	 @UDLookUp23,
	 @UDLookUp24,
	 @UDLookUp25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_ROI_UDFieldsSmallText]
	(@ROIID 	[int],
	 @UDSmallText6 	[varchar](50),
	 @UDSmallText7 	[varchar](50),
	 @UDSmallText8 	[varchar](50),
	 @UDSmallText9 	[varchar](50),
	 @UDSmallText10 	[varchar](50),
	 @UDSmallText11 	[varchar](50),
	 @UDSmallText12 	[varchar](50),
	 @UDSmallText13 	[varchar](50),
	 @UDSmallText14 	[varchar](50),
	 @UDSmallText15 	[varchar](50),
	 @UDSmallText16 	[varchar](50),
	 @UDSmallText17 	[varchar](50),
	 @UDSmallText18 	[varchar](50),
	 @UDSmallText19 	[varchar](50),
	 @UDSmallText20 	[varchar](50),
	 @UDSmallText21 	[varchar](50),
	 @UDSmallText22 	[varchar](50),
	 @UDSmallText23 	[varchar](50),
	 @UDSmallText24 	[varchar](50),
	 @UDSmallText25 	[varchar](50))
as 
insert into [dbo].[ROI_UDFieldsSmallText] 
	 ([ROIID],
	 [UDSmallText6],
	 [UDSmallText7],
	 [UDSmallText8],
	 [UDSmallText9],
	 [UDSmallText10],
	 [UDSmallText11],
	 [UDSmallText12],
	 [UDSmallText13],
	 [UDSmallText14],
	 [UDSmallText15],
	 [UDSmallText16],
	 [UDSmallText17],
	 [UDSmallText18],
	 [UDSmallText19],
	 [UDSmallText20],
	 [UDSmallText21],
	 [UDSmallText22],
	 [UDSmallText23],
	 [UDSmallText24],
	 [UDSmallText25]) 
values
	(@ROIID,
	 @UDSmallText6,
	 @UDSmallText7,
	 @UDSmallText8,
	 @UDSmallText9,
	 @UDSmallText10,
	 @UDSmallText11,
	 @UDSmallText12,
	 @UDSmallText13,
	 @UDSmallText14,
	 @UDSmallText15,
	 @UDSmallText16,
	 @UDSmallText17,
	 @UDSmallText18,
	 @UDSmallText19,
	 @UDSmallText20,
	 @UDSmallText21,
	 @UDSmallText22,
	 @UDSmallText23,
	 @UDSmallText24,
	 @UDSmallText25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_ROI_UDFieldsText]
	(@ROIID 	[int],
	 @UDText6 	[varchar](255),
	 @UDText7 	[varchar](255),
	 @UDText8 	[varchar](255),
	 @UDText9 	[varchar](255),
	 @UDText10 	[varchar](255),
	 @UDText11 	[varchar](255),
	 @UDText12 	[varchar](255),
	 @UDText13 	[varchar](255),
	 @UDText14 	[varchar](255),
	 @UDText15 	[varchar](255),
	 @UDText16 	[varchar](255),
	 @UDText17 	[varchar](255),
	 @UDText18 	[varchar](255),
	 @UDText19 	[varchar](255),
	 @UDText20 	[varchar](255),
	 @UDText21 	[varchar](255),
	 @UDText22 	[varchar](255),
	 @UDText23 	[varchar](255),
	 @UDText24 	[varchar](255),
	 @UDText25 	[varchar](255))
as 
insert into [dbo].[ROI_UDFieldsText] 
	 ([ROIID],
	 [UDText6],
	 [UDText7],
	 [UDText8],
	 [UDText9],
	 [UDText10],
	 [UDText11],
	 [UDText12],
	 [UDText13],
	 [UDText14],
	 [UDText15],
	 [UDText16],
	 [UDText17],
	 [UDText18],
	 [UDText19],
	 [UDText20],
	 [UDText21],
	 [UDText22],
	 [UDText23],
	 [UDText24],
	 [UDText25]) 
values
	(@ROIID,
	 @UDText6,
	 @UDText7,
	 @UDText8,
	 @UDText9,
	 @UDText10,
	 @UDText11,
	 @UDText12,
	 @UDText13,
	 @UDText14,
	 @UDText15,
	 @UDText16,
	 @UDText17,
	 @UDText18,
	 @UDText19,
	 @UDText20,
	 @UDText21,
	 @UDText22,
	 @UDText23,
	 @UDText24,
	 @UDText25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [I_ROI_UDFieldsTime]
	(@ROIID 	[int],
	 @UDTime6 	[datetime],
	 @UDTime7 	[datetime],
	 @UDTime8 	[datetime],
	 @UDTime9 	[datetime],
	 @UDTime10 	[datetime],
	 @UDTime11 	[datetime],
	 @UDTime12 	[datetime],
	 @UDTime13 	[datetime],
	 @UDTime14 	[datetime],
	 @UDTime15 	[datetime],
	 @UDTime16 	[datetime],
	 @UDTime17 	[datetime],
	 @UDTime18 	[datetime],
	 @UDTime19 	[datetime],
	 @UDTime20 	[datetime],
	 @UDTime21 	[datetime],
	 @UDTime22 	[datetime],
	 @UDTime23 	[datetime],
	 @UDTime24 	[datetime],
	 @UDTime25 	[datetime])
as 
insert into [dbo].[ROI_UDFieldsTime] 
	 ([ROIID],
	 [UDTime6],
	 [UDTime7],
	 [UDTime8],
	 [UDTime9],
	 [UDTime10],
	 [UDTime11],
	 [UDTime12],
	 [UDTime13],
	 [UDTime14],
	 [UDTime15],
	 [UDTime16],
	 [UDTime17],
	 [UDTime18],
	 [UDTime19],
	 [UDTime20],
	 [UDTime21],
	 [UDTime22],
	 [UDTime23],
	 [UDTime24],
	 [UDTime25]) 
values
	(@ROIID,
	 @UDTime6,
	 @UDTime7,
	 @UDTime8,
	 @UDTime9,
	 @UDTime10,
	 @UDTime11,
	 @UDTime12,
	 @UDTime13,
	 @UDTime14,
	 @UDTime15,
	 @UDTime16,
	 @UDTime17,
	 @UDTime18,
	 @UDTime19,
	 @UDTime20,
	 @UDTime21,
	 @UDTime22,
	 @UDTime23,
	 @UDTime24,
	 @UDTime25)
	 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE  PROCEDURE [I_ROI_UpdateHistory]
(
@ROIID 	 [int],
@Coder 	 [int],
@UpdateType varchar(10)
)
AS 

declare @HID as int --NP-00025
select @HID = HospitalID from U_Users where Code = @Coder

insert into [ROI_UpdateHistory] ([ROIID], [HospitalID], [Coder], [Updated], [UpdateType]) 
values (@ROIID, @HID, @Coder, GetDate(), @UpdateType)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [I_ROI_UserDefined]
	(@ROIID 	[int],
	 @UDDate1 	[datetime],
	 @UDDate2 	[datetime],
	 @UDDate3 	[datetime],
	 @UDDate4 	[datetime],
	 @UDTime1 	[datetime],
	 @UDTime2 	[datetime],
	 @UDTime3 	[datetime],
	 @UDTime4 	[datetime],
	 @UDLookup1 	[int],
	 @UDLookup2 	[int],
	 @UDLookup3 	[int],
	 @UDLookup4 	[int],
	 @UDInteger1 	[int],
	 @UDInteger2 	[int],
	 @UDInteger3 	[int],
	 @UDInteger4 	[int],
	 @UDText1 	[varchar](255),
	 @UDText2 	[varchar](255),
	 @UDText3 	[varchar](255),
	 @UDText4 	[varchar](255),
	 @UDSmallText1 	[varchar](75),
	 @UDSmallText2 	[varchar](50),
	 @UDSmallText3 	[varchar](50),
	 @UDSmallText4 	[varchar](50),
	 @UDDate5 	[datetime], 
	 @UDTime5 	[datetime], 
	 @UDLookup5 	[int], 
	 @UDInteger5 	[varchar](50), 
	 @UDText5 	[varchar](255), 
 	 @UDSmallText5 	[varchar](50))

AS INSERT INTO [dbo].[ROI_UserDefined] 
	 ( [ROIID],
	 [UDDate1],
	 [UDDate2],
	 [UDDate3],
	 [UDDate4],
	 [UDTime1],
	 [UDTime2],
	 [UDTime3],
	 [UDTime4],
	 [UDLookup1],
	 [UDLookup2],
	 [UDLookup3],
	 [UDLookup4],
	 [UDInteger1],
	 [UDInteger2],
	 [UDInteger3],
	 [UDInteger4],
	 [UDText1],
	 [UDText2],
	 [UDText3],
	 [UDText4],
	 [UDSmallText1],
	 [UDSmallText2],
	 [UDSmallText3],
	 [UDSmallText4],
	 [UDDate5], 
	 [UDTime5], 
	 [UDLookup5], 
	 [UDInteger5], 
	 [UDText5], 
 	 [UDSmallText5]) 
 
VALUES 
	( @ROIID,
	 @UDDate1,
	 @UDDate2,
	 @UDDate3,
	 @UDDate4,
	 @UDTime1,
	 @UDTime2,
	 @UDTime3,
	 @UDTime4,
	 @UDLookup1,
	 @UDLookup2,
	 @UDLookup3,
	 @UDLookup4,
	 @UDInteger1,
	 @UDInteger2,
	 @UDInteger3,
	 @UDInteger4,
	 @UDText1,
	 @UDText2,
	 @UDText3,
	 @UDText4,
	 @UDSmallText1,
	 @UDSmallText2,
	 @UDSmallText3,
	 @UDSmallText4,
	 @UDDate5, 
	 @UDTime5, 
	 @UDLookup5, 
	 @UDInteger5, 
	 @UDText5, 
 	 @UDSmallText5)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [I_SH_Appointments]
	(@AppointmentID	[int],
	 @Patientid	 	[int],
	 @ProviderNumber 	[int],
	 @AppointmentDate 	[datetime],
	 @AppointmentTime 	[datetime],
	 @Duration	 	[int],
	 @AppointmentReason 	[int],
	 @VisitType		[int],
	 @Location	 	[int],
	 @Room		[int],
	 @Status		[int],
	 @ArrivalTime		[datetime],
	 @CancelReason 	[int])

AS 
SELECT @AppointmentID = (SELECT isnull(MAX(AppointmentID), 0) FROM SH_Appointments) + 1
INSERT INTO [dbo].[SH_Appointments] 
	 ([AppointmentID],
	 [Patientid],
	 [ProviderNumber],
	 [AppointmentDate],
	 [AppointmentTime],
	 [Duration],
	 [AppointmentReason],
	 [VisitType],
	 [Location],
	 [Room], 
	 [Status],
	 [ArrivalTime],
	 [CancelReason]) 
VALUES 
	(@AppointmentID,
	 @PatientID,
	 @ProviderNumber,
	 @AppointmentDate,
	 @AppointmentTime,
	 @Duration,
	 @AppointmentReason,
	 @VisitType,
	 @Location,
	 @Room,
	 @Status,
	 @ArrivalTime,
	 @CancelReason)

IF @Status = 11735 
	BEGIN
		DECLARE @RetVal	[int]
		DECLARE @ChrtNum	[varchar](10)
	 	DECLARE @HCN	[varchar](12)
	 	DECLARE @HCNVer	[varchar](2)
	 	DECLARE @MaName	[varchar](35)
	 	DECLARE @LName	[varchar](35)
	 	DECLARE @MiName 	[varchar](15)
	 	DECLARE @FName	[varchar](35)
	 	DECLARE @Gender 	[int]
	 	DECLARE @DOB	[datetime]
		DECLARE @EncNum 	[varchar](20)
	
		SELECT @ChrtNum = ChartNumber, @HCN = HealthCareNumber, @HCNVer = HCNVersion, @MaName = MaidenName, @LName = LastName, @MiName = MiddleName, @FName = FirstName, @Gender = Gender, @DOB = BirthDate FROM CM_CPI WHERE PatientID = @PatientID
	
		EXEC P_UpdateClinicEncNum @EncNum OUTPUT
		EXEC @RetVal = I_CR_Demographic 0,  @ChrtNum, @HCN, @HCNVer, @MaName, @LName, @MiName, @FName, @Gender, @DOB, 1, 1, 1, 1, 2, NULL, '', 0
		EXEC I_CR_Visit @RetVal, 0, @ProviderNumber, @EncNum, '001', @AppointmentDate, @AppointmentTime, @ArrivalTime, NULL, NULL, 0, @VisitType, 0, 0, NULL, NULL, NULL, NULL, 0, 0, 0, NULL, 0, 0, NULL, NULL, NULL
	END
RETURN @AppointmentID



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [I_SH_UpdateHistory] 
	@AbstractID as int,
	@Coder as int
AS 

INSERT INTO SH_UpdateHistory (AbstractID, Coder, Updated) Values (@AbstractID, @Coder, GetDate())



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






CREATE   PROCEDURE [I_Transcription]
	(@HospitalID		[int],
	 @TranscriptionID 	[int],
	 @AbstractID 	[int],
	 @PatientID 	[int],
	 @DictatingPhysician 	[int],
	 @DictationDate 	[datetime],
	 @DictationTime 	[datetime],
	 @DocumentType 	[int],
	 @DocumentName 	[varchar](100),
	 @TranscriptionDate 	[datetime],
	 @TranscriptionTime 	[datetime],
	 @Transcriptionist 	[int],
	 @StartWordCount 	[int],
	 @LastWordCount 	[int],
	 @TranscriptionLength 	[int],
	 @SignDate 		[datetime],
	 @SignTime 		[datetime],
	 @SignPhysician 	[int],
	 @CareType		[int],
	 @UpdateCPI	VarChar(1) Output)

AS
	INSERT INTO [TR_Main] 
	 ([HospitalID],
	 [TranscriptionID],
	 [AbstractID],
	 [PatientID],
	 [CareType],
	 [DictatingPhysician],
	 [DictationDate],
	 [DictationTime],
	 [SignPhysician],
	 [SignDate],
	 [SignTime],
	 [DocumentType],
	 [DocumentName],
	 [TranscriptionDate],
	 [TranscriptionTime],
	 [Transcriptionist],
	 [StartWordCount],
	 [LastWordCount],
	 [TranscriptionLength],
	 [IsDeleted]) 
 
VALUES 
	(@HospitalID,
	 @TranscriptionID,
	 @AbstractID,
	 @PatientID,
	 @CareType,
	 @DictatingPhysician,
	 @DictationDate,
	 @DictationTime,
	 @SignPhysician,
	 @SignDate,
	 @SignTime,
	 @DocumentType,
	 @DocumentName,
	 @TranscriptionDate,
	 @TranscriptionTime,
	 @Transcriptionist,
	 @StartWordCount,
	 @LastWordCount,
	 @TranscriptionLength,
	 2)

	If isnull(@TranscriptionDate, '') >= CONVERT(VarChar(10), (Select top 1 isnull(TranscriptionDate, '') from TR_Main 
			where Patientid = @PatientID order by TranscriptionDate desc), 111)
		Set @UpdateCPI = 'Y'
	Else
		Set @UpdateCPI = 'N'

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE   PROCEDURE [I_U_Permission]
	(@UserID	[int]
	,@MDAS_Bulk	[int]
	,@MDAS_Scan 	[int] 
	,@MDAS_Import 	[int] 
	,@MDAS_Cancel 	[int] 
	,@MDAS_Revise 	[int] 
	,@MDAS_Append 	[int] 
	,@MDAS_AppendI	[int] 
	,@MDAS_View 	[int] 
	,@MDAS_Print 	[int] 
	,@MDAS_Export 	[int] 
	,@MDAS_Send 	[int] 
	)
AS 
insert into [U_Permission] 
	([UserID]
	,[MDAS_Bulk]
	,[MDAS_Scan]
	,[MDAS_Import]
	,[MDAS_Cancel]
	,[MDAS_Revise]
	,[MDAS_Append]
	,[MDAS_AppendI]
	,[MDAS_View]
	,[MDAS_Print]
	,[MDAS_Export]
	,[MDAS_Send]
	)
values 
	(@UserID
	,@MDAS_Bulk
	,@MDAS_Scan
	,@MDAS_Import
	,@MDAS_Cancel
	,@MDAS_Revise
	,@MDAS_Append
	,@MDAS_AppendI
	,@MDAS_View
	,@MDAS_Print
	,@MDAS_Export
	,@MDAS_Send)

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE  PROCEDURE [I_U_UserFields] 
	@UserID as int,
	@BasedOn as int = 1
AS 

	IF exists (Select UserID FROM dbo.U_UsersFields WHERE UserID = @UserID)
	Delete dbo.U_UsersFields Where UserID = @UserID
	
	Insert into dbo.U_UsersFields (RoleID, UserID, FieldID, SortOrder, GroupID, MultipleIndex, MandatoryStatus, Needed, FieldSize, DataType, SubAppID, LookUpTable, CIHI_ID, 
	                      Header_CIHI_English, Header_CIHI_French, Header_CIHI_Spanish, Header_User, FieldEnabled, FieldVisible, DefaultValue, AppID,  ParamProcID, ParamOrder, ParamName, ParamDataType, ParamSize, NeedForUserDef, UNoteCode)
	SELECT     RoleID, @UserID, FieldID, SortOrder, GroupID, MultipleIndex, MandatoryStatus, Needed, FieldSize, DataType, SubAppID, LookUpTable, CIHI_ID, 
	                      Header_CIHI_English, Header_CIHI_French, Header_CIHI_Spanish, Header_User, FieldEnabled, FieldVisible, DefaultValue, AppID, ParamProcID, ParamOrder, ParamName, ParamDataType, ParamSize, NeedForUserDef, UNoteCode
	FROM         dbo.U_UsersFields
	WHERE     (UserID = @BasedOn)
	Return 0



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE   PROCEDURE [I_U_Users]
	(@BasedOn		[int],
	 @Code			[int],
	 @DisplayCode 		[varchar](12),
	 @UserDescription	[varchar](50),
	 @DefaultDescription	[varchar](50),
	 @CIHIValue		[varchar](12),
	 @Validfrom		[varchar](10),
	 @ValidTo		[varchar](10),
	 @InterfaceIn		[varchar](12),
	 @UserName 		[varchar](50),
	 @UserPassword 		[varchar](50),
	 @PasswordChanged	[datetime],
	 @ChangePassword	[int],
	 @LastName		[varchar](50),
	 @MiddleName 		[varchar](50),
	 @FirstName 		[varchar](50),
	 @IsAdmin		[int],
	 @CanSubmitI 		[int],
	 @CanSubmitS 		[int],
	 @CanSubmitA 		[int],
	 @LanguageID 		[int],
	 @DisplayMessages 	[int],
	 @PermitCPI 		[int],
	 @PermitChartLoc 	[int],
	 @PermitChartDef	[int],
	 @PermitTranscription	[int],
	 @PermitROI		[int],
	 @PermitCCR	 	[int],
	 @PermitInPat	 	[int],
	 @PermitSDS	 	[int],
	 @PermitAmcare	 	[int],
	 @PermitBatchGrouper 	[int],
	 @PermitCareMap		[int],
	 @PermitReportGen 	[int],
	 @PermitCIHISubmit 	[int],
	 @PermitCIHICorrect 	[int],
	 @PermitBatchInterface 	[int],
	 @PermitHL7Interface 	[int],
	 @PermitUndelete 	[int],
	 @PermitHospProf 	[int],
	 @PermitInstProf 	[int],
	 @PermitUserProf 	[int],
	 @PermitLookUpMaint 	[int],
	 @PermitControlFile 	[int],
	 @RoleID		[int],
	 @PermitCCR10	 	[int],
	 @PermitInPat10		[int],
	 @PermitSDS10	 	[int],
	 @PermitAmcare10	[int],
	 @CanSubmitI10		[int],
	 @CanSubmitS10		[int],
	 @CanSubmitA10		[int],
	 @PermitRehab10		[int],
	 @CanSubmitR10  	[int],
	 @PermitClinic 		[int], 
	 @PermitBilling 	[int], 
	 @PermitScheduler 	[int], 
	 @CanSubmitCL 		[int],
	 @TransInitials		[varchar](10),
	 @AutoShowLookUp 	[int],
	 @AutoShowClone 	[int],
	 @CanSubmitC10 		[int],
	 @PermitCCRS10 		[int],
	 @EnableQuickSearch 	[int],
	 @SearchChartPrefix 	[varchar](3),
	 @ShowVIP		[int],
	 @CanModifyCharts 	[int],
	 @FlyCalcGrouper	[int],
	 @UserDateFormat 	[int],
	 @ChangePasswordDate 	[datetime],
	 @FontSize 		[int],
	 @DisplayMultUser 	[int],
	 @HospitalID		[int],
	 @CanResetA 		[int], 
	 @CanResetR 		[int], 
	 @CanResetC 		[int],
	 @PermitVisitHist 	[int], 
	 @PermitDAS 		[int],
	 @FlyCalcCACS 		[int], 
	 @FlyCalcDPG 		[int], 
	 @FlyCalcFIM 		[int], 
	 @FlyCalcRUG 		[int],
	 @DefaultHospID 	[int],
	 @CanSubmitM10 		[int],
 	 @PermitOMHRS10 	[int],
     @LUText 		[varchar](255), 
	 @CanReSetM 		[int],
	 @NTAuthority 		[varchar](100) ,
	 @PermitProvdrMaint 	[int],
	 @PermitRegionProf	[int],
	 @DisplayChrtLinks 	[int],
	 @AccessLockChart 	[int], 
	 @PromptLoc 		[int], 
	 @PromptDef 		[int], 
	 @AmCareFacFile  	[int], 
	 @CCRSFacFile 		[int], 
	 @RehabFacFile 		[int], 
	 @OMHRSFacFile 		[int], 
	 @DADSepFile 		[int], 
	 @CCRSAuditFile 	[int], 
	 @ImportDADErrors 	[int], 
	 @ExecTermChrt 		[int], 
	 @ShowAllRegion 	[int], 
	 @PermitViewChartAct 	[int], 
	 @PermitViewChartDef 	[int], 
	 @PermitChartVolume 	[int], 
	 @PermitWRUUpdates 	[int],
	 @PermitMDASLayer 	[int], 
	 @PermitMDASPrivacy 	[int],
	 @MDASRecordLock 	[int],
	 @MDASSensitvity	[int],
	 @CanPurgeVolQue 	[int],
	 @PermitAdapCS	[int],
	 @PermitCCM 		[int],
	 @CanSubmitCCM 	[int],
     @ImportOMHRSErrors 	[int],
	 @CanViewWho		[int],
	 @FlyCalcSCIPP 		[int],
	 @CanLaunchSolCom 	[int],
	 @CanPurgeLog		[int],
	 @CanDADInstFile    [int],
	 @CanClearCPILock   [int],
	 @PermitCodeSmart	[int],
	 @SetLevelOneCorrection [int],
	 @ShowConfidentialRequest [int],
	 @ModifyRegionalID [int], 
	 @CanSubmitCJRR		[int],
	 @PermitCJRR		[int],
	 @CanReSetCJRR		[int],
	 @FolioCAFile       [varchar](250),
	 @FolioCCIFile      [varchar](250),
	 @SkipLoginScreen   [int],
	 @codeSmartFile     [varchar](250),
	 @PermitEditEngine  [int],
	 @EditEngineFile     [varchar](250),
	 @SelectQueue		[int]
)
AS 
	set @UserPassword = replace(isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 1, 1)) - 10), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 2, 1)) - 11), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 3, 1)) - 12), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 4, 1)) - 13), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 5, 1)) - 14), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 6, 1)) - 15), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 7, 1)) - 16), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 8, 1)) - 17), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 9, 1)) - 18), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 10, 1)) - 19), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 11, 1)) - 20), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 12, 1)) - 21), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 13, 1)) - 22), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 14, 1)) - 23), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 15, 1)) - 24), ''), '               ', '')


--This will check to make sure that the User isn't duplicated
select @Code = Code from U_Users where [DisplayCode] = @DisplayCode AND [UserDescription] = @UserDescription AND [CIHIValue] = @CIHIValue AND [UserName] = @UserName AND [UserPassword] = @UserPassword

if NOT EXISTS(select Code from U_Users where [DisplayCode] = @DisplayCode AND [UserDescription] = @UserDescription AND [CIHIValue] = @CIHIValue AND [UserName] = @UserName AND [UserPassword] = @UserPassword)
begin	
	select @Code= (select max(Code) from U_Users) + 1
	insert into [U_Users] 
		 ([Code],
		 [DisplayCode],
		 [UserDescription],
		 [DefaultDescription],
		 [CIHIValue],
		 [Validfrom],
		 [ValidTo],
         [LUText], 
		 [InterfaceIn],
		 [HospitalID],
		 [DefaultHospID],
		 [UserName],
		 [NTAuthority], 
		 [UserPassword],
		 [PasswordChanged],
		 [ChangePasswordDays],
		 [ChangePasswordDate],
		 [ShowVIP],
		 [CanModifyCharts],
		 [LastName],
		 [MiddleName],
		 [FirstName],
		 [TransInitials],
		 [SearchChartPrefix],
		 [IsAdmin],
		 [CanSubmitI],
		 [CanSubmitS],
		 [CanSubmitA],
		 [CanSubmitI10],
		 [CanSubmitS10],
		 [CanSubmitA10],
		 [CanSubmitC10],
		 [CanSubmitR10],
		 [CanSubmitM10],
		 [CanSubmitCL],
		 [LanguageID],
		 [DisplayMessages],
		 [AutoShowLookUp], 
		 [AutoShowClone],
		 [PermitCPI],
		 [PermitChartLoc],
		 [PermitChartDef],
		 [PermitTranscription],
		 [PermitROI],
		 [PermitCCR],
		 [PermitInPat],
		 [PermitSDS],
		 [PermitAmcare],
		 [PermitCCR10],
		 [PermitInPat10],
		 [PermitSDS10],
		 [PermitAmcare10],
		 [PermitCCRS10], 
		 [PermitRehab10],
		 [PermitOMHRS10],
		 [PermitClinic], 
		 [PermitBatchGrouper],
		 [PermitCareMap],
		 [PermitScheduler], 
		 [PermitReportGen],
		 [PermitCIHISubmit],
		 [PermitCIHICorrect],
		 [PermitBilling], 
		 [PermitBatchInterface],
		 [PermitHL7Interface],
		 [PermitUndelete],
		 [PermitRegionProf], 
		 [PermitHospProf],
		 [PermitInstProf],
		 [PermitUserProf],
		 [PermitLookUpMaint],
		 [PermitProvdrMaint],
		 [PermitControlFile],
		 [RoleID],
		 [PasswordAttempt],
		 [EnableQuickSearch],
		 [FlyCalcGrouper],
		 [UserDateFormat],
	  	 [FontSize],
		 [DisplayMultUser],
		 [CanResetA], 
	 	 [CanResetR], 
		 [CanResetC],
		 [CanReSetM],
		 [PermitVisitHist], 
		 [PermitDAS],
		 [FlyCalcCACS], 
		 [FlyCalcDPG], 
		 [FlyCalcFIM], 
		 [FlyCalcRUG],
	 	 [DisplayChrtLinks],
		 [AccessLockChart], 
		 [PromptLoc], 
		 [PromptDef], 
		 [AmCareFacFile], 
		 [CCRSFacFile], 
		 [RehabFacFile], 
		 [OMHRSFacFile], 
		 [DADSepFile], 
		 [CCRSAuditFile], 
		 [ImportDADErrors], 
		 [ExecTermChrt], 
		 [ShowAllRegion], 
		 [PermitViewChartAct], 
		 [PermitViewChartDef], 
		 [PermitChartVolume], 
		 [PermitWRUUpdates],
		 [PermitMDASLayer], 
		 [PermitMDASPrivacy],
		 [MDASRecordLock],
	 	 [MDASSensitvity],
	 	 [CanPurgeVolQue],
		 [PermitAdapCS],
		 [PermitCCM],
		 [CanSubmitCCM],
         [ImportOMHRSErrors],
		 [CanViewWho],
		 [FlyCalcSCIPP],
		 [CanLaunchSolCom],
		 [CanPurgeLog],
		 [DADInstFile],
		 [CanClearCPILock],
		 [PermitCodeSmart],
		 [SetLevelOneCorrection],
		 [ShowConfidentialRequest],
		 [ModifyRegionalID],
		 [CanSubmitCJRR],
		 [PermitCJRR],
		 [CanReSetCJRR],
		 [FolioCAFile],
		 [FolioCCIFile],
		 [SkipLoginScreen],
		 [codeSmartFile],
		 [PermitEditEngine],
		 [EditEngineFile],
		 [SelectQueue]
		 ) 
	values 
		 (@Code,
		 @DisplayCode,
		 @UserDescription,
		 @DefaultDescription,
		 @CIHIValue,
		 @Validfrom,
		 @ValidTo,
         @LUText, 
		 @InterfaceIn,
		 @HospitalID,
		 @DefaultHospID,
		 @UserName,
		 @NTAuthority,
		 @UserPassword,
		 @PasswordChanged,
		 @ChangePassword,	
		 @ChangePasswordDate,
		 @ShowVIP,
		 @CanModifyCharts, 
		 @LastName,
		 @MiddleName,
		 @FirstName,
		 @TransInitials,
		 @SearchChartPrefix,
		 @IsAdmin,
		 @CanSubmitI,
		 @CanSubmitS,
		 @CanSubmitA,
		 @CanSubmitI10,
		 @CanSubmitS10,
		 @CanSubmitA10,
		 @CanSubmitC10,
		 @CanSubmitR10,
		 @CanSubmitM10,
		 @CanSubmitCL,
		 @LanguageID,
		 @DisplayMessages,
		 @AutoShowLookUp,
		 @AutoShowClone,
		 @PermitCPI,
		 @PermitChartLoc,
		 @PermitChartDef,
		 @PermitTranscription,
		 @PermitROI,
		 @PermitCCR,
		 @PermitInPat,
		 @PermitSDS,
		 @PermitAmcare,
		 @PermitCCR10,
		 @PermitInPat10,
		 @PermitSDS10,
		 @PermitAmcare10,
		 @PermitCCRS10, 
		 @PermitRehab10,
		 @PermitOMHRS10,
		 @PermitClinic, 
		 @PermitBatchGrouper,
		 @PermitCareMap,
		 @PermitScheduler, 
		 @PermitReportGen,
		 @PermitCIHISubmit,
		 @PermitCIHICorrect,
		 @PermitBilling, 
		 @PermitBatchInterface,
		 @PermitHL7Interface,
		 @PermitUndelete,
		 @PermitRegionProf,
		 @PermitHospProf,
		 @PermitInstProf,
		 @PermitUserProf,
		 @PermitLookUpMaint,
		 @PermitProvdrMaint,
		 @PermitControlFile,
		 @RoleID,
		 0,
		 @EnableQuickSearch,
		 @FlyCalcGrouper,
		 @UserDateFormat,
		 @FontSize,
		 @DisplayMultUser,
		 @CanResetA, 
		 @CanResetR, 
		 @CanResetC,
		 @CanReSetM,
		 @PermitVisitHist, 
		 @PermitDAS,
		 @FlyCalcCACS, 
		 @FlyCalcDPG, 
		 @FlyCalcFIM, 
		 @FlyCalcRUG,
	  	 @DisplayChrtLinks,
		 @AccessLockChart, 
		 @PromptLoc, 
		 @PromptDef, 
		 @AmCareFacFile, 
		 @CCRSFacFile, 
		 @RehabFacFile, 
		 @OMHRSFacFile, 
		 @DADSepFile, 
		 @CCRSAuditFile, 
		 @ImportDADErrors, 
		 @ExecTermChrt, 
		 @ShowAllRegion, 
		 @PermitViewChartAct, 
		 @PermitViewChartDef, 
		 @PermitChartVolume, 
		 @PermitWRUUpdates,
		 @PermitMDASLayer, 
		 @PermitMDASPrivacy,
		 @MDASRecordLock,
		 @MDASSensitvity,
	 	 @CanPurgeVolQue,
		 @PermitAdapCS,
		 @PermitCCM,
		 @CanSubmitCCM,
         @ImportOMHRSErrors,
		 @CanViewWho,
		 @FlyCalcSCIPP,
		 @CanLaunchSolCom,
		 @CanPurgeLog,
		 @CanDADInstFile,
		 @CanClearCPILock,
		 @PermitCodeSmart,
		 @SetLevelOneCorrection,
		 @ShowConfidentialRequest,
		 @ModifyRegionalID,
		 @CanSubmitCJRR,
		 @PermitCJRR,
		 @CanReSetCJRR,
		 @FolioCAFile,
		 @FolioCCIFile,
		 @SkipLoginScreen,
		 @codeSmartFile,		 
		 @PermitEditEngine,
		 @EditEngineFile,
		 @SelectQueue
)
	exec I_U_Users_password @Code, @UserPassword	--2.x-0205
end

if @RoleID = 0 
	begin
	EXEC I_U_UserFields @Code, @BasedOn
	end
else if @RoleID <> 0
	begin
	EXEC U_UsersRoles @RoleID
	end

	return @Code

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [I_U_Users_password]
	@UserID int, 	@UserPassword varchar(50)
as

declare @LastDate datetime
declare @count int
declare @minID int

if not exists (select * from dbo.U_Users_Password where UserID = @UserID and UserPassword = @UserPassword)
begin
	Insert into dbo.U_Users_Password(UserID, UserPassword, 	DateStamp)
	select @UserID, @UserPassword, getdate()

	select @count = count(*), @minID = min(RecordID) from dbo.U_Users_Password where UserID = @UserID

	if @count > 50
		delete from U_Users_password where RecordID = @minID
end
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE    PROCEDURE [I_UpdateAudit]
	@AbstractID as int, 
	@Occ as int,
	@FieldID as int, 
	@Coder as int, 
	@OldValue as varchar(255), 
	@NewValue as varchar(255),
	@AppID as int = 201,
	@HospID as int = 0,
	@Extra as varchar(255)	--EN - 00553 
AS
	insert into AB_UpdateAudit values (@Abstractid, @Occ, @Fieldid, @Coder, Getdate(), @OldValue, @NewValue, @AppID, @HospID, @Extra)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE  PROCEDURE [I_UpdateHistory] 
	@AppID as int,
	@AbstractID as int,
	@Coder as int
AS 

declare @HID as int --NP-00025
select @HID = HospitalID from U_Users where Code = @Coder

insert into UH_Main (AppID, RecordID, HospitalID, Coder, Updated) values(@Appid, @HID, @AbstractID, @Coder, GetDate())



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [I_WM_WorkLoad]
	@UserID int ,
	@LogID int ,
	@AppID int ,
	@ModID int ,
	@LinkID int ,	
	@OpID int ,
	@OpType int,
    @LoginID int
AS 

declare @OSDate as datetime
declare @OFDate as datetime

insert WM_WorkLoad 
	(
	UserID ,
	LogID ,
	AppID ,
	ModID ,
	LinkID ,	
	OpID ,
	OpType ,
	OpTime,
    LoginID
	) 
values
	( 
	@UserID ,
	@LogID ,
	@AppID ,
	@ModID ,
	@LinkID ,	
	@OpID ,
	@OpType ,
	getdate(),
    @LoginID	
	)

if @OpType = 18501 and @LogID = 0 
	update WM_Workload set LogID = RecordID where RecordID = @@identity

if @OpType = 18502 and @ModID = 0 
	update WM_Workload set ModID = RecordID where RecordID = @@identity

if (@OpType = 18503 or @OpType = 18504) and @OpID = 0 
	update WM_Workload set OpID = RecordID where RecordID = @@identity

if @OpType = 18508
begin
	select @OSDate = OpTime from WM_Workload where RecordID = @OpID
	select @OFDate = OpTime from WM_Workload where RecordID = @@identity
	update WM_WorkLoad set OpLen = datediff(millisecond, @OSDate, @OFDate) where RecordID = @@identity
end

if @OpType = 18509
begin
	select @OSDate = OpTime from WM_Workload where RecordID = @ModID
	select @OFDate = OpTime from WM_Workload where RecordID = @@identity
	update WM_WorkLoad set OpLen = datediff(second, @OSDate, @OFDate) where RecordID = @@identity
end

if @OpType = 18510
begin
	select @OSDate = OpTime from WM_Workload where RecordID = @LogID
	select @OFDate = OpTime from WM_Workload where RecordID = @@identity
	update WM_WorkLoad set OpLen = datediff(minute, @OSDate, @OFDate) where RecordID = @@identity
end

return @@identity



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--L_AbstractData 401, 4, 20591, 4

CREATE PROCEDURE [L_AbstractData] 
   @AppID as int, 
   @UserID as int, 
   @AbstractID as int, 
   @LogID as int = 0 
AS  
declare @SDate as datetime 
 
declare @sql as nvarchar(1000) 
declare @exec_return int 
 
declare @FieldID as varchar(6) 
declare @SystemName as varchar(50) 
declare @LookupTable as varchar(100)     
declare @TempValue as varchar(50) 
 
declare @ICDType as varchar(1) 
declare @SortOrder as varchar(10) 
declare @DischargeDate as datetime 
declare @AdmitDate as datetime 
declare @CareType as int 
declare @AProv as varchar(10) 
declare @DDAte as varchar(10) 
declare @MultipleIndex as int 
declare @DataType as int 
declare @AB_DiagnosisCount as int 
declare @AB_InterventionCount as int 
declare @AB_ProviderCount as int 
declare @AB_MISCount as int 
declare @AB_PatientServiceCount as int 
declare @AB_ProjectCount as int 
declare @AB_SpecialCareUnitCount as int 
declare @AB_MB_AlcCount as int 
declare @AB_MB_FacilityStudyCount as int 
declare @AB_MB_NonALCCount as int 
declare @AB_TransferServiceCount as int 
declare @AB_PresentingComplaintCount as int --ED-02091
declare @AB_DischargeDiagnosisCount as int --ED-02091
declare @AB_ConsultCount as int --NP - 00151
declare @AB_CCMDrugCount as int --EN - 00487
declare @AB_EDIntervenionCount as int 
declare @AB_InvestigateCount as int 
declare @CC_AID as varchar(20)
declare @AB_SurgicalProcedureCount as int --EN - 00513
declare @AB_Diagnosis_CodeSmartCount as int --EN - 00505
declare @AB_Intervention_CodeSmartCount  as int --EN - 00505
declare @AB_InterventValueSetCount int

set nocount on 
 
create table #LoadResults  
( 
    SortOrder int,  
    FieldID int,  
    Occurrence int, 
    Code int, 
    DisplayCode varchar(50), 
    UserDescription varchar(8000), 
    CIHIValue varchar(50),  
    Validfrom datetime,  
    ValidTo datetime 
) 
 
select      
    dbo.AB_Abstract.*, dbo.AB_Ancillary.AncillaryField1, dbo.AB_Ancillary.AncillaryField2, dbo.AB_Ancillary.AncillaryField3,  
    dbo.AB_Ancillary.AncillaryField4, dbo.AB_Ancillary.AncillaryField5, dbo.AB_Ancillary.AncillaryField6, dbo.AB_Ancillary.AncillaryField7,  
    dbo.AB_Ancillary.AncillaryField8, dbo.AB_Ancillary.AncillaryField9, dbo.AB_Ancillary.AncillaryField10, dbo.AB_Ancillary.AncillaryField11,  
    dbo.AB_Ancillary.AncillaryField12, dbo.AB_Ancillary.AncillaryField13, dbo.AB_Ancillary.AncillaryField14, dbo.AB_Ancillary.AncillaryField15,  
    dbo.AB_Ancillary.AncillaryField16, dbo.AB_Ancillary.AncillaryField17, dbo.AB_BasicOption.BasicOption1, dbo.AB_BasicOption.BasicOption2,  
    dbo.AB_BasicOption.BasicOption3, dbo.AB_BasicOption.BasicOption4, dbo.AB_BasicOption.BasicOption5, dbo.AB_BasicOption.BasicOption6,  
    dbo.AB_BasicOption.BasicOption7, dbo.AB_BasicOption.BasicOption8, dbo.AB_BasicOption.BasicOption9, dbo.AB_BasicOption.BasicOption10,  
    dbo.AB_BasicOption.BasicOption11, dbo.AB_BasicOption.BasicOption12, dbo.AB_BasicOption.BasicOption13, dbo.AB_BasicOption.BasicOption14,  
    dbo.AB_BasicOption.BasicOption15, dbo.AB_BasicOption.BasicOption16, dbo.AB_BasicOption.BasicOption17, dbo.AB_BasicOption.BasicOption18,  
    dbo.AB_BasicOption.BasicOption19, dbo.AB_Blood.TransfusionIndicator, dbo.AB_Blood.RedBloodCell, dbo.AB_Blood.RedCellTyped,  
    dbo.AB_Blood.RedCellUnits, dbo.AB_Blood.RedCellXMatch, dbo.AB_Blood.Platelets, dbo.AB_Blood.PlateletsTyped, dbo.AB_Blood.PlateletsUnits,  
    dbo.AB_Blood.PlateletsXMatch, dbo.AB_Blood.Plasma, dbo.AB_Blood.PlasmaTyped, dbo.AB_Blood.PlasmaUnits, dbo.AB_Blood.PlasmaXMatch,  
    dbo.AB_Blood.Albumin, dbo.AB_Blood.AlbuminTyped, dbo.AB_Blood.AlbuminUnits, dbo.AB_Blood.AlbuminXMatch, dbo.AB_Blood.OtherBlood,  
    dbo.AB_Blood.OtherBloodTyped, dbo.AB_Blood.OtherBloodUnits, dbo.AB_Blood.OtherBloodXMatch, dbo.AB_Blood.AutoTransfusion,  
    dbo.AB_Blood.CryoprecipitatePlasma, dbo.AB_Blood.CryosupernatantPlasma, dbo.AB_Blood.IVIG_SCIG, dbo.AB_Blood.Fibrinogen, 
    dbo.AB_Blood.PCC, dbo.AB_Blood.FEIBA, dbo.AB_Blood.AntithrombinIII, dbo.AB_Blood.C1Inhibitor, 
	dbo.AB_Blood.ProteinC_OtherFactors,
    dbo.AB_CancerStaging.ClinicalTumor, dbo.AB_CancerStaging.ClinicalNode, dbo.AB_CancerStaging.ClinicalMetastasis,  
    dbo.AB_CancerStaging.PathTumor, dbo.AB_CancerStaging.PathNode, dbo.AB_CancerStaging.PathMetastasis, dbo.AB_CancerStaging.SummaryStage,  
    dbo.AB_DeathInformation.AutopsyPerformed, dbo.AB_DeathInformation.CoronerCase, dbo.AB_DeathInformation.DeathInSCU,  
    dbo.AB_DeathInformation.DeathInOR, dbo.AB_DeathInformation.DeathLessTwoPO, dbo.AB_DeathInformation.DeathTwoTenPO,  
    dbo.AB_DeathInformation.DeathGreaterTenPO, dbo.AB_DeathInformation.DeathAfterAdmit, dbo.AB_DeathInformation.DeathOnArrival,  
    dbo.AB_DeathInformation.DeathInER, dbo.AB_DeathInformation.TraumaDeath, dbo.AB_DeathInformation.PregnancyDeath,  
    dbo.AB_DeathInformation.OtherDeath, dbo.AB_MentalHealth.MentalReferralSource, dbo.AB_MentalHealth.MentalAdmitMethod,  
    dbo.AB_MentalHealth.MentalLegalStatus, dbo.AB_MentalHealth.MentalAWOL, dbo.AB_MentalHealth.MentalSuicide,  
    dbo.AB_MentalHealth.MentalPrevPsych, dbo.AB_MentalHealth.MentalReferralTo, dbo.AB_MentalHealth.MentalECTTreatment,  
    dbo.AB_MentalHealth.MentalNumberECT, dbo.AB_MentalHealth.MentalEducation, dbo.AB_MentalHealth.MentalEmployment,  
    dbo.AB_MentalHealth.MentalFinancial, 
    dbo.AB_MentalHealth.LegalStatusUponArrivaltoED, dbo.AB_MentalHealth.LegalStatusAtAdmission,
    dbo.AB_MentalHealth.TypeOfRestraint01, dbo.AB_MentalHealth.FrequencyOfRestraint01, 
    dbo.AB_MentalHealth.TypeOfRestraint02, dbo.AB_MentalHealth.FrequencyOfRestraint02, 
    dbo.AB_MentalHealth.TypeOfRestraint03, dbo.AB_MentalHealth.FrequencyOfRestraint03, 
    dbo.AB_MentalHealth.TypeOfRestraint04, dbo.AB_MentalHealth.FrequencyOfRestraint04, 

    dbo.AB_ReproductiveCare.PrevTermDelivery, dbo.AB_ReproductiveCare.PrevPreTermDelivery,  
    dbo.AB_ReproductiveCare.PrevSpontAbortions, dbo.AB_ReproductiveCare.PrevInduceAbortions, dbo.AB_ReproductiveCare.PrevLiveBirths,  
    dbo.AB_ReproductiveCare.GestationalAge, dbo.AB_ReproductiveCare.AbortionDate, dbo.AB_ReproductiveCare.DeliveryDate,  
    dbo.AB_ReproductiveCare.DeliveryTime, dbo.AB_ReproductiveCare.LastMensesDate, dbo.AB_ReproductiveCare.BreastFeeding,  
    dbo.AB_ReproductiveCare.InitialOR, dbo.AB_ReproductiveCare.SubsequentOR, dbo.AB_ReproductiveCare.Sterilization,  
    dbo.AB_ReproductiveCare.Complication1, dbo.AB_ReproductiveCare.Complication2, dbo.AB_ReproductiveCare.Complication3,  
    dbo.AB_ReproductiveCare.ReprodComments, dbo.AB_Therapeutic.PhysioTherapy, dbo.AB_Therapeutic.PhysioUnits,  
    dbo.AB_ReproductiveCare.LaborLOS, dbo.AB_ReproductiveCare.LaborLOSHour,
    dbo.AB_Therapeutic.OccupationalTherapy, dbo.AB_Therapeutic.OccupationalUnits, dbo.AB_Therapeutic.SpeechTherapy,  
    dbo.AB_Therapeutic.SpeechUnits, dbo.AB_Therapeutic.RespiratoryTherapy, dbo.AB_Therapeutic.RespiratoryUnits,  
    dbo.AB_Therapeutic.FirstOptionTherapy, dbo.AB_Therapeutic.FirstOptionUnits, dbo.AB_Therapeutic.SecondOptionTherapy,  
    dbo.AB_Therapeutic.SecondOptionUnits, dbo.AB_VendorAssigned.VendorID, dbo.AB_VendorAssigned.MCC, dbo.AB_VendorAssigned.CMG,  
    dbo.AB_VendorAssigned.Plx, dbo.AB_VendorAssigned.RIW, dbo.AB_VendorAssigned.DPG, UDDate1, UDDate2, UDDate3, UDDate4, UDDate5, UDTime1, UDTime2, UDTime3, UDTime4, UDTime5, UDLookup1, UDLookup2, UDLookup3, UDLookup4, UDLookUp5, UDInteger1,  
    UDInteger2, UDInteger3, UDInteger4, UDInteger5, UDText1, UDText2, UDText3, UDText4, UDText5, UDSmallText1, UDSmallText2, UDSmallText3,  UDSmallText4,  UDSmallText5, AbstractType, PreviousName, PrimaryPhone, PrimaryAddress, PrimaryAddress2, EmployerName, RegistrantLastName, RegistrantFirstName,  
    DeclarationNumber, MHInstfrom, MHInstTo, AnestheticLabor, PrenatalVisitDate, NumberPrenatalVisits, Gravida, Parity, ObsEducation,  
    SmokingPerDay, SmokingQuitDate, AlcoholDuringPregnancy, Days_WeekAlcoholConsumed, DrinksPerday, PreConceptionalFolicAcid,  
    PostConceptionalFolicAcid, FirstStageDate, FirstStageTime, FirstStageDuration, SecondStageDate, SecondStageTime, SecondStageDuration,  
    Presentation, RoutineCare, FreeFlowOxygen, BagVentilation, IntubationNotMeconium, MedicationResuscitation, NarconMaloxone, ChestCompressions,  
    Feeding, Meconium, Apgar1Min, Apgar5Min, Gestation, MotherPHIN, Elopements, LeaveCertificates, FirstStageDateUnknown, SecondStageDateUnknown, PrenatalVisitDateUnknown, SmokingQuitDateUnknown, ALC_TotalDays, MB_Autopsy, MB_Weight, NumberPrenatal, PresentDelivery, PositionDelviery, HCNExpiredDate, --, CIHI_AbstractID   
    [AB_NACRS].[SpecialistRequestDate], [AB_NACRS].[SpecialistRequestTime], [AB_NACRS].[SpecialistRequestTimeUnknown], [AB_NACRS].[SpecialistNumber], [AB_NACRS].[SpecialistService], --ED-2091
    [AB_NACRS].[NonPhysicianAssessmentDate], [AB_NACRS].[NonPhysicianAssessmentTime], [AB_NACRS].[NonPhysicianAssessmentTimeUnknown], [AB_NACRS].[NonPhysicianNumber], [AB_NACRS].[NonPhysicianService], --ED-2091
    [AB_NACRS].[AmCareTypeCode], [AB_NACRS].[AmCareGroup],
    [AB_NACRS].StatusAfterTriage, [AB_NACRS].EDVisitIndicator,
    AB_ReproductiveCare.DeliveryTimeUnknown,
    --ED - 02336
    CancerCareVisit, VisitProgramCode, CCMVisitType, InpatientFlag, RadiationReviewFlag, ChemoFlag, ClinicalTrialFlag, HealthCareProviderNumber,
	CourseOfRadiationTreatment, CourseCompleteFlag, NHPIPCode, BodyRegionCode, DosePerFraction, IntentOfRadiationTreatment, DecisionToTreatDate, ReadyToTreatDate, UrgencyCategory, TreatmentUnitName,
    RTProtocol,
	--EN - 00487 CCORegimen, CCODrugCode, CCMDIN, DrugOriginFlag, BodySurfaceArea, DoseAdministered, MeasurementUnit, Route, IntentOfSystemicTreatment, LineOfTherapy, 
	ArrivedByNotTreatedFlag, AlcoholQuitDate, AlcoholQuitDateUnknown, SmokingInPregnancy
	--EN-00524
	,[UDDate6],[UDDate7],[UDDate8],[UDDate9],[UDDate10]
	,[UDDate11],[UDDate12],[UDDate13],[UDDate14],[UDDate15]
	,[UDDate16],[UDDate17],[UDDate18],[UDDate19],[UDDate20]
	,[UDDate21],[UDDate22],[UDDate23],[UDDate24],[UDDate25]
	,[UDTime6],[UDTime7],[UDTime8],[UDTime9],[UDTime10]
	,[UDTime11],[UDTime12],[UDTime13],[UDTime14],[UDTime15]
	,[UDTime16],[UDTime17],[UDTime18],[UDTime19],[UDTime20]
	,[UDTime21],[UDTime22],[UDTime23],[UDTime24],[UDTime25]
	,[UDLookUp6],[UDLookUp7],[UDLookUp8],[UDLookUp9],[UDLookUp10]
	,[UDLookUp11],[UDLookUp12],[UDLookUp13],[UDLookUp14],[UDLookUp15]
	,[UDLookUp16],[UDLookUp17],[UDLookUp18],[UDLookUp19],[UDLookUp20]
	,[UDLookUp21],[UDLookUp22],[UDLookUp23],[UDLookUp24],[UDLookUp25]
	,[UDInteger6],[UDInteger7],[UDInteger8],[UDInteger9],[UDInteger10]
	,[UDInteger11],[UDInteger12],[UDInteger13],[UDInteger14],[UDInteger15]
	,[UDInteger16],[UDInteger17],[UDInteger18],[UDInteger19],[UDInteger20]
	,[UDInteger21],[UDInteger22],[UDInteger23],[UDInteger24],[UDInteger25]
	,[UDText6],[UDText7],[UDText8],[UDText9],[UDText10]
	,[UDText11],[UDText12],[UDText13],[UDText14],[UDText15]
	,[UDText16],[UDText17],[UDText18],[UDText19],[UDText20]
	,[UDText21],[UDText22],[UDText23],[UDText24],[UDText25]
	,[UDSmallText6],[UDSmallText7],[UDSmallText8],[UDSmallText9],[UDSmallText10]
	,[UDSmallText11],[UDSmallText12],[UDSmallText13],[UDSmallText14],[UDSmallText15]
	,[UDSmallText16],[UDSmallText17],[UDSmallText18],[UDSmallText19],[UDSmallText20]
	,[UDSmallText21],[UDSmallText22],[UDSmallText23],[UDSmallText24],[UDSmallText25]
    , QBP_BilateralJointReplacement, QBP_ChronicObstructivePulmonary, QBP_CongestiveHeartFailure, QBP_CS_Abdominal, QBP_CSBone, QBP_CSBreastDelayedReconstruction, QBP_CSBreastImmediateReconstruction, QBP_CSBreastNoReconstruction, QBP_CSColorectal, QBP_CSEndocrineOther, QBP_CSEsophagus, QBP_CSGastric, QBP_CSGentourinary, QBP_CSGynecology, QBP_CSHNK, QBP_CSLiver, QBP_CSLung, QBP_CSNeuroBrain, QBP_CSNeuroSpinal, QBP_CSNonSiteSpecific, QBP_CSPancreas, QBP_CSProstate, QBP_CSSkinLymphNode, QBP_CSSkinSoftTissue, QBP_CSSoftTissue, QBP_CSThorax, QBP_CSThyroid, QBP_HipFracture, QBP_CornealTransplant, QBP_KneeAthroscopy, QBP_VascularLower, QBP_VascularAortic, QBP_SpineInstruIP, QBP_SpineNonInstruDay, QBP_SpineNonInstruIP, QBP_BilateralCataracts, QBP_Pneumonia, QBP_ShoulderArthroplasties, QBP_ShoulderOther, QBP_ShoulderRepairs, QBP_ShoulderReverseArthroplaties, QBP_StrokeAcuteHemorrhage, QBP_StrokeAcuteIschemic, QBP_StrokeAcuteTransient, QBP_StrokeEndovascularTherapy, QBP_UnilateralHipReplacement, QBP_UnilateralKneeReplacement, QBP_Tonsillectomy, QBP_NonCancerHysterectomy, QBP_Retinal	
into #ABMainTemp 
from          
dbo.AB_Abstract  with (nolock) 
left join dbo.AB_Ancillary        with (nolock) on dbo.AB_Abstract.AbstractID = dbo.AB_Ancillary.AbstractID  
left join dbo.AB_BasicOption      with (nolock) on dbo.AB_Abstract.AbstractID = dbo.AB_BasicOption.AbstractID  
left join dbo.AB_Blood            with (nolock) on dbo.AB_Abstract.AbstractID = dbo.AB_Blood.AbstractID  
left join dbo.AB_CancerStaging    with (nolock) on dbo.AB_Abstract.AbstractID = dbo.AB_CancerStaging.AbstractID  
left join dbo.AB_DeathInformation with (nolock) on dbo.AB_Abstract.AbstractID = dbo.AB_DeathInformation.AbstractID  
left join dbo.AB_MentalHealth     with (nolock) on dbo.AB_Abstract.AbstractID = dbo.AB_MentalHealth.AbstractID  
left join dbo.AB_ReproductiveCare with (nolock) on dbo.AB_Abstract.AbstractID = dbo.AB_ReproductiveCare.AbstractID  
left join dbo.AB_Therapeutic      with (nolock) on dbo.AB_Abstract.AbstractID = dbo.AB_Therapeutic.AbstractID  
left join dbo.AB_VendorAssigned   with (nolock) on dbo.AB_Abstract.AbstractID = dbo.AB_VendorAssigned.AbstractID  
left join dbo.AB_UDAbstracting    with (nolock) on dbo.AB_Abstract.AbstractID = dbo.AB_UDAbstracting.AbstractID   
left join dbo.AB_Manitoba         with (nolock) on dbo.AB_Abstract.AbstractID = dbo.AB_Manitoba.AbstractID 
left join dbo.AB_NACRS            with (nolock) on dbo.AB_Abstract.AbstractID = dbo.AB_NACRS.AbstractID --ED-02091
left join dbo.AB_CCM_CancerCareInformation with (nolock) on dbo.AB_Abstract.AbstractID = dbo.AB_CCM_CancerCareInformation.AbstractID
left join dbo.AB_CCM_Radiation with (nolock) on dbo.AB_Abstract.AbstractID = dbo.AB_CCM_Radiation.AbstractID
--left join dbo.AB_CCM_SystemicDrug on dbo.AB_Abstract.AbstractID = dbo.AB_CCM_SystemicDrug.AbstractID
left join dbo.AB_UDFieldsDate with (nolock) on dbo.AB_Abstract.AbstractID = dbo.AB_UDFieldsDate.AbstractID --EN-00524
left join dbo.AB_UDFieldsTime with (nolock) on dbo.AB_Abstract.AbstractID = dbo.AB_UDFieldsTime.AbstractID --EN-00524
left join dbo.AB_UDFieldsLookUp with (nolock) on dbo.AB_Abstract.AbstractID = dbo.AB_UDFieldsLookUp.AbstractID --EN-00524
left join dbo.AB_UDFieldsInteger with (nolock) on dbo.AB_Abstract.AbstractID = dbo.AB_UDFieldsInteger.AbstractID --EN-00524
left join dbo.AB_UDFieldsText with (nolock) on dbo.AB_Abstract.AbstractID = dbo.AB_UDFieldsText.AbstractID --EN-00524
left join dbo.AB_UDFieldsSmallText with (nolock) on dbo.AB_Abstract.AbstractID = dbo.AB_UDFieldsSmallText.AbstractID --EN-00524
left join dbo.AB_QBP_Flag with (nolock) on dbo.AB_Abstract.AbstractID = dbo.AB_QBP_Flag.AbstractID --2.x-1772
--left join dbo.AB_Submission         on dbo.AB_Abstract.AbstractID = dbo.AB_Submission.AbstractID 
where dbo.AB_Abstract.AbstractID = @AbstractID 

select * into #AB_Diagnosis from AB_Diagnosis where AbstractID = @AbstractID -- MultipleIndex 3, 13, 32 
set @AB_DiagnosisCount = @@rowcount 
select * into #AB_Intervention from AB_Intervention where AbstractID = @AbstractID-- MultipleIndex 4, 14, 33 
set @AB_InterventionCount = @@rowcount 
select * into #AB_Provider from AB_Provider where AbstractID = @AbstractID-- MultipleIndex 2, 12, 31 
set @AB_ProviderCount = @@rowcount 
select * into #AB_MIS from AB_MIS where AbstractID = @AbstractID-- MultipleIndex 34 
set @AB_MISCount = @@rowcount 
select * into #AB_PatientService from AB_PatientService where AbstractID = @AbstractID-- MultipleIndex 1, 11 
set @AB_PatientServiceCount = @@rowcount 
select * into #AB_Project from AB_Project where AbstractID = @AbstractID-- MultipleIndex 6, 16, 35 
set @AB_ProjectCount = @@rowcount 
select * into #AB_SpecialCareUnit from AB_SpecialCareUnit where AbstractID = @AbstractID-- MultipleIndex 5, 15 
set @AB_SpecialCareUnitCount = @@rowcount 
select * into #AB_MB_Alc from AB_MB_Alc where AbstractID = @AbstractID-- MultipleIndex 18 
set @AB_MB_AlcCount = @@rowcount 
select * into #AB_MB_FacilityStudy from AB_MB_FacilityStudy where AbstractID = @AbstractID-- MultipleIndex 17 
set @AB_MB_FacilityStudyCount = @@rowcount 
select * into #AB_MB_NonALC from AB_MB_NonALC where AbstractID = @AbstractID-- MultipleIndex 19 
set @AB_MB_NonALCCount = @@rowcount 
select * into #AB_TransferService from AB_TransferService where AbstractID = @AbstractID -- MultipleIndex 20 
set @AB_TransferServiceCount = @@rowcount 

select * into #AB_PresentingComplaints from AB_PresentingComplaints where AbstractID = @AbstractID -- MultipleIndex 36 --ED-02091
set @AB_PresentingComplaintCount = @@rowcount  
select * into #AB_DischargeDiagnosis from AB_DischargeDiagnosis where AbstractID = @AbstractID -- MultipleIndex 37 --ED-02091
set @AB_DischargeDiagnosisCount = @@rowcount 
select * into #AB_Consult from AB_Consult where AbstractID = @AbstractID -- MultipleIndex 38 --NP - 00151
set @AB_ConsultCount = @@rowcount 
select * into #AB_CCM_SystemicDrug from AB_CCM_SystemicDrug where AbstractID = @AbstractID -- MultipleIndex 39 --EN - 00487
set @AB_CCMDrugCount = @@rowcount 

select * into #AB_EDInterventionPicklist from AB_EDInterventionPicklist where AbstractID = @AbstractID -- MultipleIndex 42
set @AB_EDIntervenionCount = @@rowcount 
select * into #AB_InvestigativeTechnology from AB_InvestigativeTechnology where AbstractID = @AbstractID -- MultipleIndex 43
set @AB_InvestigateCount = @@rowcount 
select * into #AB_EDInterventionValueSet from AB_EDInterventionValueSet where AbstractID = @AbstractID -- MultipleIndex 44
set @AB_InterventValueSetCount = @@rowcount 

select * into #AB_SurgicalProcedure from AB_SurgicalProcedure where AbstractID = @AbstractID -- MultipleIndex 21 --EN - 00513
set @AB_SurgicalProcedureCount = @@rowcount 

select * into #AB_Diagnosis_CodeSmart from AB_Diagnosis_CodeSmart where AbstractID = @AbstractID -- MultipleIndex 21 --EN - 00505
set @AB_Diagnosis_CodeSmartCount = @@rowcount 
select * into #AB_Intervention_CodeSmart from AB_Intervention_CodeSmart where AbstractID = @AbstractID -- MultipleIndex 21 --EN - 00505
set @AB_Intervention_CodeSmartCount = @@rowcount 

select  
    dbo.U_Fields.FieldID,  
    dbo.U_Fields.SystemName,  
    dbo.U_UsersFields.LookUpTable,  
    dbo.U_UsersFields.MultipleIndex,  
    dbo.U_UsersFields.DataType,  
    dbo.U_UsersFields.SortOrder  
into #UsersFields 
from dbo.U_Fields  
join dbo.U_UsersFields on dbo.U_Fields.FieldID = dbo.U_UsersFields.FieldID 
where dbo.U_UsersFields.UserID = @UserID  
and dbo.U_UsersFields.AppID = @AppID 
and dbo.U_Fields.IsGroup = 0 
and dbo.U_UsersFields.DataType <> 100000  
and dbo.U_Fields.FieldID not between 60000 and 80000 
ORDER BY dbo.U_UsersFields.SortOrder 
 
update #UsersFields set LookupTable = 'LU_ProviderService' where LookupTable = 'LLU_ProviderServices' 
update #UsersFields set LookupTable = 'LU_ProviderSpecialty' where LookupTable = 'LLU_ProviderSpecialty' 
update #UsersFields set LookupTable = 'LU_CodeFile' where isnumeric(LookupTable) = 1 
 
select @ICDType = icdtype, @DischargeDate = dischargedate, @AdmitDate = admitdate, @CareType = CareType from AB_Abstract 
where (dbo.AB_Abstract.AbstractID = @AbstractID)  
select @AProv = LU_Province.CIHIValue from H_HospitalProfile left join 
dbo.LU_Province on dbo.H_HospitalProfile.ProvinceNumber = dbo.LU_Province.Code 
 
if isdate(@DischargeDate) = 0 or @CareType = 5 
   set @DischargeDate = @AdmitDate 
 
set @DDate = convert(varchar(10), @DischargeDate, 101) 
 
if isdate(@DDate) = 0 and isnull(@AdmitDate, 0) = 0 begin 
   if @ICDType = 'T' and @AProv in ('BC', 'SK', 'NS') 
       set @DDate = '2001/04/01' 
   else if @ICDType = 'T' 
       set @DDate = '2002/04/01' 
   else 
       set @DDate = '2002/03/30' 
end 
else if isdate(@DDate) = 0 and isnull(@AdmitDate, 0) <> 0 
    set @DDate = convert(varchar(10), @AdmitDate, 101) 
 
if @ICDType = 'T' begin 
   update #UsersFields set LookupTable = 'ICD_DiagFile10' where DataType = 60 
   update #UsersFields set LookupTable = 'ICD_ProcFile10' where DataType = 61 
end 
else if @ICDType = 'C' begin 
   update #UsersFields set LookupTable = 'ICD_DiagFile9cm' where DataType = 60 
   update #UsersFields set LookupTable = 'ICD_ProcFile9cm' where DataType = 61 
end 
else if @ICDType = '9' begin 
   update #UsersFields set LookupTable = 'ICD_DiagFile9' where DataType = 60 
   update #UsersFields set LookupTable = 'ICD_ProcFile9' where DataType = 61 
end 
 
declare cur cursor fast_forward for 
 
    select FieldID, SystemName, LookUpTable, MultipleIndex, DataType, SortOrder  
    from #UsersFields 
 
open cur 
 
fetch next from cur into @FieldID, @SystemName, @LookupTable, @MultipleIndex, @DataType, @SortOrder 
 
while @@Fetch_Status = 0 begin 
    set @sql = '' 
 
    if @MultipleIndex in (1, 11) begin  
        if isnull(@LookupTable, '') = '' and @AB_PatientServiceCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', ServiceOccurrence, null, null, ' + @SystemName + ', null, null, null from #AB_PatientService' 
        else if @AB_PatientServiceCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', ServiceOccurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_PatientService t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code' 
    end 
 
    else if @MultipleIndex in (3, 13, 32) begin 
        if isnull(@LookupTable, '') = '' and @AB_DiagnosisCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', DiagnosisOccurrence, null, null, ' + @SystemName + ', null, null, null from #AB_Diagnosis' 
        else if @AB_DiagnosisCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', DiagnosisOccurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_Diagnosis t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code' 
    end 
 
    else if @MultipleIndex in (4, 14, 33) begin 
        if isnull(@LookupTable, '') = '' and @AB_InterventionCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', IntervOccurrence, null, null, ' + @SystemName + ', null, null, null from #AB_Intervention' 
        else if @LookupTable in ('LU_IntervAttStatus', 'LU_IntervAttLocation', 'LU_IntervAttExtent') and @AB_InterventionCount > 0 begin  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', IntervOccurrence, isnull(Code, 0), DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_Intervention t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code '  
 
            if @AppID in (301, 401)   
                set @sql = @sql + ' where isnull(Sector, 0) in (0, 3, 2)'  
            else  
                set @sql = @sql + ' where isnull(Sector, 0) in (0, 3, 1)'  
		print @sql
        end  
        else if @AB_InterventionCount > 0  
           set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', IntervOccurrence, isnull(Code, 0), DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_Intervention t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code' 
    end 
 
    else if @MultipleIndex in (6, 16, 35) begin 
        if isnull(@LookupTable, '') = '' and @AB_ProjectCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', ProjectOccurrence, null, null, ' + @SystemName + ', null, null, null from #AB_Project' 
        else if @AB_ProjectCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', ProjectOccurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_Project t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code' 
    end 
 
    else if @MultipleIndex in (2, 12, 31) begin 
        if isnull(@LookupTable, '') = '' and @AB_ProviderCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', ProviderOccurrence, null, null, ' + @SystemName + ', null, null, null from #AB_Provider' 
        else if @AB_ProviderCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', ProviderOccurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_Provider t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code' 
    end 
 
    else if @MultipleIndex in (5, 15) begin 
        if isnull(@LookupTable, '') = '' and @AB_SpecialCareUnitCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', SCUOccurrence, null, null, ' + @SystemName + ', null, null, null from #AB_SpecialCareUnit' 
        else if @AB_SpecialCareUnitCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', SCUOccurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_SpecialCareUnit t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code' 
    end 
 
    else if @MultipleIndex in (18) begin 
        if isnull(@LookupTable, '') = '' and @AB_MB_AlcCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, null, null, ' + @SystemName + ', null, null, null from #AB_MB_Alc' 
        else if @AB_MB_AlcCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_MB_Alc t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code' 
    end 
 
    else if @MultipleIndex in (19) begin 
        if isnull(@LookupTable, '') = '' and @AB_MB_NonALCCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, null, null, ' + @SystemName + ', null, null, null from #AB_MB_NonALC' 
        else if @AB_MB_NonALCCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_MB_NonALC t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code' 
    end 
 
    else if @MultipleIndex in (17) begin 
        if isnull(@LookupTable, '') = '' and @AB_MB_FacilityStudyCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, null, null, ' + @SystemName + ', null, null, null from #AB_MB_FacilityStudy' 
        else if @AB_MB_FacilityStudyCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_MB_FacilityStudy t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code' 
    end 
 
    else if @MultipleIndex in (20) begin 
        if isnull(@LookupTable, '') = '' and @AB_TransferServiceCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, null, null, ' + @SystemName + ', null, null, null from #AB_TransferService' 
        else if @AB_TransferServiceCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_TransferService t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code' 
    end 

    else if @MultipleIndex in (21) begin 
        if isnull(@LookupTable, '') = '' and @AB_SurgicalProcedureCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence = SurgicalOccurrence, null, null, ' + @SystemName + ', null, null, null from #AB_SurgicalProcedure' 
        else if @AB_SurgicalProcedureCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence = SurgicalOccurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_SurgicalProcedure t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code' 
    end 

    else if @MultipleIndex in (22, 40) begin --EN - 00505
        if isnull(@LookupTable, '') = '' and @AB_Diagnosis_CodeSmartCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence = cSDiagnosisOccurrence, null, null, ' + @SystemName + ', null, null, null from #AB_Diagnosis_CodeSmart' 
        else if @AB_Diagnosis_CodeSmartCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence = cSDiagnosisOccurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_Diagnosis_CodeSmart t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code' 
    end 

    else if @MultipleIndex in (23, 41) begin --EN - 00505
        if isnull(@LookupTable, '') = '' and @AB_Intervention_CodeSmartCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence = cSInterventionOccurrence, null, null, ' + @SystemName + ', null, null, null from #AB_Intervention_CodeSmart' 
        else if @AB_Intervention_CodeSmartCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence = cSInterventionOccurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_Intervention_CodeSmart t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code' 
    end 
 
    else if @MultipleIndex in (34) begin -- 50 begin 
        if isnull(@LookupTable, '') = '' and @AB_MISCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', MISOccurrence, null, null, cast(' + @SystemName + ' as varchar(255)), null, null, null from #AB_MIS' 
        else if @AB_MISCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', MISOccurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_MIS t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code' 
    end 

    else if @MultipleIndex in (36) begin -- ED-02091
        if isnull(@LookupTable, '') = '' and @AB_PresentingComplaintCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, null, null, cast(' + @SystemName + ' as varchar(255)), null, null, null from #AB_PresentingComplaints' 
        else if @AB_PresentingComplaintCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_PresentingComplaints t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code' 
    end 

    else if @MultipleIndex in (37) begin -- ED-02091
        if isnull(@LookupTable, '') = '' and @AB_DischargeDiagnosisCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, null, null, cast(' + @SystemName + ' as varchar(255)), null, null, null from #AB_DischargeDiagnosis' 
        else if @AB_DischargeDiagnosisCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_DischargeDiagnosis t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code' 
    end 
 
    else if @MultipleIndex in (38) begin -- NP - 00151
    
        if isnull(@LookupTable, '') = '' and @AB_ConsultCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, null, null, cast(' + @SystemName + ' as varchar(255)), null, null, null from #AB_Consult' 
        else if @AB_ConsultCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_Consult t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code' 
               
    end            

    else if @MultipleIndex in (39) begin -- EN - 00487
        if isnull(@LookupTable, '') = '' and @AB_CCMDrugCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, null, null, cast(' + @SystemName + ' as varchar(255)), null, null, null from #AB_CCM_SystemicDrug' 
        else if @AB_CCMDrugCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_CCM_SystemicDrug t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code' 
        
    end 

    else if @MultipleIndex in (42) begin -- 
        if isnull(@LookupTable, '') = '' and @AB_EDIntervenionCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, null, null, cast(' + @SystemName + ' as varchar(255)), null, null, null from #AB_EDInterventionPicklist' 
        else if @AB_EDIntervenionCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_EDInterventionPicklist t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code' 
        
    end 

    else if @MultipleIndex in (43) begin -- 
        if isnull(@LookupTable, '') = '' and @AB_InvestigateCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, null, null, cast(' + @SystemName + ' as varchar(255)), null, null, null from #AB_InvestigativeTechnology' 
        else if @AB_InvestigateCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_InvestigativeTechnology t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code' 
        
    end 

    else if @MultipleIndex in (44) begin -- 
        if isnull(@LookupTable, '') = '' and @AB_InterventValueSetCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, null, null, cast(' + @SystemName + ' as varchar(255)), null, null, null from #AB_EDInterventionValueSet' 
        else if @AB_InterventValueSetCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from #AB_EDInterventionValueSet t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code' 
        
    end 

    else begin 
        if isnull(@LookupTable, '') = '' and @SystemName <> 'CancerCareVisit' begin 
            if @SystemName <> 'AbstractNotes'  
                set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', 0, null, null, ' + @SystemName + ', null, null, null from #ABMainTemp' 
        end 
        else if @SystemName = 'PostalCode' begin 
            set @sql = 'select @TempV =  ' + @SystemName + '  from #ABMainTemp' 
            exec sp_executesql @sql, N'@TempV varchar(50) output', @TempValue Output 
            set @sql = '' 
            --PR - 3362 client put single quote in postal code
            if isnull(@TempValue, '') <> ''  
                set @sql =  
                    'select top 1 ' + @SortOrder + ', ' + @fieldid + ', 0, Code, ''' + replace(left(@TempValue, 3), '''', '''''') + ' ' + replace(substring(@TempValue, 4, 3), '''', '''''') + ''', UserDescription, ''' + replace(@TempValue, '''', '''''') + ''', Validfrom, ValidTo ' +  
 
                    'from LU_PostalCode ' +  
                    'where ''' + @DDate + ''' between Validfrom and ValidTo ' +  
                    'and CIHIValue in ( ' +  
                        '''' + replace(left(@TempValue, 6), '''', '''''') + ''', ' +  
                        '''' + replace(left(@TempValue, 5), '''', '''''') + ''', ' +   
                        '''' + replace(left(@TempValue, 4), '''', '''''') + ''', ' +  
                        '''' + replace(left(@TempValue, 3), '''', '''''') + ''', ' +  
                        '''' + replace(left(@TempValue, 2), '''', '''''') + ''', ' +  
                        '''' + replace(left(@TempValue, 1), '''', '''''') + ''') ' +  
                    'order by len(CIHIValue) desc' 
            --PRINT @SQL
        end 
        else begin 
            set @sql = 'select @TempV = ' + @SystemName + ' from #ABMainTemp' 
            exec sp_executesql @sql, N'@TempV varchar(50) output', @TempValue Output 
            set @sql = '' 
             
            if isnull(@TempValue, '') <> ''  and @SystemName <> 'CancerCareVisit'
                set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', 0, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from ' + @LookupTable + ' where (Code = ' + @TempValue + ')' 
            else if @SystemName = 'CancerCareVisit' begin
                set @sql = 'select @CC_AID = AbstractID from AB_Main where UniversalID = ' + cast(@TempValue as varchar(50))
                exec sp_executesql @sql, N'@CC_AID varchar(20) output', @CC_AID Output 
                set @sql = '' 
                
                set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', 0, Code = ' + cast(@TempValue as varchar(20)) + ', 
                    DisplayCode= convert(varchar(20), r.RegisterDate, 111), 
                    UserDescription = ''Inst: '' + h.DisplayCode + '', Seq:'' + cast(isnull(DiseaseSequenceNum, 1) as varchar(10)) + '', Problem: '' + d.DisplayCode + ''-'' + d.UserDescription,
                    CIHIValue = '''', Validfrom = ''1950/01/01'', ValidTo = ''2099/12/31''
                    from dbo.CC_Demographic cc 
                        inner join dbo.CC_DiseaseRegister r on cc.AbstractID = r.AbstractID
                        inner join dbo.H_InstitutionProfile h on cc.InstitutionNumber = h.code
                        left join ICD_DiagFile10 d on r.DiagnosisCode = d.code
                    where cc.AbstractID = ' + @CC_AID 
                --print @sql
            end    
        end 
    end 
    
    
    if isnull(@sql, '') != '' begin  
        insert #LoadResults (SortOrder, FieldID, Occurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo)  
        exec @exec_return = sp_executesql @sql 
        --print @sql 
        if @exec_return != 0  
            RAISERROR (@sql, 11, 1) 
    end 
 
    fetch next from cur into @FieldID, @SystemName, @LookupTable, @MultipleIndex, @DataType, @SortOrder 
end 
 
close cur 
deallocate cur 
 
update #LoadResults set code = 0, Displaycode = NULL, UserDescription = NULL, CIHIValue = NULL where (ValidTo < '' + @DDate + '' or Validfrom > '' + @DDate + '') 
update #LoadResults set userdescription = convert(varchar(20), cast(userdescription as datetime), 120) where isdate(userdescription) = 1 and len(userdescription) > 10 

declare @HID as int --NP-00025
select @HID = HospitalID from U_Users where Code = @LogID
insert into AB_updateHistory (AbstractID, HospitalID, Coder, Updated, UpdateType) values (@AbstractID, @HID, @LogID, getdate(), 'Viewed') 
set nocount off 
print '' 
 
select FKey = FieldID, Occ = Occurrence, Code, DisplayCode, UserDescription, CIHIValue  
from #LoadResults  
order by SortOrder, Occurrence 
--   print datediff(ms, @SDate, getdate()) 

return 0
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE                              PROCEDURE [L_BatchGrouper]
	@InstNumber as int,
	@DateFrom as VarChar(10),
	@DateTo as VarChar(10),
	@Complete as int,
	@Grouper as int,
	@ICDType as VarChar(1)
AS
	Declare @DiagNumber as int
	Set @DiagNumber = 1
	Declare @IntervNumber as int
	Set @IntervNumber = 1

	Set nocount on
	CREATE TABLE #BGrouper ([AbstractID] [int] NULL) ON [PRIMARY]
	If @Complete = 1 and @Grouper in (1, 2)
	Begin
		Insert into #BGrouper 
		Select abstractid from ab_abstract
		WHERE (dbo.AB_Abstract.InstitutionNumber = @InstNumber) AND (dbo.AB_Abstract.DischargeDate BETWEEN @DateFrom AND @DateTo) and ICDType = @ICDType 
	End
	Else If @Complete <> 1 and @Grouper in (1, 2)
	Begin
		Insert into #BGrouper 
		Select abstractid from ab_abstract
		WHERE (dbo.AB_Abstract.InstitutionNumber = @InstNumber) AND (dbo.AB_Abstract.DischargeDate BETWEEN @DateFrom AND @DateTo) AND (dbo.AB_Abstract.IsValidated > 2) and ICDType = @ICDType
	End
	Else If @Complete = 1 and @Grouper = 5
	Begin
		Insert into #BGrouper 
		Select abstractid from ab_abstract
		WHERE (dbo.AB_Abstract.InstitutionNumber = @InstNumber) AND (dbo.AB_Abstract.AdmitDate BETWEEN @DateFrom AND @DateTo) and ICDType = @ICDType 
	End
	Else If @Complete <> 1 and @Grouper = 5
	Begin
		Insert into #BGrouper 
		Select abstractid from ab_abstract
		WHERE (dbo.AB_Abstract.InstitutionNumber = @InstNumber) AND (dbo.AB_Abstract.AdmitDate BETWEEN @DateFrom AND @DateTo) AND (dbo.AB_Abstract.IsValidated > 2) and ICDType = @ICDType
	End


	If @Grouper = 1 and @ICDType = 'T'
	Begin
		Set @DiagNumber = 25
		Set @IntervNumber = 20
	End
	Else If @Grouper = 1 and @ICDType <> 'T'
	Begin
		Set @DiagNumber = 15
		Set @IntervNumber = 10
	End
	Else If @Grouper = 5 and @ICDType = 'T'
		Set @IntervNumber = 10

	Set Nocount off
If @Grouper in (1, 2, 5)
Begin
	If @ICDType = 'T'
	Begin
		--ICD10 CMG
		If @Grouper in (1,2)
			SELECT dbo.AB_Abstract.AbstractID AS AIDMain, dbo.AB_Abstract.ICDType, dbo.AB_Abstract.DischargeDate, dbo.AB_Abstract.AdmitDate, 
                      dbo.AB_Abstract.EncounterNumber, dbo.LU_Gender_I.CIHIValue AS Gender, dbo.AB_Abstract.Weight, dbo.AB_Abstract.AgeNumber, 
                      dbo.AB_Abstract.AgeCode, dbo.AB_Abstract.InstitutionTo, dbo.AB_Abstract.InstitutionFrom, dbo.AB_Abstract.LOSDays, dbo.AB_Abstract.AcuteLOS, 
                      dbo.LU_DispositionCode_I.CIHIValue AS ExitCode, dbo.LU_DispositionCode_A.CIHIValue AS DispositionCode, 
                      dbo.LU_Program.CIHIValue AS ProgramCode, AgeGroup
			FROM dbo.AB_Abstract LEFT OUTER JOIN
                      dbo.LU_Gender_I ON dbo.AB_Abstract.Gender = dbo.LU_Gender_I.Code LEFT OUTER JOIN
                      dbo.LU_Program ON dbo.AB_Abstract.Program = dbo.LU_Program.Code LEFT OUTER JOIN
                      dbo.LU_DispositionCode_A ON dbo.AB_Abstract.DispositionCode = dbo.LU_DispositionCode_A.Code LEFT OUTER JOIN
                      dbo.LU_DispositionCode_I ON dbo.AB_Abstract.DispositionCode = dbo.LU_DispositionCode_I.Code
			WHERE dbo.AB_Abstract.AbstractID in (select abstractid from #BGrouper)
			ORDER BY dbo.AB_Abstract.AbstractID
		Else
			SELECT dbo.AB_Abstract.AbstractID AS AIDMain, dbo.AB_Abstract.ICDType, dbo.AB_Abstract.DischargeDate, dbo.AB_Abstract.AdmitDate, 
                      dbo.AB_Abstract.EncounterNumber, dbo.LU_Gender_I.CIHIValue AS Gender, dbo.AB_Abstract.Weight, dbo.AB_Abstract.AgeNumber, 
                      dbo.LU_AgeCode.CIHIValue AS AgeCode, dbo.AB_Abstract.InstitutionTo, dbo.AB_Abstract.InstitutionFrom, dbo.AB_Abstract.LOSDays, 
                      dbo.AB_Abstract.AcuteLOS, dbo.LU_DispositionCode_I.CIHIValue AS ExitCode, dbo.LU_DispositionCode_A.CIHIValue AS DispositionCode, 
                      dbo.LU_Program.CIHIValue AS ProgramCode, AgeGroup
			FROM  dbo.AB_Abstract LEFT OUTER JOIN
                      dbo.LU_AgeCode ON dbo.AB_Abstract.AgeCode = dbo.LU_AgeCode.Code LEFT OUTER JOIN
                      dbo.LU_Gender_I ON dbo.AB_Abstract.Gender = dbo.LU_Gender_I.Code LEFT OUTER JOIN
                      dbo.LU_Program ON dbo.AB_Abstract.Program = dbo.LU_Program.Code LEFT OUTER JOIN
                      dbo.LU_DispositionCode_A ON dbo.AB_Abstract.DispositionCode = dbo.LU_DispositionCode_A.Code LEFT OUTER JOIN
                      dbo.LU_DispositionCode_I ON dbo.AB_Abstract.DispositionCode = dbo.LU_DispositionCode_I.Code
			WHERE dbo.AB_Abstract.AbstractID in (select abstractid from #BGrouper)
			ORDER BY dbo.AB_Abstract.AbstractID

			
			SELECT dbo.AB_Diagnosis.AbstractID as AIDDiag, dbo.ICD_DiagFile10.CIHIValue AS Diag, dbo.LU_DiagnosisType.CIHIValue AS DiagType
			FROM dbo.AB_Diagnosis RIGHT OUTER JOIN dbo.AB_Abstract ON dbo.AB_Diagnosis.AbstractID = dbo.AB_Abstract.AbstractID LEFT OUTER JOIN
			dbo.LU_DiagnosisType ON dbo.AB_Diagnosis.DiagnosisType = dbo.LU_DiagnosisType.Code LEFT OUTER JOIN
			dbo.ICD_DiagFile10 ON dbo.AB_Diagnosis.DiagnosisCode = dbo.ICD_DiagFile10.Code
			WHERE (dbo.AB_Diagnosis.AbstractID IN (Select abstractid from #BGrouper) and DiagnosisOccurrence <= @DiagNumber)
			ORDER BY dbo.AB_Diagnosis.AbstractID, dbo.AB_Diagnosis.DiagnosisOccurrence

			select AbstractID, [AIDInterv], [AIDProc], [ICDType], [IntervProc], [IntervCode], [FullIntervention], [IntervAttribute],[OOHInd],[AttStat],[AttLoc],[AttExt]
			from (SELECT dbo.AB_Intervention.AbstractID AS AbstractID, dbo.AB_Intervention.AbstractID AS AIDInterv, dbo.AB_Intervention.AbstractID AS AIDProc, 
                      dbo.AB_Intervention.IntervICDType AS ICDType, dbo.ICD_ProcFile10.CIHIValue AS IntervProc, dbo.ICD_ProcFile10.CIHIValue AS IntervCode, 
                      RTRIM(dbo.ICD_ProcFile10.CIHIValue + SPACE(10 - LEN(dbo.ICD_ProcFile10.CIHIValue)) + ISNULL(dbo.LU_IntervAttLocation.CIHIValue, '')) 
                      AS FullIntervention, dbo.LU_IntervAttLocation.CIHIValue AS IntervAttribute, dbo.LU_YesBlankAlpha.CIHIValue AS OOHInd, 
                      dbo.LU_IntervAttStatus.CIHIValue AS AttStat, dbo.LU_IntervAttLocation.CIHIValue AS AttLoc, dbo.LU_IntervAttExtent.CIHIValue AS AttExt, IntervOccurrence
			FROM  dbo.LU_IntervAttLocation RIGHT OUTER JOIN
                      dbo.AB_Intervention LEFT OUTER JOIN
                      dbo.LU_YesBlankAlpha ON dbo.AB_Intervention.IntervOOHIndicator = dbo.LU_YesBlankAlpha.Code LEFT OUTER JOIN
                      dbo.LU_IntervAttStatus ON dbo.AB_Intervention.IntervAttribStatus = dbo.LU_IntervAttStatus.Code LEFT OUTER JOIN
                      dbo.LU_IntervAttExtent ON dbo.AB_Intervention.IntervAttribExtent = dbo.LU_IntervAttExtent.Code ON 
                      dbo.LU_IntervAttLocation.Code = dbo.AB_Intervention.IntervAttribLocation LEFT OUTER JOIN
                      dbo.ICD_ProcFile10 ON dbo.AB_Intervention.IntervCode = dbo.ICD_ProcFile10.Code
			WHERE (dbo.AB_Intervention.AbstractID IN (select abstractid from #BGrouper)) and dbo.AB_Intervention.IntervCode is not null and IntervOccurrence <= @intervnumber and isnull(dbo.LU_IntervAttStatus.CIHIValue, '') <> 'A') as a
			ORDER BY a.AbstractID, a.IntervOccurrence

			SELECT dbo.AB_Intervention.AbstractID as AIDInterv, ISNULL(dbo.AB_Intervention.IntervCode, 0) as IntervCode,
	                dbo.LU_AnaestTechnique.CIHIValue as AnaestTechnique FROM dbo.AB_Intervention 
	                RIGHT OUTER JOIN dbo.AB_Abstract ON dbo.AB_Intervention.AbstractID = dbo.AB_Abstract.AbstractID 
	                LEFT OUTER JOIN dbo.LU_AnaestTechnique ON dbo.AB_Intervention.IntervAnaestTechnique = dbo.LU_AnaestTechnique.Code
			WHERE (dbo.AB_Intervention.AbstractID IN (select abstractid from #BGrouper) and IntervOccurrence = 1)
			ORDER BY dbo.AB_Intervention.AbstractID
	End
	Else If @ICDType = 'C'
	Begin
		--ICD9cm CMG
			SELECT dbo.AB_Abstract.AbstractID AS AIDMain, dbo.AB_Abstract.ICDType, dbo.AB_Abstract.DischargeDate, dbo.AB_Abstract.AdmitDate, 
                      dbo.AB_Abstract.EncounterNumber, dbo.LU_Gender_I.CIHIValue AS Gender, dbo.AB_Abstract.Weight, dbo.AB_Abstract.AgeNumber, 
                      dbo.AB_Abstract.AgeCode, dbo.AB_Abstract.InstitutionTo, dbo.AB_Abstract.InstitutionFrom, dbo.AB_Abstract.LOSDays, dbo.AB_Abstract.AcuteLOS, 
                      dbo.LU_DispositionCode_I.CIHIValue AS ExitCode, dbo.LU_DispositionCode_A.CIHIValue AS DispositionCode, 
                      dbo.LU_Program.CIHIValue AS ProgramCode, AgeGroup
			FROM dbo.AB_Abstract LEFT OUTER JOIN
                      dbo.LU_Gender_I ON dbo.AB_Abstract.Gender = dbo.LU_Gender_I.Code LEFT OUTER JOIN
                      dbo.LU_Program ON dbo.AB_Abstract.Program = dbo.LU_Program.Code LEFT OUTER JOIN
                      dbo.LU_DispositionCode_A ON dbo.AB_Abstract.DispositionCode = dbo.LU_DispositionCode_A.Code LEFT OUTER JOIN
                      dbo.LU_DispositionCode_I ON dbo.AB_Abstract.DispositionCode = dbo.LU_DispositionCode_I.Code
			WHERE dbo.AB_Abstract.AbstractID in (select abstractid from #BGrouper)
			ORDER BY dbo.AB_Abstract.AbstractID
			
			SELECT dbo.AB_Diagnosis.AbstractID as AIDDiag, dbo.ICD_DiagFile9cm.CIHIValue AS Diag, dbo.LU_DiagnosisType.CIHIValue AS DiagType
			FROM dbo.AB_Diagnosis RIGHT OUTER JOIN dbo.AB_Abstract ON dbo.AB_Diagnosis.AbstractID = dbo.AB_Abstract.AbstractID LEFT OUTER JOIN
			dbo.LU_DiagnosisType ON dbo.AB_Diagnosis.DiagnosisType = dbo.LU_DiagnosisType.Code LEFT OUTER JOIN
			dbo.ICD_DiagFile9cm ON dbo.AB_Diagnosis.DiagnosisCode = dbo.ICD_DiagFile9cm.Code
			WHERE (dbo.AB_Diagnosis.AbstractID IN (Select abstractid from #BGrouper) and DiagnosisOccurrence <= @DiagNumber)
			ORDER BY dbo.AB_Diagnosis.AbstractID, dbo.AB_Diagnosis.DiagnosisOccurrence

			select AbstractID, [AIDInterv], [AIDProc], [ICDType], [IntervProc], [IntervCode], [FullIntervention], [IntervAttribute],[OOHInd],[AttStat],[AttLoc],[AttExt]
			from (SELECT dbo.AB_Intervention.AbstractID AS AbstractID, dbo.AB_Intervention.AbstractID AS AIDInterv, dbo.AB_Intervention.AbstractID AS AIDProc, 
                      dbo.AB_Intervention.IntervICDType AS ICDType, dbo.ICD_ProcFile9cm.CIHIValue AS IntervProc, dbo.ICD_ProcFile9cm.CIHIValue AS IntervCode, 
                      RTRIM(dbo.ICD_ProcFile9cm.CIHIValue + SPACE(10 - LEN(dbo.ICD_ProcFile9cm.CIHIValue)) + ISNULL(dbo.LU_IntervAttLocation.CIHIValue, '')) 
                      AS FullIntervention, dbo.LU_IntervAttLocation.CIHIValue AS IntervAttribute, dbo.LU_YesBlankAlpha.CIHIValue AS OOHInd, 
                      dbo.LU_IntervAttStatus.CIHIValue AS AttStat, dbo.LU_IntervAttLocation.CIHIValue AS AttLoc, dbo.LU_IntervAttExtent.CIHIValue AS AttExt, IntervOccurrence
			FROM  dbo.LU_IntervAttLocation RIGHT OUTER JOIN
                      dbo.AB_Intervention LEFT OUTER JOIN
                      dbo.LU_YesBlankAlpha ON dbo.AB_Intervention.IntervOOHIndicator = dbo.LU_YesBlankAlpha.Code LEFT OUTER JOIN
                      dbo.LU_IntervAttStatus ON dbo.AB_Intervention.IntervAttribStatus = dbo.LU_IntervAttStatus.Code LEFT OUTER JOIN
                      dbo.LU_IntervAttExtent ON dbo.AB_Intervention.IntervAttribExtent = dbo.LU_IntervAttExtent.Code ON 
                      dbo.LU_IntervAttLocation.Code = dbo.AB_Intervention.IntervAttribLocation LEFT OUTER JOIN
                      dbo.ICD_ProcFile9cm ON dbo.AB_Intervention.IntervCode = dbo.ICD_ProcFile9cm.Code
			WHERE (dbo.AB_Intervention.AbstractID IN (select abstractid from #BGrouper)) and dbo.AB_Intervention.IntervCode is not null and IntervOccurrence <= @intervnumber and isnull(dbo.LU_IntervAttStatus.CIHIValue, '') <> 'A') as a
			ORDER BY a.AbstractID, a.IntervOccurrence

			SELECT dbo.AB_Intervention.AbstractID as AIDInterv, ISNULL(dbo.AB_Intervention.IntervCode, 0) as IntervCode,
	                dbo.LU_AnaestTechnique.CIHIValue as AnaestTechnique FROM dbo.AB_Intervention 
	                RIGHT OUTER JOIN dbo.AB_Abstract ON dbo.AB_Intervention.AbstractID = dbo.AB_Abstract.AbstractID 
	                LEFT OUTER JOIN dbo.LU_AnaestTechnique ON dbo.AB_Intervention.IntervAnaestTechnique = dbo.LU_AnaestTechnique.Code
			WHERE (dbo.AB_Intervention.AbstractID IN (select abstractid from #BGrouper) and IntervOccurrence = 1)
			ORDER BY dbo.AB_Intervention.AbstractID
	End
	Else If @ICDType = '9'	Begin		--ICD9 CMG
			SELECT dbo.AB_Abstract.AbstractID AS AIDMain, dbo.AB_Abstract.ICDType, dbo.AB_Abstract.DischargeDate, dbo.AB_Abstract.AdmitDate, 
                      dbo.AB_Abstract.EncounterNumber, dbo.LU_Gender_I.CIHIValue AS Gender, dbo.AB_Abstract.Weight, dbo.AB_Abstract.AgeNumber, 
                      dbo.AB_Abstract.AgeCode, dbo.AB_Abstract.InstitutionTo, dbo.AB_Abstract.InstitutionFrom, dbo.AB_Abstract.LOSDays, dbo.AB_Abstract.AcuteLOS, 
                      dbo.LU_DispositionCode_I.CIHIValue AS ExitCode, dbo.LU_DispositionCode_A.CIHIValue AS DispositionCode, 
                      dbo.LU_Program.CIHIValue AS ProgramCode, AgeGroup
			FROM dbo.AB_Abstract LEFT OUTER JOIN
                      dbo.LU_Gender_I ON dbo.AB_Abstract.Gender = dbo.LU_Gender_I.Code LEFT OUTER JOIN
                      dbo.LU_Program ON dbo.AB_Abstract.Program = dbo.LU_Program.Code LEFT OUTER JOIN
                      dbo.LU_DispositionCode_A ON dbo.AB_Abstract.DispositionCode = dbo.LU_DispositionCode_A.Code LEFT OUTER JOIN
                      dbo.LU_DispositionCode_I ON dbo.AB_Abstract.DispositionCode = dbo.LU_DispositionCode_I.Code
			WHERE dbo.AB_Abstract.AbstractID in (select abstractid from #BGrouper)
			ORDER BY dbo.AB_Abstract.AbstractID
			
			SELECT dbo.AB_Diagnosis.AbstractID as AIDDiag, dbo.ICD_DiagFile9.CIHIValue AS Diag, dbo.LU_DiagnosisType.CIHIValue AS DiagType
			FROM dbo.AB_Diagnosis RIGHT OUTER JOIN dbo.AB_Abstract ON dbo.AB_Diagnosis.AbstractID = dbo.AB_Abstract.AbstractID LEFT OUTER JOIN
			dbo.LU_DiagnosisType ON dbo.AB_Diagnosis.DiagnosisType = dbo.LU_DiagnosisType.Code LEFT OUTER JOIN
			dbo.ICD_DiagFile9 ON dbo.AB_Diagnosis.DiagnosisCode = dbo.ICD_DiagFile9.Code
			WHERE (dbo.AB_Diagnosis.AbstractID IN (Select abstractid from #BGrouper) and DiagnosisOccurrence <= @DiagNumber)
			ORDER BY dbo.AB_Diagnosis.AbstractID, dbo.AB_Diagnosis.DiagnosisOccurrence

			select AbstractID, [AIDInterv], [AIDProc], [ICDType], [IntervProc], [IntervCode], [FullIntervention], [IntervAttribute],[OOHInd],[AttStat],[AttLoc],[AttExt]
			from (SELECT dbo.AB_Intervention.AbstractID AS AbstractID, dbo.AB_Intervention.AbstractID AS AIDInterv, dbo.AB_Intervention.AbstractID AS AIDProc, 
                      dbo.AB_Intervention.IntervICDType AS ICDType, dbo.ICD_ProcFile9.CIHIValue AS IntervProc, dbo.ICD_ProcFile9.CIHIValue AS IntervCode, 
                      RTRIM(dbo.ICD_ProcFile9.CIHIValue + SPACE(10 - LEN(dbo.ICD_ProcFile9.CIHIValue)) + ISNULL(dbo.LU_IntervAttLocation.CIHIValue, '')) 
                      AS FullIntervention, dbo.LU_IntervAttLocation.CIHIValue AS IntervAttribute, dbo.LU_YesBlankAlpha.CIHIValue AS OOHInd, 
                      dbo.LU_IntervAttStatus.CIHIValue AS AttStat, dbo.LU_IntervAttLocation.CIHIValue AS AttLoc, dbo.LU_IntervAttExtent.CIHIValue AS AttExt, IntervOccurrence
			FROM  dbo.LU_IntervAttLocation RIGHT OUTER JOIN
                      dbo.AB_Intervention LEFT OUTER JOIN
                      dbo.LU_YesBlankAlpha ON dbo.AB_Intervention.IntervOOHIndicator = dbo.LU_YesBlankAlpha.Code LEFT OUTER JOIN
                      dbo.LU_IntervAttStatus ON dbo.AB_Intervention.IntervAttribStatus = dbo.LU_IntervAttStatus.Code LEFT OUTER JOIN
                      dbo.LU_IntervAttExtent ON dbo.AB_Intervention.IntervAttribExtent = dbo.LU_IntervAttExtent.Code ON 
                      dbo.LU_IntervAttLocation.Code = dbo.AB_Intervention.IntervAttribLocation LEFT OUTER JOIN
                      dbo.ICD_ProcFile9 ON dbo.AB_Intervention.IntervCode = dbo.ICD_ProcFile9.Code
			WHERE (dbo.AB_Intervention.AbstractID IN (select abstractid from #BGrouper)) and dbo.AB_Intervention.IntervCode is not null and IntervOccurrence <= @intervnumber and isnull(dbo.LU_IntervAttStatus.CIHIValue, '') <> 'A') as a
			ORDER BY a.AbstractID, a.IntervOccurrence

			SELECT dbo.AB_Intervention.AbstractID as AIDInterv, ISNULL(dbo.AB_Intervention.IntervCode, 0) as IntervCode,
	                dbo.LU_AnaestTechnique.CIHIValue as AnaestTechnique FROM dbo.AB_Intervention 
	                RIGHT OUTER JOIN dbo.AB_Abstract ON dbo.AB_Intervention.AbstractID = dbo.AB_Abstract.AbstractID 
	                LEFT OUTER JOIN dbo.LU_AnaestTechnique ON dbo.AB_Intervention.IntervAnaestTechnique = dbo.LU_AnaestTechnique.Code
			WHERE (dbo.AB_Intervention.AbstractID IN (select abstractid from #BGrouper) and IntervOccurrence = 1)
			ORDER BY dbo.AB_Intervention.AbstractID
	End
End


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [L_BatchGrouper2007P]
	@InstNumber as int,
	@DateFrom as VarChar(10),
	@DateTo as VarChar(10),
	@Complete as int,
	@Grouper as int
AS
	Declare @DiagNumber as int
	Set @DiagNumber = 1
	Declare @IntervNumber as int
	Set @IntervNumber = 1

	Set nocount on
	CREATE TABLE #BGrouper ([AbstractID] [int] NULL) ON [PRIMARY]
	If @Complete = 1 and @Grouper in (1, 2)
	Begin
		Insert into #BGrouper 
		Select abstractid from ab_abstract
		WHERE (dbo.AB_Abstract.InstitutionNumber = @InstNumber) AND (dbo.AB_Abstract.DischargeDate BETWEEN @DateFrom AND @DateTo) and ICDType = 'T' 
	End
	Else If @Complete <> 1 and @Grouper in (1, 2)
	Begin
		Insert into #BGrouper 
		Select abstractid from ab_abstract
		WHERE (dbo.AB_Abstract.InstitutionNumber = @InstNumber) AND (dbo.AB_Abstract.DischargeDate BETWEEN @DateFrom AND @DateTo) AND (dbo.AB_Abstract.IsValidated > 2) and ICDType = 'T'
	End
	Else If @Complete = 1 and @Grouper = 5
	Begin
		Insert into #BGrouper 
		Select abstractid from ab_abstract
		WHERE (dbo.AB_Abstract.InstitutionNumber = @InstNumber) AND (dbo.AB_Abstract.AdmitDate BETWEEN @DateFrom AND @DateTo) and ICDType = 'T' 
	End
	Else If @Complete <> 1 and @Grouper = 5
	Begin
		Insert into #BGrouper 
		Select abstractid from ab_abstract
		WHERE (dbo.AB_Abstract.InstitutionNumber = @InstNumber) AND (dbo.AB_Abstract.AdmitDate BETWEEN @DateFrom AND @DateTo) AND (dbo.AB_Abstract.IsValidated > 2) and ICDType = 'T'
	End

	If @Grouper in (1,2)
	Begin
		Set @DiagNumber = 25
		Set @IntervNumber = 20
	End
	Else If @Grouper = 5
		Set @IntervNumber = 10

	Set Nocount off

	SELECT dbo.AB_Abstract.AbstractID AS AIDMain, dbo.LU_Gender_I.CIHIValue AS Gender, 
			  [Weight] = (case when caretype = 1 and dischargedate >= '2018/04/01' 
							   then (case when isnumeric(AB_Abstract.WeightKilo) = 1 then cast(cast(AB_Abstract.WeightKilo as decimal(7, 3)) * 1000 as int) else 0 end)
							   else dbo.AB_Abstract.Weight end), 
              dbo.AB_Abstract.AgeNumber, 
              --PR - 06128 remove code from PR - 05880 remove birthdate estimated = Y
              (case when BirthDate = '9999/09/01' then 'U' else dbo.LU_AgeCode.CIHIValue end) AS AgeCode, 
              --(case when BirthDate = '9999/09/01' then 'U' when isnull(LU_BirthDateEstimated.CIHIValue, '') = 'Y' then 'U' else dbo.LU_AgeCode.CIHIValue end) AS AgeCode, 
              dbo.AB_Abstract.InstitutionTo, dbo.AB_Abstract.InstitutionFrom, 
              dbo.AB_Abstract.LOSDays, dbo.AB_Abstract.AcuteLOS, dbo.LU_DispositionCode_I.CIHIValue AS ExitCode, 
              dbo.LU_DispositionCode_A.CIHIValue AS DispositionCode, dbo.LU_Program.CIHIValue AS ProgramCode, dbo.AB_ReproductiveCare.GestationalAge, 
              dbo.LU_EntryCode.CIHIValue AS EntryCode, ICDType, EncounterNumber, dbo.AB_Abstract.AdmitDate,
              --PR - 04791
              LU_ContactMode.CIHIValue as ContactMode, LU_AmCareTypeCode.CIHIValue as AmCareTypeCode,
              --ED - 02229
              LevelCode = (case when isnull(H.LevelCode, 0) >= 3 then 3 when isnull(H.LevelCode, 0) = 2 then 2 else 0 end), 
              LU_EDVisitIndicator.CIHIValue as EDVisitIndicator,
			  InstitutionFromType = (case when isnull(LU_InstFrom.[InstitutionType], '') = '' then (case when LU_InstFrom.IsAcute = 1 then '1' when LU_InstFrom.[HospitalType] = 'HC' then '8' else '' end) else LU_InstFrom.[InstitutionType] end),
			  InstitutionToType = (case when isnull(LU_InstTo.[InstitutionType], '') = '' then (case when LU_InstTo.IsAcute = 1 then '1' when LU_InstTo.[HospitalType] = 'HC' then '8' else '' end) else LU_InstTo.[InstitutionType] end) ,
			  (case when isnumeric(CostPerRIW) = 1 then CostPerRIW else '0' end) as CostPerRIW,
              MISCode = isnull(LU_MISCode.CIHIValue, ''),
              AdmitCategory = isnull(LU_AdmitCategory.CIHIValue, ''),
              ResponsiblePayment = isnull(LU_RespPayment.CIHIValue, ''),
              HCNProvince = isnull(LU_HCNProvince.CIHIValue, ''),
              Access = isnull((select top 1 FieldAccess from U_Fields where Fieldid = 80000), 0)
	FROM dbo.AB_Abstract inner join 
	          dbo.h_institutionprofile h on dbo.AB_Abstract.InstitutionNumber = h.code LEFT OUTER JOIN
              dbo.LU_EntryCode ON dbo.AB_Abstract.EntryCode = dbo.LU_EntryCode.Code LEFT OUTER JOIN
              dbo.AB_ReproductiveCare ON dbo.AB_Abstract.AbstractID = dbo.AB_ReproductiveCare.AbstractID LEFT OUTER JOIN
              dbo.LU_AgeCode ON dbo.AB_Abstract.AgeCode = dbo.LU_AgeCode.Code LEFT OUTER JOIN
              dbo.LU_Gender_I ON dbo.AB_Abstract.Gender = dbo.LU_Gender_I.Code LEFT OUTER JOIN
              dbo.LU_Program ON dbo.AB_Abstract.Program = dbo.LU_Program.Code LEFT OUTER JOIN
              dbo.LU_DispositionCode_A ON dbo.AB_Abstract.DispositionCode = dbo.LU_DispositionCode_A.Code LEFT OUTER JOIN
              dbo.LU_DispositionCode_I ON dbo.AB_Abstract.DispositionCode = dbo.LU_DispositionCode_I.Code left join
              --PR - 04791
              dbo.LU_ContactMode on dbo.Ab_Abstract.ContactMode = dbo.LU_ContactMode.code left join 
              dbo.AB_NACRS on dbo.AB_NACRS.AbstractID = dbo.AB_Abstract.AbstractID left join
              dbo.LU_CodeFile  lu_AmCareTypeCode on lu_AmCareTypeCode.code = dbo.AB_NACRS.AmCareTypeCode left join
              --ED - 02229
              dbo.LU_YesNoSystem LU_EDVisitIndicator on LU_EDVisitIndicator.code = dbo.AB_NACRS.EDVisitIndicator left join
              --PR - 05880
              dbo.LU_YesBlankAlpha LU_BirthDateEstimated on LU_BirthDateEstimated.Code = AB_Abstract.BirthDateEstimated left join
			  dbo.LU_Institution_10 LU_InstFrom on AB_Abstract.InstitutionFrom = LU_InstFrom.Code left join
			  dbo.LU_Institution_10 LU_InstTo on AB_Abstract.InstitutionTo = LU_InstTo.Code left join
			  dbo.LU_MISCode on AB_Abstract.MISCode = LU_MISCode.Code left join
			  dbo.LU_AdmitCategory on AB_Abstract.AdmitCategory = LU_AdmitCategory.Code left join
			  dbo.LU_RespPayment on AB_Abstract.ResponsiblePayment = LU_RespPayment.Code left join
			  dbo.LU_HCNProvince on AB_Abstract.HCNProvince = LU_HCNProvince.Code 
	WHERE dbo.AB_Abstract.AbstractID in (select abstractid from #BGrouper)
	ORDER BY dbo.AB_Abstract.AbstractID
	
	SELECT dbo.AB_Diagnosis.AbstractID as AIDDiag, dbo.ICD_DiagFile10.CIHIValue AS Diag, dbo.LU_DiagnosisType.CIHIValue AS DiagType, DiagnosisOccurrence as DiagOcc
	FROM dbo.AB_Diagnosis RIGHT OUTER JOIN dbo.AB_Abstract ON dbo.AB_Diagnosis.AbstractID = dbo.AB_Abstract.AbstractID LEFT OUTER JOIN
	dbo.LU_DiagnosisType ON dbo.AB_Diagnosis.DiagnosisType = dbo.LU_DiagnosisType.Code LEFT OUTER JOIN
	dbo.ICD_DiagFile10 ON dbo.AB_Diagnosis.DiagnosisCode = dbo.ICD_DiagFile10.Code
	WHERE (dbo.AB_Diagnosis.AbstractID IN (Select abstractid from #BGrouper) and DiagnosisOccurrence <= @DiagNumber)
	ORDER BY dbo.AB_Diagnosis.AbstractID, dbo.AB_Diagnosis.DiagnosisOccurrence

	select AbstractID as AIDProc, AbstractID as AIDInterv, [IntervCode], IntervCode as [IntervProc], [OOHInd],[AttStat],[AttLoc],[AttExt], IntervDate, AnaestTech, IntervOccurrence
	from (SELECT dbo.AB_Intervention.AbstractID, dbo.ICD_ProcFile10.CIHIValue AS IntervCode,dbo.LU_YesBlankAlpha.CIHIValue AS OOHInd, 
              dbo.LU_IntervAttStatus.CIHIValue AS AttStat, dbo.LU_IntervAttLocation.CIHIValue AS AttLoc, dbo.LU_IntervAttExtent.CIHIValue AS AttExt, 
              dbo.AB_Intervention.IntervOccurrence, dbo.AB_Intervention.IntervDate, dbo.LU_AnaestTechnique.CIHIValue AS AnaestTech
			FROM dbo.LU_IntervAttExtent RIGHT OUTER JOIN
              dbo.AB_Intervention LEFT OUTER JOIN
              dbo.LU_AnaestTechnique ON dbo.AB_Intervention.IntervAnaestTechnique = dbo.LU_AnaestTechnique.Code LEFT OUTER JOIN
              dbo.LU_YesBlankAlpha ON dbo.AB_Intervention.IntervOOHIndicator = dbo.LU_YesBlankAlpha.Code LEFT OUTER JOIN
              dbo.LU_IntervAttStatus ON dbo.AB_Intervention.IntervAttribStatus = dbo.LU_IntervAttStatus.Code ON 
              dbo.LU_IntervAttExtent.Code = dbo.AB_Intervention.IntervAttribExtent LEFT OUTER JOIN
              dbo.LU_IntervAttLocation ON dbo.AB_Intervention.IntervAttribLocation = dbo.LU_IntervAttLocation.Code LEFT OUTER JOIN
              dbo.ICD_ProcFile10 ON dbo.AB_Intervention.IntervCode = dbo.ICD_ProcFile10.Code
	WHERE (dbo.AB_Intervention.AbstractID IN (select abstractid from #BGrouper)) and IntervOccurrence <= @intervnumber
	    and (dbo.AB_Intervention.IntervCode > 0 or LU_AnaestTechnique.CIHIValue is not null)	--PR - 05535 allow blank intervention with AnaestTechnique  --PR - 04801
	) as a
	ORDER BY a.AbstractID, a.IntervOccurrence

	SELECT dbo.AB_Intervention.AbstractID as AIDInterv, ISNULL(dbo.AB_Intervention.IntervCode, 0) as IntervCode,
            dbo.LU_AnaestTechnique.CIHIValue as AnaestTechnique FROM dbo.AB_Intervention 
            RIGHT OUTER JOIN dbo.AB_Abstract ON dbo.AB_Intervention.AbstractID = dbo.AB_Abstract.AbstractID 
            LEFT OUTER JOIN dbo.LU_AnaestTechnique ON dbo.AB_Intervention.IntervAnaestTechnique = dbo.LU_AnaestTechnique.Code
	WHERE (dbo.AB_Intervention.AbstractID IN (select abstractid from #BGrouper) and IntervOccurrence = 1)
	ORDER BY dbo.AB_Intervention.AbstractID

    --EN - 00554
	SELECT dbo.AB_SpecialCareUnit.AbstractID as AIDSCU, SCUOccurrence, dbo.LU_SCUNumber.CIHIValue as SCUNumber
    FROM dbo.AB_SpecialCareUnit 
            RIGHT OUTER JOIN dbo.AB_Abstract ON dbo.AB_SpecialCareUnit.AbstractID = dbo.AB_Abstract.AbstractID 
            LEFT OUTER JOIN dbo.LU_SCUNumber ON dbo.AB_SpecialCareUnit.SCUNUmber = dbo.LU_SCUNumber.Code
	WHERE dbo.AB_SpecialCareUnit.AbstractID IN (select abstractid from #BGrouper) and SCUOccurrence <= 6
	ORDER BY dbo.AB_SpecialCareUnit.AbstractID, SCUOccurrence
	
    --2018 Level 2
	select [AB_DischargeDiagnosis].AbstractID as AIDDischarge, [Occurrence] as DischargeOccurrence, CIHIValue as DischargeDiagnosis
	from [dbo].[AB_DischargeDiagnosis]
		left join ICD_DiagFile10 on [DischargeDiagnosis] = Code
	WHERE dbo.[AB_DischargeDiagnosis].AbstractID IN (select abstractid from #BGrouper) and [Occurrence] <= 3
	ORDER BY AbstractID, Occurrence

	select AB_EDInterventionPicklist.AbstractID as AIDIntervPickList, [Occurrence] as PickListOccurrence, CIHIValue as InterventionPickList
	from [dbo].AB_EDInterventionPicklist
		left join [dbo].[LU_EDIntervnetionPickList] on [EDInterventionPickList] = Code
	WHERE dbo.AB_EDInterventionPicklist.AbstractID IN (select abstractid from #BGrouper) and [Occurrence] <= 3
	ORDER BY AbstractID, Occurrence

	select [AB_InvestigativeTechnology].AbstractID as AIDInvestigativeT, [Occurrence] as InvestigativeTOccurrence, CIHIValue as InvestigativeTechnology, isnull([NumberInvestigativeTechnologyPerformed], 0) as NumberInvestigativeTechnologyPerformed
	from [dbo].[AB_InvestigativeTechnology]
		left join [dbo].[LU_EDInvestigativeTechnology] on [InvestigativeTechnology] = Code
	WHERE dbo.[AB_InvestigativeTechnology].AbstractID IN (select abstractid from #BGrouper) and [Occurrence] <= 3
	ORDER BY AbstractID, Occurrence

	--2022 Level 2
	select [AB_EDInterventionValueSet].AbstractID as AIDInvestigativeT, [Occurrence] as EDInterventionValueSetOccurrence, CIHIValue as EDInterventionValueSet, isnull([NumberEDInvestigativeTechnologiesPerformed], 0) as NumberInvestigativeTechnologyPerformed
	from [dbo].[AB_EDInterventionValueSet]
		left join [dbo].[ICD_EDInterventionValueSet] on [EDInterventionValueSet] = Code
	WHERE dbo.[AB_EDInterventionValueSet].AbstractID IN (select abstractid from #BGrouper) and [Occurrence] <= 6
	ORDER BY AbstractID, Occurrence
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE   PROCEDURE [L_CACS]
	@Key as int
AS 

SELECT  AB_CACS.AbstractID, AB_CACS.OccurrenceNumber, AB_CACS.CACS_Year, MAC, CACSCell, ACW, CACSDescription, InterventionCode,
    AgeCategory, AnaestheticCategory, MITTotalCount, BatchGroupDate,
    ACW_HBAM, ACW_Base, CACSPartition, 
    MIT_Category_01, MIT_Category_Count_01, MIT_Category_02, MIT_Category_Count_02, 
    MIT_Category_03, MIT_Category_Count_03, MIT_Category_04, MIT_Category_Count_04, 
    MIT_Category_05, MIT_Category_Count_05, MIT_Category_06, MIT_Category_Count_06, 
    MIT_Category_07, MIT_Category_Count_07, MIT_Category_08, MIT_Category_Count_08, 
    MIT_Category_09, MIT_Category_Count_09, MIT_Category_10, MIT_Category_Count_10
FROM AB_CACS left join dbo.AB_CACS_Investigative
    on  AB_CACS.AbstractID = dbo.AB_CACS_Investigative.AbstractID and 
        AB_CACS.OccurrenceNumber = dbo.AB_CACS_Investigative.OccurrenceNumber and
        AB_CACS.CACS_Year = dbo.AB_CACS_Investigative.CACS_Year
WHERE AB_CACS.AbstractID = @Key AND AB_CACS.OccurrenceNumber = 1
    and isnull(IsFixed , 0) = 0
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [L_CACS_Years]
	@ICDType as VarChar(1)
AS 

	If @ICDType = 'C' 
		Set @ICDType = '9'

	Select CACSYears from CACS_Years where ICDType = @ICDType
	Order by CACSYears desc




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


-- This is called by the Load Method of the CPI Control
CREATE    PROCEDURE [L_CancerCare]
	@Key as int
AS 

select * from [dbo].[CC_Demographic] where AbstractID = @Key
select * from [dbo].[CC_DiseaseRegister] where AbstractID = @Key
select * from [dbo].[CC_CancerStageDiag] where AbstractID = @Key
select * from [dbo].[CC_CollaborateStageDiag] where AbstractID = @Key
select * from [dbo].[CC_ReferralDate] where AbstractID = @Key
select * from [dbo].[CC_HealthCareProf] where AbstractID = @Key order by Occurrence
select * from [dbo].[CC_RecordInfo] where AbstractID = @Key
select * from [dbo].[CC_UserDefined] where AbstractID = @Key
select * from [dbo].[CC_NDFP] where AbstractID = @Key
select * from [dbo].[CC_DischargeInfo] where AbstractID = @Key    -- New table 03/13/2008

select * from [CC_UDFieldsDate] where AbstractID = @Key
select * from [CC_UDFieldsTime] where AbstractID = @Key
select * from [CC_UDFieldsLookUp] where AbstractID = @Key
select * from [CC_UDFieldsInteger] where AbstractID = @Key
select * from [CC_UDFieldsText] where AbstractID = @Key
select * from [CC_UDFieldsSmallText] where AbstractID = @Key
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [L_CCRSData]
   @AppID as int,
   @UserID as int,
   @AbstractID as int,
   @Clone as int = 0
AS 

set nocount on 

declare @SDate datetime
declare @sql nvarchar(1000)
declare @FieldID varchar(6)
declare @SystemName varchar(50)
declare @LookUpTable varchar(100)    
declare @result varchar(50)
declare @TempCode varchar(50)
declare @TempDisplayCode varchar(50)
declare @TempUserDesc varchar(255)
declare @TempCIHI varchar(50)
declare @ICDType varchar(1)
declare @SortOrder varchar(6)
declare @DischargeDate datetime
declare @AdmitDate datetime
declare @CareType int
declare @DDAte varchar(10)
declare @MultipleIndex int
declare @DataType int
declare @CRS_SignatureCount int
declare @CRS_MedicationCount int
declare @CRS_ProjectCount int
declare @CRS_SpecialProjectCount int

if @Clone = 1
	set @AbstractID = 
        (
        select top 1 AbstractID 
        from CRS_Demographic 
        where LinkID = @AbstractID 
        and (AA8 in (14502, 14503, 14504, 14505, 14506, 14511)  
            or (AA8 = 14501 and AdmitDate >= '2012/04/01'))
        order by isnull(A3, AdmitDate) desc
        )
        
create table #TableABLoad 
(
    SortOrder int, 
    FieldID int, 
    Occurrence int,
    Code int,
    DisplayCode varchar(50),
    UserDescription varchar(255),
    CIHIValue varchar(50), 
    ValidFrom datetime, 
    ValidTo datetime
)

select
    dbo.CRS_Demographic.*, 
    
    dbo.CRS_Admission.AB3,       dbo.CRS_Admission.AB4,      dbo.CRS_Admission.AB5All,   dbo.CRS_Admission.AB5a, 
    dbo.CRS_Admission.AB5b,      dbo.CRS_Admission.AB5c,     dbo.CRS_Admission.AB5d,     dbo.CRS_Admission.AB5e, 
    dbo.CRS_Admission.AB7,       dbo.CRS_Admission.AB8,      dbo.CRS_Admission.AB9,      dbo.CRS_Admission.AB10All, 
    dbo.CRS_Admission.AB10a,     dbo.CRS_Admission.AB10b,    dbo.CRS_Admission.AB10c,    dbo.CRS_Admission.AB10d, 
    dbo.CRS_Admission.AB10e,     dbo.CRS_Admission.AB10f,    dbo.CRS_Admission.AC1a,     dbo.CRS_Admission.AC1b, 
    dbo.CRS_Admission.AC1c,      dbo.CRS_Admission.AC1d,     dbo.CRS_Admission.AC1e,     dbo.CRS_Admission.AC1f, 
    dbo.CRS_Admission.AC1g,      dbo.CRS_Admission.AC1I,     dbo.CRS_Admission.AC1j,     dbo.CRS_Admission.AC1k, 
    dbo.CRS_Admission.AC1m,      dbo.CRS_Admission.AC1n,     dbo.CRS_Admission.AC1o,     dbo.CRS_Admission.AC1p, 
    dbo.CRS_Admission.AC1q,      dbo.CRS_Admission.AC1s,     dbo.CRS_Admission.AC1t,     dbo.CRS_Admission.AC1u, 
    dbo.CRS_Admission.AC1v,      dbo.CRS_Admission.AC1w,     dbo.CRS_Admission.ResidenceCode,
    
    dbo.CRS_Ancillary.AncillaryField1,  dbo.CRS_Ancillary.AncillaryField2,  dbo.CRS_Ancillary.AncillaryField3, 
    dbo.CRS_Ancillary.AncillaryField4,  dbo.CRS_Ancillary.AncillaryField5,  dbo.CRS_Ancillary.AncillaryField6, 
    dbo.CRS_Ancillary.AncillaryField7,  dbo.CRS_Ancillary.AncillaryField8,  dbo.CRS_Ancillary.AncillaryField9, 
    dbo.CRS_Ancillary.AncillaryField10, dbo.CRS_Ancillary.AncillaryField11, dbo.CRS_Ancillary.AncillaryField12, 
    dbo.CRS_Ancillary.AncillaryField13, dbo.CRS_Ancillary.AncillaryField14, dbo.CRS_Ancillary.AncillaryField15, 
    dbo.CRS_Ancillary.AncillaryField16, dbo.CRS_Ancillary.AncillaryField17, 

    dbo.CRS_BasicOption.BasicOption1,  dbo.CRS_BasicOption.BasicOption2,  dbo.CRS_BasicOption.BasicOption3, 
    dbo.CRS_BasicOption.BasicOption4,  dbo.CRS_BasicOption.BasicOption5,  dbo.CRS_BasicOption.BasicOption6, 
    dbo.CRS_BasicOption.BasicOption7,  dbo.CRS_BasicOption.BasicOption8,  dbo.CRS_BasicOption.BasicOption9, 
    dbo.CRS_BasicOption.BasicOption10, dbo.CRS_BasicOption.BasicOption11, dbo.CRS_BasicOption.BasicOption12, 
    dbo.CRS_BasicOption.BasicOption13, dbo.CRS_BasicOption.BasicOption14, dbo.CRS_BasicOption.BasicOption15, 
    dbo.CRS_BasicOption.BasicOption16, dbo.CRS_BasicOption.BasicOption17, dbo.CRS_BasicOption.BasicOption18, 
    dbo.CRS_BasicOption.BasicOption19, 

    dbo.CRS_UDAbstracting.UDDate1,    dbo.CRS_UDAbstracting.UDDate2,    dbo.CRS_UDAbstracting.UDDate3, 
    dbo.CRS_UDAbstracting.UDDate4,    dbo.CRS_UDAbstracting.UDDate5,	dbo.CRS_UDAbstracting.UDTime1,    dbo.CRS_UDAbstracting.UDTime2, 
    dbo.CRS_UDAbstracting.UDTime3,    dbo.CRS_UDAbstracting.UDTime4,    dbo.CRS_UDAbstracting.UDTime5,    dbo.CRS_UDAbstracting.UDLookup1, 
    dbo.CRS_UDAbstracting.UDLookup2,  dbo.CRS_UDAbstracting.UDLookup3,  dbo.CRS_UDAbstracting.UDLookup4,  dbo.CRS_UDAbstracting.UDLookup5, 
    dbo.CRS_UDAbstracting.UDInteger1, dbo.CRS_UDAbstracting.UDInteger2, dbo.CRS_UDAbstracting.UDInteger3, 
    dbo.CRS_UDAbstracting.UDInteger4, dbo.CRS_UDAbstracting.UDInteger5, dbo.CRS_UDAbstracting.UDText1,    dbo.CRS_UDAbstracting.UDText2, 
    dbo.CRS_UDAbstracting.UDText3,    dbo.CRS_UDAbstracting.UDText4,  dbo.CRS_UDAbstracting.UDText5,  dbo.CRS_UDAbstracting.UDSmallText1,  
    dbo.CRS_UDAbstracting.UDSmallText2,  dbo.CRS_UDAbstracting.UDSmallText3,   dbo.CRS_UDAbstracting.UDSmallText4,  dbo.CRS_UDAbstracting.UDSmallText5,  

    dbo.CRS_AssessFull1.A7a,     dbo.CRS_AssessFull1.A7b,    dbo.CRS_AssessFull1.A7c,    dbo.CRS_AssessFull1.A7d,   
    dbo.CRS_AssessFull1.A7e,     dbo.CRS_AssessFull1.A7f,    dbo.CRS_AssessFull1.A7g,    dbo.CRS_AssessFull1.A7h,   
    dbo.CRS_AssessFull1.A7I,     dbo.CRS_AssessFull1.A7j,    dbo.CRS_AssessFull1.A7k,    dbo.CRS_AssessFull1.C1,  
    dbo.CRS_AssessFull1.C2All,   dbo.CRS_AssessFull1.C2a,    dbo.CRS_AssessFull1.C2b,    dbo.CRS_AssessFull1.C2c,   
    dbo.CRS_AssessFull1.C3All,   dbo.CRS_AssessFull1.C3a,    dbo.CRS_AssessFull1.C3b,    dbo.CRS_AssessFull1.C3c, 
    dbo.CRS_AssessFull1.C3d,     dbo.CRS_AssessFull1.C3e,    dbo.CRS_AssessFull1.C3f,    dbo.CRS_AssessFull1.C5,    
    dbo.CRS_AssessFull1.D1,      dbo.CRS_AssessFull1.D2a,    dbo.CRS_AssessFull1.D2b,    dbo.CRS_AssessFull1.D3,    
    dbo.CRS_AssessFull1.F2All,   dbo.CRS_AssessFull1.F2a,    dbo.CRS_AssessFull1.F2b,    dbo.CRS_AssessFull1.F2c,   
    dbo.CRS_AssessFull1.F2d,     dbo.CRS_AssessFull1.F2e,    dbo.CRS_AssessFull1.F2f,    dbo.CRS_AssessFull1.F2g,   
    dbo.CRS_AssessFull1.F3a,     dbo.CRS_AssessFull1.F3b,    dbo.CRS_AssessFull1.F3c,    dbo.CRS_AssessFull1.G5All, 
    dbo.CRS_AssessFull1.G5a,     dbo.CRS_AssessFull1.G5b,    dbo.CRS_AssessFull1.G5c,    dbo.CRS_AssessFull1.G5d,   
    dbo.CRS_AssessFull1.G8All,   dbo.CRS_AssessFull1.G8a,    dbo.CRS_AssessFull1.G8b,    dbo.CRS_AssessFull1.G8c,   
    dbo.CRS_AssessFull1.G8d,     dbo.CRS_AssessFull1.J3a,    dbo.CRS_AssessFull1.J3b,    dbo.CRS_AssessFull1.J3c,   
    dbo.CRS_AssessFull1.J3d,     dbo.CRS_AssessFull1.J3e,    dbo.CRS_AssessFull1.J3f,    dbo.CRS_AssessFull1.J3g,   
    dbo.CRS_AssessFull1.J3h,     dbo.CRS_AssessFull1.J3I,    dbo.CRS_AssessFull1.J3j, 
    
    dbo.CRS_AssessFull2.L1All,   dbo.CRS_AssessFull2.L1a,    dbo.CRS_AssessFull2.L1b,    dbo.CRS_AssessFull2.L1c, 
    dbo.CRS_AssessFull2.L1d,     dbo.CRS_AssessFull2.L1e,    dbo.CRS_AssessFull2.L1f,    dbo.CRS_AssessFull2.M3, 
    dbo.CRS_AssessFull2.N3All,   dbo.CRS_AssessFull2.N3a,    dbo.CRS_AssessFull2.N3b,    dbo.CRS_AssessFull2.N3c, 
    dbo.CRS_AssessFull2.N3d,     dbo.CRS_AssessFull2.N4All,  dbo.CRS_AssessFull2.N4a,    dbo.CRS_AssessFull2.N4b, 
    dbo.CRS_AssessFull2.N4c,     dbo.CRS_AssessFull2.N4d,    dbo.CRS_AssessFull2.N4e,    dbo.CRS_AssessFull2.N4f, 
    dbo.CRS_AssessFull2.N4g,     dbo.CRS_AssessFull2.N4h,    dbo.CRS_AssessFull2.N4I,    dbo.CRS_AssessFull2.N4j, 
    dbo.CRS_AssessFull2.N4k,     dbo.CRS_AssessFull2.N4l,    dbo.CRS_AssessFull2.N5a,    dbo.CRS_AssessFull2.N5b, 
    dbo.CRS_AssessFull2.O2,      dbo.CRS_AssessFull2.P2All,  dbo.CRS_AssessFull2.P2a,    dbo.CRS_AssessFull2.P2b, 
    dbo.CRS_AssessFull2.P2c,     dbo.CRS_AssessFull2.P2d,    dbo.CRS_AssessFull2.P2e,    dbo.CRS_AssessFull2.P5, 
    dbo.CRS_AssessFull2.P6,      dbo.CRS_AssessFull2.P9,     dbo.CRS_AssessFull2.Q1a,    dbo.CRS_AssessFull2.Q1b, 
    dbo.CRS_AssessFull2.Q1c,     dbo.CRS_AssessFull2.R1a,    dbo.CRS_AssessFull2.R1b,    dbo.CRS_AssessFull2.R1c, 
    
    dbo.CRS_AssessShare1.A9All,  dbo.CRS_AssessShare1.A9a,   dbo.CRS_AssessShare1.A9b,   dbo.CRS_AssessShare1.A9c, 
    dbo.CRS_AssessShare1.A9d,    dbo.CRS_AssessShare1.A9e,   dbo.CRS_AssessShare1.A9f,   dbo.CRS_AssessShare1.A10All, 
    dbo.CRS_AssessShare1.A10a,   dbo.CRS_AssessShare1.A10b,  dbo.CRS_AssessShare1.A10c,  dbo.CRS_AssessShare1.A10d, 
    dbo.CRS_AssessShare1.A10e,   dbo.CRS_AssessShare1.A10f,  dbo.CRS_AssessShare1.A10g,  dbo.CRS_AssessShare1.A10h, 
    dbo.CRS_AssessShare1.B1,     dbo.CRS_AssessShare1.B2a,   dbo.CRS_AssessShare1.B2b,   dbo.CRS_AssessShare1.B3All, 
    dbo.CRS_AssessShare1.B3a,    dbo.CRS_AssessShare1.B3b,   dbo.CRS_AssessShare1.B3c,   dbo.CRS_AssessShare1.B3d, 
    dbo.CRS_AssessShare1.B4,     dbo.CRS_AssessShare1.B5a,   dbo.CRS_AssessShare1.B5b,   dbo.CRS_AssessShare1.B5c, 
    dbo.CRS_AssessShare1.B5d,    dbo.CRS_AssessShare1.B5e,   dbo.CRS_AssessShare1.B5f,   dbo.CRS_AssessShare1.B6, 
    dbo.CRS_AssessShare1.C4,     dbo.CRS_AssessShare1.C6,    dbo.CRS_AssessShare1.C7,    dbo.CRS_AssessShare1.E1a, 
    dbo.CRS_AssessShare1.E1b,    dbo.CRS_AssessShare1.E1c,   dbo.CRS_AssessShare1.E1d,   dbo.CRS_AssessShare1.E1e, 
    dbo.CRS_AssessShare1.E1f,    dbo.CRS_AssessShare1.E1g,   dbo.CRS_AssessShare1.E1h,   dbo.CRS_AssessShare1.E1I, 
    dbo.CRS_AssessShare1.E1j,    dbo.CRS_AssessShare1.E1k,   dbo.CRS_AssessShare1.E1l,   dbo.CRS_AssessShare1.E1m, 
    dbo.CRS_AssessShare1.E1n,    dbo.CRS_AssessShare1.E1o,   dbo.CRS_AssessShare1.E1p,   dbo.CRS_AssessShare1.E2, 
    dbo.CRS_AssessShare1.E3,     dbo.CRS_AssessShare1.E4aA,  dbo.CRS_AssessShare1.E4aB,  dbo.CRS_AssessShare1.E4bA,
    dbo.CRS_AssessShare1.E4bB,   dbo.CRS_AssessShare1.E4cA,  dbo.CRS_AssessShare1.E4cB,  dbo.CRS_AssessShare1.E4dA, 
    dbo.CRS_AssessShare1.E4dB,   dbo.CRS_AssessShare1.E4eA,  dbo.CRS_AssessShare1.E4eB,  dbo.CRS_AssessShare1.E5, 
    dbo.CRS_AssessShare1.A11a,   dbo.CRS_AssessShare1.A11b,  dbo.CRS_AssessShare1.A12a,   dbo.CRS_AssessShare1.A12b,   
    
    dbo.CRS_AssessShare2.F1All,  dbo.CRS_AssessShare2.F1a,   dbo.CRS_AssessShare2.F1b,   dbo.CRS_AssessShare2.F1c, 
    dbo.CRS_AssessShare2.F1d,    dbo.CRS_AssessShare2.F1e,   dbo.CRS_AssessShare2.F1f,   dbo.CRS_AssessShare2.G1aA, 
    dbo.CRS_AssessShare2.G1aB,   dbo.CRS_AssessShare2.G1bA,  dbo.CRS_AssessShare2.G1bB,  dbo.CRS_AssessShare2.G1cA, 
    dbo.CRS_AssessShare2.G1cB,   dbo.CRS_AssessShare2.G1dA,  dbo.CRS_AssessShare2.G1dB,  dbo.CRS_AssessShare2.G1eA, 
    dbo.CRS_AssessShare2.G1eB,   dbo.CRS_AssessShare2.G1fA,  dbo.CRS_AssessShare2.G1fB,  dbo.CRS_AssessShare2.G1gA, 
    dbo.CRS_AssessShare2.G1gB,   dbo.CRS_AssessShare2.G1hA,  dbo.CRS_AssessShare2.G1hB,  dbo.CRS_AssessShare2.G1iA, 
    dbo.CRS_AssessShare2.G1iB,   dbo.CRS_AssessShare2.G1jA,  dbo.CRS_AssessShare2.G1jB,  dbo.CRS_AssessShare2.G2A, 
    dbo.CRS_AssessShare2.G2B,    dbo.CRS_AssessShare2.G3a,   dbo.CRS_AssessShare2.G3b,   dbo.CRS_AssessShare2.G4aA, 
    dbo.CRS_AssessShare2.G4aB,   dbo.CRS_AssessShare2.G4bA,  dbo.CRS_AssessShare2.G4bB,  dbo.CRS_AssessShare2.G4cA, 
    dbo.CRS_AssessShare2.G4cB,   dbo.CRS_AssessShare2.G4dA,  dbo.CRS_AssessShare2.G4dB,  dbo.CRS_AssessShare2.G4eA, 
    dbo.CRS_AssessShare2.G4eB,   dbo.CRS_AssessShare2.G4fA,  dbo.CRS_AssessShare2.G4fB,  dbo.CRS_AssessShare2.G6All, 
    dbo.CRS_AssessShare2.G6a,    dbo.CRS_AssessShare2.G6b,   dbo.CRS_AssessShare2.G6c,   dbo.CRS_AssessShare2.G6d, 
    dbo.CRS_AssessShare2.G6e,    dbo.CRS_AssessShare2.G7,    dbo.CRS_AssessShare2.G9,    dbo.CRS_AssessShare2.H1a, 
    dbo.CRS_AssessShare2.H1b,    dbo.CRS_AssessShare2.H2All, dbo.CRS_AssessShare2.H2a,   dbo.CRS_AssessShare2.H2b, 
    dbo.CRS_AssessShare2.H2c,    dbo.CRS_AssessShare2.H2d,   dbo.CRS_AssessShare2.H3All, dbo.CRS_AssessShare2.H3a, 
    dbo.CRS_AssessShare2.H3b,    dbo.CRS_AssessShare2.H3c,   dbo.CRS_AssessShare2.H3d,   dbo.CRS_AssessShare2.H3e, 
    dbo.CRS_AssessShare2.H3f,    dbo.CRS_AssessShare2.H3g,   dbo.CRS_AssessShare2.H3h,   dbo.CRS_AssessShare2.H3I, 
    dbo.CRS_AssessShare2.H4, 
    
    dbo.CRS_AssessShare3.I1All,  dbo.CRS_AssessShare3.I1a,   dbo.CRS_AssessShare3.I1b,   dbo.CRS_AssessShare3.I1c, 
    dbo.CRS_AssessShare3.I1d,    dbo.CRS_AssessShare3.I1e,   dbo.CRS_AssessShare3.I1f,   dbo.CRS_AssessShare3.I1g, 
    dbo.CRS_AssessShare3.I1h,    dbo.CRS_AssessShare3.I1i,   dbo.CRS_AssessShare3.I1j,   dbo.CRS_AssessShare3.I1k, 
    dbo.CRS_AssessShare3.I1l,    dbo.CRS_AssessShare3.I1m,   dbo.CRS_AssessShare3.I1n,   dbo.CRS_AssessShare3.I1o, 
    dbo.CRS_AssessShare3.I1p,    dbo.CRS_AssessShare3.I1q,   dbo.CRS_AssessShare3.I1r,   dbo.CRS_AssessShare3.I1s, 
    dbo.CRS_AssessShare3.I1t,    dbo.CRS_AssessShare3.I1u,   dbo.CRS_AssessShare3.I1v,   dbo.CRS_AssessShare3.I1w, 
    dbo.CRS_AssessShare3.I1x,    dbo.CRS_AssessShare3.I1y,   dbo.CRS_AssessShare3.I1z,   dbo.CRS_AssessShare3.I1aa, 
    dbo.CRS_AssessShare3.I1bb,   dbo.CRS_AssessShare3.I1cc,  dbo.CRS_AssessShare3.I1dd,  dbo.CRS_AssessShare3.I1ee, 
    dbo.CRS_AssessShare3.I1ff,   dbo.CRS_AssessShare3.I1gg,  dbo.CRS_AssessShare3.I1hh,  dbo.CRS_AssessShare3.I1ii, 
    dbo.CRS_AssessShare3.I1jj,   dbo.CRS_AssessShare3.I1kk,  dbo.CRS_AssessShare3.I1ll,  dbo.CRS_AssessShare3.I1mm, 
    dbo.CRS_AssessShare3.I1nn,   dbo.CRS_AssessShare3.I1oo,  dbo.CRS_AssessShare3.I1pp,  dbo.CRS_AssessShare3.I1qq, 
    dbo.CRS_AssessShare3.I1rr,   dbo.CRS_AssessShare3.I1ss,  dbo.CRS_AssessShare3.I1tt,  dbo.CRS_AssessShare3.I1uu, 
    dbo.CRS_AssessShare3.I2All,  dbo.CRS_AssessShare3.I2a,   dbo.CRS_AssessShare3.I2b,   dbo.CRS_AssessShare3.I2c, 
    dbo.CRS_AssessShare3.I2d,    dbo.CRS_AssessShare3.I2e,   dbo.CRS_AssessShare3.I2f,   dbo.CRS_AssessShare3.I2g, 
    dbo.CRS_AssessShare3.I2h,    dbo.CRS_AssessShare3.I2I,   dbo.CRS_AssessShare3.I2j,   dbo.CRS_AssessShare3.I2k, 
    dbo.CRS_AssessShare3.I2l,    dbo.CRS_AssessShare3.I2m,   dbo.CRS_AssessShare3.J1All, dbo.CRS_AssessShare3.J1a, 
    dbo.CRS_AssessShare3.J1b,    dbo.CRS_AssessShare3.J1c,   dbo.CRS_AssessShare3.J1d,   dbo.CRS_AssessShare3.J1e, 
    dbo.CRS_AssessShare3.J1f,    dbo.CRS_AssessShare3.J1g,   dbo.CRS_AssessShare3.J1h,   dbo.CRS_AssessShare3.J1i, 
    dbo.CRS_AssessShare3.J1j,    dbo.CRS_AssessShare3.J1k,   dbo.CRS_AssessShare3.J1l,   dbo.CRS_AssessShare3.J1m, 
    dbo.CRS_AssessShare3.J1n,    dbo.CRS_AssessShare3.J1o,   dbo.CRS_AssessShare3.J2a,   dbo.CRS_AssessShare3.J2b, 
    dbo.CRS_AssessShare3.J4All,  dbo.CRS_AssessShare3.J4a,   dbo.CRS_AssessShare3.J4b,   dbo.CRS_AssessShare3.J4c, 
    dbo.CRS_AssessShare3.J4d,    dbo.CRS_AssessShare3.J5All, dbo.CRS_AssessShare3.J5a,   dbo.CRS_AssessShare3.J5b, 
    dbo.CRS_AssessShare3.J5c,    
    
    dbo.CRS_AssessShare4.K1All,  dbo.CRS_AssessShare4.K1a,   dbo.CRS_AssessShare4.K1b,   dbo.CRS_AssessShare4.K1c, 
    dbo.CRS_AssessShare4.K2a,    dbo.CRS_AssessShare4.K2b,   dbo.CRS_AssessShare4.K3a,   dbo.CRS_AssessShare4.K3b, 
    dbo.CRS_AssessShare4.K4All,  dbo.CRS_AssessShare4.K4a,   dbo.CRS_AssessShare4.K4b,   dbo.CRS_AssessShare4.K4c, 
    dbo.CRS_AssessShare4.K5All,  dbo.CRS_AssessShare4.K5a,   dbo.CRS_AssessShare4.K5b,   dbo.CRS_AssessShare4.K5c, 
    dbo.CRS_AssessShare4.K5d,    dbo.CRS_AssessShare4.K5e,   dbo.CRS_AssessShare4.K5f,   dbo.CRS_AssessShare4.K5g, 
    dbo.CRS_AssessShare4.K5h,    dbo.CRS_AssessShare4.K6a,   dbo.CRS_AssessShare4.K6b,   dbo.CRS_AssessShare4.M1a, 
    dbo.CRS_AssessShare4.M1b,    dbo.CRS_AssessShare4.M1c,   dbo.CRS_AssessShare4.M1d,   dbo.CRS_AssessShare4.M2a, 
    dbo.CRS_AssessShare4.M2b,    dbo.CRS_AssessShare4.M4All, dbo.CRS_AssessShare4.M4a,   dbo.CRS_AssessShare4.M4b, 
    dbo.CRS_AssessShare4.M4c,    dbo.CRS_AssessShare4.M4d,   dbo.CRS_AssessShare4.M4e,   dbo.CRS_AssessShare4.M4f, 
    dbo.CRS_AssessShare4.M4g,    dbo.CRS_AssessShare4.M5All, dbo.CRS_AssessShare4.M5a,   dbo.CRS_AssessShare4.M5b, 
    dbo.CRS_AssessShare4.M5c,    dbo.CRS_AssessShare4.M5d,   dbo.CRS_AssessShare4.M5e,   dbo.CRS_AssessShare4.M5f, 
    dbo.CRS_AssessShare4.M5g,    dbo.CRS_AssessShare4.M5h,   dbo.CRS_AssessShare4.M5I,   dbo.CRS_AssessShare4.M6All, 
    dbo.CRS_AssessShare4.M6a,    dbo.CRS_AssessShare4.M6b,   dbo.CRS_AssessShare4.M6c,   dbo.CRS_AssessShare4.M6d, 
    dbo.CRS_AssessShare4.M6e,    dbo.CRS_AssessShare4.M6f,   dbo.CRS_AssessShare4.N1All, dbo.CRS_AssessShare4.N1a, 
    dbo.CRS_AssessShare4.N1b,    dbo.CRS_AssessShare4.N1c,   dbo.CRS_AssessShare4.N2,    dbo.CRS_AssessShare4.O1, 
    dbo.CRS_AssessShare4.O3,     dbo.CRS_AssessShare4.O4a,   dbo.CRS_AssessShare4.O4b,   dbo.CRS_AssessShare4.O4c, 
    dbo.CRS_AssessShare4.O4d,    dbo.CRS_AssessShare4.O4e,   dbo.CRS_AssessShare4.O4f, 
    
    dbo.CRS_AssessShare5.P1aAll, dbo.CRS_AssessShare5.P1aa,  dbo.CRS_AssessShare5.P1ab,  dbo.CRS_AssessShare5.P1ac, 
    dbo.CRS_AssessShare5.P1ad,   dbo.CRS_AssessShare5.P1ae,  dbo.CRS_AssessShare5.P1af,  dbo.CRS_AssessShare5.P1ag, 
    dbo.CRS_AssessShare5.P1ah,   dbo.CRS_AssessShare5.P1ai,  dbo.CRS_AssessShare5.P1aj,  dbo.CRS_AssessShare5.P1ak, 
    dbo.CRS_AssessShare5.P1al,   dbo.CRS_AssessShare5.P1am,  dbo.CRS_AssessShare5.P1an,  dbo.CRS_AssessShare5.P1ao, 
    dbo.CRS_AssessShare5.P1ap,   dbo.CRS_AssessShare5.P1aq,  dbo.CRS_AssessShare5.P1ar,  dbo.CRS_AssessShare5.P1baA, 
    dbo.CRS_AssessShare5.P1baB,  dbo.CRS_AssessShare5.P1bbA, dbo.CRS_AssessShare5.P1bbB, dbo.CRS_AssessShare5.P1bcA, 
    dbo.CRS_AssessShare5.P1bcB,  dbo.CRS_AssessShare5.P1bdA, dbo.CRS_AssessShare5.P1bdB, dbo.CRS_AssessShare5.P1beA, 
    dbo.CRS_AssessShare5.P1beB,  dbo.CRS_AssessShare5.P1bfA, dbo.CRS_AssessShare5.P1bfB, dbo.CRS_AssessShare5.P3a, 
    dbo.CRS_AssessShare5.P3b,    dbo.CRS_AssessShare5.P3c,   dbo.CRS_AssessShare5.P3d,   dbo.CRS_AssessShare5.P3e, 
    dbo.CRS_AssessShare5.P3f,    dbo.CRS_AssessShare5.P3g,   dbo.CRS_AssessShare5.P3h,   dbo.CRS_AssessShare5.P3I, 
    dbo.CRS_AssessShare5.P3j,    dbo.CRS_AssessShare5.P3k,   dbo.CRS_AssessShare5.P4a,   dbo.CRS_AssessShare5.P4b, 
    dbo.CRS_AssessShare5.P4c,    dbo.CRS_AssessShare5.P4d,   dbo.CRS_AssessShare5.P4e,   dbo.CRS_AssessShare5.P7, 
    dbo.CRS_AssessShare5.P8,     dbo.CRS_AssessShare5.Q2,    dbo.CRS_AssessShare5.R2b, 
    
    dbo.CRS_Diagnosis.I3a,       dbo.CRS_Diagnosis.I3b,      dbo.CRS_Diagnosis.I3c,      dbo.CRS_Diagnosis.I3d, 
    dbo.CRS_Diagnosis.I3e,       dbo.CRS_Diagnosis.I3f, 
    
    dbo.CRS_RAPS2.Delirium,      dbo.CRS_RAPS2.Cognitive,    dbo.CRS_RAPS2.Visual,       dbo.CRS_RAPS2.Communication, 
    dbo.CRS_RAPS2.ADL_Function,  dbo.CRS_RAPS2.Urinary,      dbo.CRS_RAPS2.Psychosocial, dbo.CRS_RAPS2.Mood, 
    dbo.CRS_RAPS2.Behavioural,   dbo.CRS_RAPS2.Activities,   dbo.CRS_RAPS2.Falls,        dbo.CRS_RAPS2.Nutritional, 
    dbo.CRS_RAPS2.Feeding,       dbo.CRS_RAPS2.Dehydration,  dbo.CRS_RAPS2.Dental,       dbo.CRS_RAPS2.Ulcers, 
    dbo.CRS_RAPS2.Drugs,         dbo.CRS_RAPS2.Restraints,
    --NP - 00099
    dbo.CRS_Hobic.Fatigue,       dbo.CRS_Hobic.Dyspnea,      dbo.CRS_Hobic.Nausea,
    --EN-00435
    dbo.CRS_OutcomeScale.[ADL_Long], dbo.CRS_OutcomeScale.[ADL_Short], dbo.CRS_OutcomeScale.[ADL_Self], dbo.CRS_OutcomeScale.[ABS], 
    dbo.CRS_OutcomeScale.[CHESS], dbo.CRS_OutcomeScale.[CPS], dbo.CRS_OutcomeScale.[DRS], dbo.CRS_OutcomeScale.[ISE], 
    dbo.CRS_OutcomeScale.[Pain], dbo.CRS_OutcomeScale.[PSI], dbo.CRS_OutcomeScale.PURS, dbo.CRS_OutcomeScale.FRS, 
    --EN-00436
    dbo.CRS_CAPS.[CAP_ActivitiesDailyLiving], dbo.CRS_CAPS.[CAP_PhysicalRestraints], dbo.CRS_CAPS.[CAP_CognitiveLoss], dbo.CRS_CAPS.[CAP_Delirium],
    dbo.CRS_CAPS.[CAP_Communication], dbo.CRS_CAPS.[CAP_Mood], dbo.CRS_CAPS.[CAP_Behaviour], dbo.CRS_CAPS.[CAP_Activities], dbo.CRS_CAPS.[CAP_SocialRelationship],
    dbo.CRS_CAPS.[CAP_Falls], dbo.CRS_CAPS.[CAP_Pain], dbo.CRS_CAPS.[CAP_PressureUlcers], dbo.CRS_CAPS.[CAP_CardioRespiratoryConditions], dbo.CRS_CAPS.[CAP_UnderNutrition],
    dbo.CRS_CAPS.[CAP_Dehydration], dbo.CRS_CAPS.[CAP_FeedingTube], dbo.CRS_CAPS.[CAP_AppropriateMedications], dbo.CRS_CAPS.[CAP_UrinaryIncontinence], 
    dbo.CRS_CAPS.[CAP_BowelConditions],

    --ED-02133
    dbo.CRS_UpdateRecord.[AD1], dbo.CRS_UpdateRecord.[AD2], dbo.CRS_UpdateRecord.[AD4]
	--EN-00524
	,[UDDate6],[UDDate7],[UDDate8],[UDDate9],[UDDate10]
	,[UDDate11],[UDDate12],[UDDate13],[UDDate14],[UDDate15]
	,[UDDate16],[UDDate17],[UDDate18],[UDDate19],[UDDate20]
	,[UDDate21],[UDDate22],[UDDate23],[UDDate24],[UDDate25]
	,[UDTime6],[UDTime7],[UDTime8],[UDTime9],[UDTime10]
	,[UDTime11],[UDTime12],[UDTime13],[UDTime14],[UDTime15]
	,[UDTime16],[UDTime17],[UDTime18],[UDTime19],[UDTime20]
	,[UDTime21],[UDTime22],[UDTime23],[UDTime24],[UDTime25]
	,[UDLookUp6],[UDLookUp7],[UDLookUp8],[UDLookUp9],[UDLookUp10]
	,[UDLookUp11],[UDLookUp12],[UDLookUp13],[UDLookUp14],[UDLookUp15]
	,[UDLookUp16],[UDLookUp17],[UDLookUp18],[UDLookUp19],[UDLookUp20]
	,[UDLookUp21],[UDLookUp22],[UDLookUp23],[UDLookUp24],[UDLookUp25]
	,[UDInteger6],[UDInteger7],[UDInteger8],[UDInteger9],[UDInteger10]
	,[UDInteger11],[UDInteger12],[UDInteger13],[UDInteger14],[UDInteger15]
	,[UDInteger16],[UDInteger17],[UDInteger18],[UDInteger19],[UDInteger20]
	,[UDInteger21],[UDInteger22],[UDInteger23],[UDInteger24],[UDInteger25]
	,[UDText6],[UDText7],[UDText8],[UDText9],[UDText10]
	,[UDText11],[UDText12],[UDText13],[UDText14],[UDText15]
	,[UDText16],[UDText17],[UDText18],[UDText19],[UDText20]
	,[UDText21],[UDText22],[UDText23],[UDText24],[UDText25]
	,[UDSmallText6],[UDSmallText7],[UDSmallText8],[UDSmallText9],[UDSmallText10]
	,[UDSmallText11],[UDSmallText12],[UDSmallText13],[UDSmallText14],[UDSmallText15]
	,[UDSmallText16],[UDSmallText17],[UDSmallText18],[UDSmallText19],[UDSmallText20]
	,[UDSmallText21],[UDSmallText22],[UDSmallText23],[UDSmallText24],[UDSmallText25]

into #ABMainTemp
from dbo.CRS_Demographic 
left join dbo.CRS_Diagnosis     on dbo.CRS_Demographic.AbstractID = dbo.CRS_Diagnosis.AbstractID 
left join dbo.CRS_AssessShare5  on dbo.CRS_Demographic.AbstractID = dbo.CRS_AssessShare5.AbstractID 
left join dbo.CRS_AssessShare4  on dbo.CRS_Demographic.AbstractID = dbo.CRS_AssessShare4.AbstractID 
left join dbo.CRS_AssessShare3  on dbo.CRS_Demographic.AbstractID = dbo.CRS_AssessShare3.AbstractID 
left join dbo.CRS_AssessShare2  on dbo.CRS_Demographic.AbstractID = dbo.CRS_AssessShare2.AbstractID 
left join dbo.CRS_AssessShare1  on dbo.CRS_Demographic.AbstractID = dbo.CRS_AssessShare1.AbstractID 
left join dbo.CRS_AssessFull2   on dbo.CRS_Demographic.AbstractID = dbo.CRS_AssessFull2.AbstractID 
left join dbo.CRS_AssessFull1   on dbo.CRS_Demographic.AbstractID = dbo.CRS_AssessFull1.AbstractID 
left join dbo.CRS_Admission     on dbo.CRS_Demographic.AbstractID = dbo.CRS_Admission.AbstractID 
left join dbo.CRS_Ancillary     on dbo.CRS_Demographic.AbstractID = dbo.CRS_Ancillary.AbstractID
left join dbo.CRS_BasicOption   on dbo.CRS_Demographic.AbstractID = dbo.CRS_BasicOption.AbstractID
left join dbo.CRS_UDAbstracting on dbo.CRS_Demographic.AbstractID = dbo.CRS_UDAbstracting.AbstractID
left join dbo.CRS_RAPS2         on dbo.CRS_Demographic.AbstractID = dbo.CRS_RAPS2.AbstractID 
left join dbo.CRS_Hobic         on dbo.CRS_Demographic.AbstractID = dbo.CRS_Hobic.AbstractID  --NP - 00099
left join dbo.CRS_OutcomeScale  on dbo.CRS_Demographic.AbstractID = dbo.CRS_OutcomeScale.AbstractID  --EN-00435
left join dbo.CRS_CAPS          on dbo.CRS_Demographic.AbstractID = dbo.CRS_CAPS.AbstractID --EN-00436
left join dbo.CRS_UpdateRecord on dbo.CRS_Demographic.AbstractID = dbo.CRS_UpdateRecord.AbstractID --ED-02133
left join dbo.CRS_UDFieldsDate on dbo.CRS_Demographic.AbstractID = dbo.CRS_UDFieldsDate.AbstractID --EN-00524
left join dbo.CRS_UDFieldsTime on dbo.CRS_Demographic.AbstractID = dbo.CRS_UDFieldsTime.AbstractID --EN-00524
left join dbo.CRS_UDFieldsLookUp on dbo.CRS_Demographic.AbstractID = dbo.CRS_UDFieldsLookUp.AbstractID --EN-00524
left join dbo.CRS_UDFieldsInteger on dbo.CRS_Demographic.AbstractID = dbo.CRS_UDFieldsInteger.AbstractID --EN-00524
left join dbo.CRS_UDFieldsText on dbo.CRS_Demographic.AbstractID = dbo.CRS_UDFieldsText.AbstractID --EN-00524
left join dbo.CRS_UDFieldsSmallText on dbo.CRS_Demographic.AbstractID = dbo.CRS_UDFieldsSmallText.AbstractID --EN-00524

where dbo.CRS_Demographic.AbstractID = @AbstractID


select * into #CRS_Medication from CRS_Medication where AbstractID = @AbstractID--10
set @CRS_MedicationCount = @@rowcount
select * into #CRS_Signature from CRS_Signature where AbstractID = @AbstractID--11
set @CRS_SignatureCount = @@rowcount
select * into #CRS_Project from CRS_Project where AbstractID = @AbstractID -- MultipleIndex = 114
set @CRS_ProjectCount = @@rowcount
select * into #CRS_SpecialProject from AB_SpecialProjects where AbstractID = @AbstractID and Caretype = 4 -- MultipleIndex = 9 ED - 02384
set @CRS_SpecialProjectCount = @@rowcount

select 
    dbo.U_Fields.FieldID, 
    dbo.U_Fields.SystemName, 
    dbo.U_UsersFields.LookUpTable, 
    dbo.U_UsersFields.MultipleIndex, 
    dbo.U_UsersFields.DataType, 
    dbo.U_UsersFields.SortOrder 
into #UsersFields
from dbo.U_Fields 
join dbo.U_UsersFields on dbo.U_Fields.FieldID = dbo.U_UsersFields.FieldID
where dbo.U_UsersFields.UserID = @UserID 
and dbo.U_UsersFields.AppID = @Appid 
and dbo.U_UsersFields.DataType <> 100000 
and dbo.U_Fields.IsGroup = 0
and dbo.U_Fields.FieldID not between 60000 and 70000
order by dbo.U_UsersFields.SortOrder, dbo.U_UsersFields.FieldID

update #UsersFields set LookupTable = 'LU_ProviderService' where LookupTable = 'LLU_ProviderServices'
update #UsersFields set LookupTable = 'LU_ProviderSpecialty' where LookupTable = 'LLU_ProviderSpecialty'
update #UsersFields set LookupTable = 'LU_CodeFile' where isnumeric(LookupTable) = 1
update #UsersFields set LookupTable = 'ICD_DiagFile10' where DataType = 60
update #UsersFields set LookupTable = 'ICD_ProcFile10' where DataType = 61

--PR-01568
-- select @DDate = convert(varchar(10), AdmitDate, 101) from CRS_Demographic where AbstractID = @AbstractID
if @AppID = 470
	select @DDate = convert(varchar(10), AdmitDate, 101) from CRS_Demographic where AbstractID = @AbstractID
else if @AppID = 472 or @AppID = 473
	select @DDate = convert(varchar(10), A3, 101) from CRS_Demographic where AbstractID = @AbstractID
else if @AppID = 474
	select @DDate = convert(varchar(10), DischargeDate, 101) from CRS_Demographic where AbstractID = @AbstractID
else if @AppID = 475
	select @DDate = convert(varchar(10), AB1b, 101) from CRS_Demographic where AbstractID = @AbstractID
else if @AppID = 471
	select @DDate = convert(varchar(10), Z7, 101) from CRS_Demographic where AbstractID = @AbstractID
else if @AppID = 476 --ED-02133
	select @DDate = convert(varchar(10), Z12, 101) from CRS_Demographic where AbstractID = @AbstractID
else if @AppID = 477 --ED-02133
	select @DDate = convert(varchar(10), Z13, 101) from CRS_Demographic where AbstractID = @AbstractID

if @DDate is null set @DDate = '2003/04/01'

declare cur cursor fast_forward for
    select FieldID, SystemName, LookUpTable, MultipleIndex, DataType, SortOrder 
    from #UsersFields

Open cur

fetch next from cur into @FieldID, @SystemName, @LookUpTable, @MultipleIndex, @DataType, @SortOrder
--PR - 06080 We don't need to remove abstractid
--fetch next from cur into @FieldID, @SystemName, @LookUpTable, @MultipleIndex, @DataType, @SortOrder 


while @@fetch_status = 0 begin
    set @sql = ''

    if @MultipleIndex = 10 begin
        if isnull(@LookUpTable, '') = '' and @CRS_MedicationCount > 0 
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, null, null, UserDescription = ' + @SystemName + ', null, null, null from #CRS_Medication'
        else if @CRS_MedicationCount > 0             set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo from #CRS_Medication t left join ' + @LookUpTable + ' l on t.' + @SystemName + ' = l.Code'
    end
    else if @MultipleIndex = 11 begin
        if isnull(@LookUpTable, '') = '' and @CRS_SignatureCount > 0 
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', ProviderOccurrence, null, null, UserDescription = ' + @SystemName + ', null, null, null from #CRS_Signature'
        else if @CRS_SignatureCount > 0             set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', ProviderOccurrence, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo from #CRS_Signature t left join ' + @LookUpTable + ' l on t.' + @SystemName + ' = l.Code'
    end
    else if @MultipleIndex = 114 begin
        if isnull(@LookUpTable, '') = '' and @CRS_ProjectCount > 0
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', ProjectOccurrence, null, null, UserDescription = ' + @SystemName + ', null, null, null from #CRS_Project'
        else if @CRS_ProjectCount > 0             set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', ProjectOccurrence, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo from #CRS_Project t left join ' + @LookUpTable + ' l on t.' + @SystemName + ' = l.Code'
    end 
    --ED - 02385
    else if @MultipleIndex = 9 begin
        if isnull(@LookUpTable, '') = '' and @CRS_SpecialProjectCount > 0
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', OccurrenceNumber, null, null, UserDescription = ' + @SystemName + ', null, null, null from #CRS_SpecialProject'
        else if @CRS_SpecialProjectCount > 0 and isnumeric(@LookUpTable) = 1
		    set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', OccurrenceNumber, Code = CIHIValue, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo from #CRS_SpecialProject t left join LU_codeFile l on t.' + @SystemName + ' = l.CIHIValue and l.LookupID = ' + @LookUpTable + ' and ''' + @DDate + ''' between ValidFrom and ValidTo ' 
        else if @CRS_SpecialProjectCount > 0 and isnumeric(@LookUpTable) = 0
		    set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', OccurrenceNumber, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo from #CRS_SpecialProject t left join ' + @LookUpTable + ' l on t.' + @SystemName + ' = l.code '
    end 
    else begin
        if isnull(@LookUpTable, '') = '' begin               
            if @SystemName <> 'AbstractNotes' and @SystemName <> 'RecordNotes' 
                set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', 0, null, null, UserDescription = ' + @SystemName + ', null, null, null from #ABMainTemp'
        end
        else if @LookUpTable = 'LU_PostalCode' begin
            set @sql = 'select @result =  ' + @SystemName + ' from #ABMainTemp'
            exec sp_executesql @sql, N'@result varchar(50) output', @result output
            set @sql = ''            
    
            if isnull(@result, '') <> '' begin
                set @sql = 
                    'select top 1 ' + @SortOrder + ', ' + @FieldID + ', 0, Code, ''' + left(@result, 3) + ' ' + substring(@result, 4, 3) + ''', UserDescription, ''' + @result + ''', ValidFrom, ValidTo ' + 
                    'from LU_PostalCode ' + 
                    'where ''' + @DDate + ''' between ValidFrom and ValidTo ' + 
                    'and CIHIValue in ( ' + 
                        '''' + left(@result, 6) + ''', ' + 
                        '''' + left(@result, 5) + ''', ' + 
                        '''' + left(@result, 4) + ''', ' + 
                        '''' + left(@result, 3) + ''', ' + 
                        '''' + left(@result, 2) + ''', ' + 
                        '''' + left(@result, 1) + ''') ' + 
                    'order by len(CIHIValue) desc'
            end
        end
        else begin
            set @sql = 'select @result = ' + @SystemName + ' from #ABMainTemp'
            exec sp_executesql @sql, N'@result varchar(50) output', @result output
            set @sql = ''            

            if isnull(@result, '') <> '' begin
                set @sql = 
                    'select ' + @SortOrder + ', ' + @FieldID + ', 0, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo ' + 
                    'from ' + @LookUpTable + ' ' + 
                    'where (Code = ' + @result + ')'
            end
        end
    end

    if len(@sql) > 0
        insert into #TableABLoad (SortOrder, FieldID, Occurrence, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo) exec (@sql)

    fetch next from cur into @FieldID, @SystemName, @LookUpTable, @MultipleIndex, @DataType, @SortOrder
end

close cur
deallocate cur

update #TableABLoad 
set Code = 0
, DisplayCode = null
, UserDescription = null
, CIHIValue = null 
where (ValidTo < cast(@DDate as datetime) or ValidFrom > cast(@DDate as datetime))

update #TableABLoad 
set UserDescription = convert(varchar(20), cast(UserDescription as datetime), 120) 
where isdate(UserDescription) = 1 and len(UserDescription) > 10

if @Clone = 1
    update #TableABLoad 
    set Code = null
    , DisplayCode = null
    , UserDescription = null
    , CIHIValue = null 
    where FieldID in (5010, 615, 5031)

set nocount off

select FieldID, Occurrence, Code, DisplayCode, UserDescription, CIHIValue 
from #TableABLoad 
order by SortOrder, Occurrence

--   print datediff(ms, @SDate, getdate())
return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [L_CJRRData]
   @AppID int,
   @UserID int,
   @RecordID int
AS 

set nocount on 

declare @sql nvarchar(1000)
declare @result varchar(50)
declare @LookUpDate varchar(10)

-- for multi-table record counts
declare @CJRR_FemoralComponentCount int
declare @CJRR_TibialComponentCount int 
declare @CJRR_TibialInsertCount int 
declare @CJRR_PatellarComponentCount int 
declare @CJRR_FemoralHeadCount int
declare @CJRR_AcetabularComponentCount int
declare @CJRR_AcetabularInsertCount int
declare @CJRR_CementCount int 

-- for cursor based on #UsersFields
declare @FieldID varchar(10)
declare @SystemName varchar(50)
declare @LookupTable varchar(100)    
declare @ParamProcID int
declare @DataType int
declare @SortOrder varchar(10)

create table #LoadResults 
(
    SortOrder int, 
    FieldID int, 
    Occurrence int,
    Code int,
    DisplayCode varchar(50),
    UserDescription varchar(255),
    CIHIValue varchar(50), 
    Validfrom datetime, 
    ValidTo datetime
)

select
    dbo.CJRR_Abstract.* --,
	--EN-00524
	,[UDDate1],[UDDate2],[UDDate3],[UDDate4],[UDDate5]
	,[UDDate6],[UDDate7],[UDDate8],[UDDate9],[UDDate10]
	,[UDDate11],[UDDate12],[UDDate13],[UDDate14],[UDDate15]
	,[UDDate16],[UDDate17],[UDDate18],[UDDate19],[UDDate20]
	,[UDDate21],[UDDate22],[UDDate23],[UDDate24],[UDDate25]
	,[UDTime1],[UDTime2],[UDTime3],[UDTime4],[UDTime5]
	,[UDTime6],[UDTime7],[UDTime8],[UDTime9],[UDTime10]
	,[UDTime11],[UDTime12],[UDTime13],[UDTime14],[UDTime15]
	,[UDTime16],[UDTime17],[UDTime18],[UDTime19],[UDTime20]
	,[UDTime21],[UDTime22],[UDTime23],[UDTime24],[UDTime25]
	,[UDLookUp1],[UDLookUp2],[UDLookUp3],[UDLookUp4],[UDLookUp5]
	,[UDLookUp6],[UDLookUp7],[UDLookUp8],[UDLookUp9],[UDLookUp10]
	,[UDLookUp11],[UDLookUp12],[UDLookUp13],[UDLookUp14],[UDLookUp15]
	,[UDLookUp16],[UDLookUp17],[UDLookUp18],[UDLookUp19],[UDLookUp20]
	,[UDLookUp21],[UDLookUp22],[UDLookUp23],[UDLookUp24],[UDLookUp25]
	,[UDInteger1],[UDInteger2],[UDInteger3],[UDInteger4],[UDInteger5]
	,[UDInteger6],[UDInteger7],[UDInteger8],[UDInteger9],[UDInteger10]
	,[UDInteger11],[UDInteger12],[UDInteger13],[UDInteger14],[UDInteger15]
	,[UDInteger16],[UDInteger17],[UDInteger18],[UDInteger19],[UDInteger20]
	,[UDInteger21],[UDInteger22],[UDInteger23],[UDInteger24],[UDInteger25]
	,[UDText1],[UDText2],[UDText3],[UDText4],[UDText5]
	,[UDText6],[UDText7],[UDText8],[UDText9],[UDText10]
	,[UDText11],[UDText12],[UDText13],[UDText14],[UDText15]
	,[UDText16],[UDText17],[UDText18],[UDText19],[UDText20]
	,[UDText21],[UDText22],[UDText23],[UDText24],[UDText25]
	,[UDSmallText1],[UDSmallText2],[UDSmallText3],[UDSmallText4],[UDSmallText5]
	,[UDSmallText6],[UDSmallText7],[UDSmallText8],[UDSmallText9],[UDSmallText10]
	,[UDSmallText11],[UDSmallText12],[UDSmallText13],[UDSmallText14],[UDSmallText15]
	,[UDSmallText16],[UDSmallText17],[UDSmallText18],[UDSmallText19],[UDSmallText20]
	,[UDSmallText21],[UDSmallText22],[UDSmallText23],[UDSmallText24],[UDSmallText25]
    
into #CJRRTemp
from dbo.CJRR_Abstract 
left join dbo.CJRR_UDFieldsDate on dbo.CJRR_Abstract.RecordID = dbo.CJRR_UDFieldsDate.RecordID --EN-00524
left join dbo.CJRR_UDFieldsTime on dbo.CJRR_Abstract.RecordID = dbo.CJRR_UDFieldsTime.RecordID --EN-00524
left join dbo.CJRR_UDFieldsLookUp on dbo.CJRR_Abstract.RecordID = dbo.CJRR_UDFieldsLookUp.RecordID --EN-00524
left join dbo.CJRR_UDFieldsInteger on dbo.CJRR_Abstract.RecordID = dbo.CJRR_UDFieldsInteger.RecordID --EN-00524
left join dbo.CJRR_UDFieldsText on dbo.CJRR_Abstract.RecordID = dbo.CJRR_UDFieldsText.RecordID --EN-00524
left join dbo.CJRR_UDFieldsSmallText on dbo.CJRR_Abstract.RecordID = dbo.CJRR_UDFieldsSmallText.RecordID --EN-00524

where dbo.CJRR_Abstract.RecordID = @RecordID

select * into #CJRR_FemoralComponent from CJRR_FemoralComponent where RecordID = @RecordID -- ParamProcID = 14101/15101
set @CJRR_FemoralComponentCount = @@rowcount
select * into #CJRR_TibialComponent from CJRR_TibialComponent where RecordID = @RecordID -- ParamProcID = 14201
set @CJRR_TibialComponentCount = @@rowcount
select * into #CJRR_TibialInsert from CJRR_TibialInsert where RecordID = @RecordID -- ParamProcID = 14301
set @CJRR_TibialInsertCount = @@rowcount
select * into #CJRR_PatellarComponent from CJRR_PatellarComponent where RecordID = @RecordID -- ParamProcID = 14401
set @CJRR_PatellarComponentCount = @@rowcount
select * into #CJRR_FemoralHead from CJRR_FemoralHead where RecordID = @RecordID -- ParamProcID = 15201
set @CJRR_FemoralHeadCount = @@rowcount
select * into #CJRR_AcetabularComponent from CJRR_AcetabularComponent where RecordID = @RecordID -- ParamProcID = 15301
set @CJRR_AcetabularComponentCount = @@rowcount
select * into #CJRR_AcetabularInsert from CJRR_AcetabularInsert where RecordID = @RecordID -- ParamProcID = 15401
set @CJRR_AcetabularInsertCount = @@rowcount
select * into #CJRR_Cement from CJRR_Cement where RecordID = @RecordID -- ParamProcID = 14501/15501
set @CJRR_CementCount = @@rowcount

select 
    dbo.U_Fields.FieldID, 
    dbo.U_Fields.SystemName, 
    dbo.U_UsersFields.LookUpTable, 
    dbo.U_UsersFields.ParamProcID, 
    dbo.U_UsersFields.DataType, 
    dbo.U_UsersFields.SortOrder 
into #UsersFields
from dbo.U_Fields 
join dbo.U_UsersFields on dbo.U_Fields.FieldID = dbo.U_UsersFields.FieldID
where dbo.U_UsersFields.UserID = @UserID 
and dbo.U_UsersFields.AppID = @Appid 
and dbo.U_Fields.IsGroup = 0
and dbo.U_UsersFields.DataType <> 100000 
and dbo.U_Fields.FieldID not between 60000 and 70000
order by dbo.U_UsersFields.SortOrder, dbo.U_UsersFields.FieldID

update #UsersFields set LookupTable = 'LU_CodeFile' where isnumeric(LookupTable) = 1

select @LookUpDate = convert(varchar(10), isnull(SurgeryDate, getdate()), 101) from CJRR_Abstract where RecordID = @RecordID	
if @LookUpDate is null set @LookUpDate = convert(varchar(10), getdate(), 101)  --PR - 03570 '2002/10/01'

declare cur cursor fast_forward for
    select FieldID, SystemName, LookUpTable, ParamProcID, DataType, SortOrder
    from #UsersFields

open cur

fetch next from cur into @FieldID, @SystemName, @LookupTable, @ParamProcID, @DataType, @SortOrder
fetch next from cur into @FieldID, @SystemName, @LookupTable, @ParamProcID, @DataType, @SortOrder

while @@fetch_status = 0 begin
    set @sql = ''

    if @ParamProcID in (14101, 15101)  
    begin
        if isnull(@LookupTable, '') = '' and @CJRR_FemoralComponentCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, null, null, UserDescription = ' + @SystemName + ', null, null, null from #CJRR_FemoralComponent'
        else if @CJRR_FemoralComponentCount > 0 
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo from #CJRR_FemoralComponent t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code'
    end
    else if @ParamProcID = 14201 
    begin
       if isnull(@LookupTable, '') = '' and @CJRR_TibialComponentCount > 0
           set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, null, null, UserDescription = ' + @SystemName + ', null, null, null from #CJRR_TibialComponent'
       else if @CJRR_TibialComponentCount > 0
           set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo from #CJRR_TibialComponent t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code'
    end
    else if @ParamProcID = 14301 
    begin
        if isnull(@LookupTable, '') = '' and @CJRR_TibialInsertCount > 0
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, null, null, UserDescription = ' + @SystemName + ', null, null, null from #CJRR_TibialInsert'
        else if @CJRR_TibialInsertCount > 0
			set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo from #CJRR_TibialInsert t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code'
    end
    else if @ParamProcID = 14401 
    begin
        if isnull(@LookupTable, '') = '' and @CJRR_PatellarComponentCount > 0 
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, null, null, UserDescription = ' + @SystemName + ', null, null, null from #CJRR_PatellarComponent'
        else if @CJRR_PatellarComponentCount > 0
			set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo from #CJRR_PatellarComponent t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code'
    end
    else if @ParamProcID = 15201 
    begin
        if isnull(@LookupTable, '') = '' and @CJRR_FemoralHeadCount > 0 
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, null, null, UserDescription = ' + @SystemName + ', null, null, null from #CJRR_FemoralHead'
        else if @CJRR_FemoralHeadCount > 0
			set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo from #CJRR_FemoralHead t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code'
    end    
    else if @ParamProcID = 15301 
    begin
        if isnull(@LookupTable, '') = '' and @CJRR_AcetabularComponentCount > 0 
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, null, null, UserDescription = ' + @SystemName + ', null, null, null from #CJRR_AcetabularComponent'
        else if @CJRR_AcetabularComponentCount > 0
			set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo from #CJRR_AcetabularComponent t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code'
    end    
    else if @ParamProcID = 15401 
    begin
        if isnull(@LookupTable, '') = '' and @CJRR_AcetabularInsertCount > 0 
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, null, null, UserDescription = ' + @SystemName + ', null, null, null from #CJRR_AcetabularInsert'
        else if @CJRR_AcetabularInsertCount > 0
			set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo from #CJRR_AcetabularInsert t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code'
    end
    else if @ParamProcID in (14501, 15501)
	begin
        if isnull(@LookupTable, '') = '' and @CJRR_CementCount > 0 
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, null, null, UserDescription = ' + @SystemName + ', null, null, null from #CJRR_Cement'
        else if @CJRR_CementCount > 0
			set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', Occurrence, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo from #CJRR_Cement t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code'
    end
    else 
    begin
        if isnull(@LookupTable, '') = '' begin
			if @SystemName = 'LinkID' -- UniversalID from AB_Main
				set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', 0, Code = ' + @SystemName + ', null, null, null, null, null from #CJRRTemp'
            else if @SystemName <> 'AbstractNotes' 
                set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', 0, null, null, UserDescription = ' + @SystemName + ', null, null, null from #CJRRTemp'
        end
        else if @SystemName = 'PostalCode' begin
            set @sql = 'select @result =  ' + @SystemName + ' from #CJRRTemp'
            exec sp_executesql @sql, N'@result varchar(50) output', @result output
            set @sql = ''
            
            if isnull(@result, '') <> '' begin
                set @sql = 
                    'select top 1 ' + @SortOrder + ', ' + @FieldID + ', 0, Code, ''' + left(@result, 3) + ' ' + substring(@result, 4, 3) + ''', UserDescription, ''' + @result + ''', ValidFrom, ValidTo ' + 
                    'from LU_PostalCode ' + 
                    'where ''' + @LookUpDate + ''' between ValidFrom and ValidTo ' + 
                    'and CIHIValue in ( ' + 
                        '''' + left(@result, 6) + ''', ' + 
                        '''' + left(@result, 5) + ''', ' + 
                        '''' + left(@result, 4) + ''', ' + 
                        '''' + left(@result, 3) + ''', ' +
                        '''' + left(@result, 2) + ''', ' + 
                        '''' + left(@result, 1) + ''') ' +
                    'order by len(CIHIValue) desc'
            end
        end
        else begin
            set @sql = 'select @result = ' + @SystemName + ' from #CJRRTemp'
            exec sp_executesql @sql, N'@result varchar(50) output', @result output
            set @sql = ''

            if isnull(@result, '') <> '' 
                set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', 0, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo from ' + @LookupTable + ' where Code = ' + @result + ' '
        end
    end
   
    if len(@sql) > 0 
        insert into #LoadResults (SortOrder, FieldID, Occurrence, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo) exec (@sql)

    fetch next from cur into @FieldID, @SystemName, @LookupTable, @ParamProcID, @DataType, @SortOrder
end

close cur
deallocate cur

update #LoadResults 
set Code = 0
, Displaycode = NULL
, UserDescription = NULL
, CIHIValue = NULL 
where (ValidTo < cast(@LookUpDate as datetime) or Validfrom > cast(@LookUpDate as datetime))

update #LoadResults 
set UserDescription = convert(varchar(20), cast(UserDescription as datetime), 120) 
where isdate(UserDescription) = 1 
and len(UserDescription) > 10

set nocount off

select FieldID, Occurrence, Code, DisplayCode, UserDescription, CIHIValue 
from #LoadResults 
order by SortOrder, Occurrence

return 0
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE  PROCEDURE [L_CL_ActivityRaw]
	@ActivityID as int
AS 

SELECT     CLActivityID, VolumeID, ActivityType, ActivityDateOut, ActivityTimeOut, ActivityCoderOut, ActivityDateIn, ActivityTimeIn, ActivityCoderIn, 
                      ActivityBorrower, ActivityLocation, ActivityPrevLocation, ActivityExpectedReturn, ActivityNotes, HospitalID
FROM         dbo.CL_Activity
WHERE     (CLActivityID = @ActivityID)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE PROCEDURE [L_CL_ActivityVolume]
--Delete a specific Chart Activity
	@ActivityID  as int,
    @VolumeID    as int output,
    @ActLoc       as int output,
    @PreLoc      as int output
AS 
	select top 1
        @VolumeID = VolumeID, 
        @ActLoc   = ActivityLocation, 
        @PreLoc   = ActivityPrevLocation 
    from CL_Activity 
    where CLActivityID = @ActivityID

	Return (@@rowcount)




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO




-- This is called by the Load Method of the Clinic Control
CREATE PROCEDURE [L_Clinic]
	@Key as int
AS 

SELECT * FROM CR_Demographic WHERE AbstractID = @Key
SELECT * FROM CR_Visit WHERE AbstractID = @Key
SELECT * FROM CR_VitalSign WHERE AbstractID = @Key 

SELECT * FROM CR_Diagnosis WHERE AbstractID = @Key ORDER BY DiagnosisOccurrence
SELECT * FROM CR_ProviderService WHERE AbstractID = @Key ORDER BY ProviderOccurrence
SELECT * FROM CR_Intervention WHERE AbstractID = @Key ORDER BY IntervOccurrence
SELECT * FROM CR_Supply WHERE AbstractID = @Key ORDER BY SuppliesOccurrence
SELECT * FROM CR_Prescription WHERE AbstractID = @Key ORDER BY PrescriptionOccurrence
SELECT * FROM CR_Immunization WHERE AbstractID = @Key ORDER BY Occurrence

SELECT * FROM CR_DirectBilling WHERE AbstractID = @Key 
SELECT * FROM CR_DirectBillingItems WHERE AbstractID = @Key ORDER BY OccurrenceNumber
SELECT * FROM CR_DirectBillingPayments WHERE AbstractID = @Key ORDER BY OccurrenceNumber



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


-- This is called by the Load Method of the Inpatient ICD 10 Control
CREATE   PROCEDURE [L_ClinicalPathway]
	@Key as int
AS 
	select * from [CMV_ClinicalPathway]  where [RecordID]  = @Key
	select * from [CMV_Variance] where [RecordID] = @Key  order by Occurrence

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




--This will be used to create the file.
CREATE    PROCEDURE [L_ClinicBatchLoad]
	@ProviderNumber as int
AS 
	IF @ProviderNumber = 0 
		--Do All Un-Submitted Records
		SELECT   	
			dbo.CR_Demographic.AbstractID AS [RecID], 
			dbo.CR_Demographic.BillNumber AS [AccNum],
			dbo.CR_Visit.MOHOfficeCode AS [MOH], 
			(SELECT CIHIValue FROM H_InstitutionProfile WHERE Code = dbo.CR_Visit.InstitutionNumber) AS [Inst], 
			dbo.CR_Visit.LocationCode AS [Loc],
			dbo.CR_Visit.ProviderNumber AS [ProvdN], 
			(SELECT CIHIValue FROM LU_Provider WHERE Code = dbo.CR_Visit.ProviderNumber) AS [ProvdC], 
			(SELECT CIHIValue FROM LU_CodeFile WHERE Code = dbo.CR_Visit.ProviderSpecialty) AS [ProvSpec],
			dbo.CR_Demographic.HealthCareNumber AS [HCN], 
			dbo.CR_Demographic.HCNVersion AS [HCNV], 
			(SELECT CIHIValue FROM LU_HCNProvince WHERE Code = dbo.CR_Demographic.HCNProvince) AS [HCNP], 
			dbo.CR_Demographic.BirthDate AS [DOB], 
			dbo.CR_Visit.AdmitDate AS [VDate], 
	                      	(SELECT CIHIValue FROM LU_CodeFile WHERE Code = dbo.CR_Visit.PaymentProgram) AS [PayProg], 
			(SELECT CIHIValue FROM LU_CodeFile WHERE Code = dbo.CR_Visit.Payee) AS [Payee], 
			dbo.CR_Visit.ReferenceProvider AS [RefProvd], 
			dbo.CR_Visit.InpatAdmitDate AS [ADate], 
			dbo.CR_Visit.RefLabNumber AS [RefLab], 
	                      	(SELECT CIHIValue FROM LU_YesNoAlpha WHERE Code = dbo.CR_Visit.ManualReviewInd) AS [MRI], 
			dbo.CR_Demographic.LastName AS [LName], 
			dbo.CR_Demographic.FirstName AS [FName], 
			(SELECT CIHIValue FROM LU_CodeFile WHERE Code = dbo.CR_Demographic.Gender) AS [Gender]
		FROM dbo.CR_Demographic INNER JOIN dbo.CR_Visit ON dbo.CR_Demographic.AbstractID = dbo.CR_Visit.AbstractID
		WHERE IsDeleted = 2 AND IsSubmited <> 1
	ELSE 		 
		--Only Do Un-Submitted Records for the passed Provider
		SELECT   	
			dbo.CR_Demographic.AbstractID AS [RecID], 
			dbo.CR_Demographic.BillNumber AS [AccNum],
			dbo.CR_Visit.MOHOfficeCode AS [MOH], 
			(SELECT CIHIValue FROM H_InstitutionProfile WHERE Code = dbo.CR_Visit.InstitutionNumber) AS [Inst], 
			dbo.CR_Visit.LocationCode AS [Loc],
			dbo.CR_Visit.ProviderNumber AS [ProvdN], 
			(SELECT CIHIValue FROM LU_Provider WHERE Code = dbo.CR_Visit.ProviderNumber) AS [ProvdC], 
			(SELECT CIHIValue FROM LU_CodeFile WHERE Code = dbo.CR_Visit.ProviderSpecialty) AS [ProvSpec],
			dbo.CR_Demographic.HealthCareNumber AS [HCN], 
			dbo.CR_Demographic.HCNVersion AS [HCNV], 
			(SELECT CIHIValue FROM LU_HCNProvince WHERE Code = dbo.CR_Demographic.HCNProvince) AS [HCNP], 
			dbo.CR_Demographic.BirthDate AS [DOB], 
			dbo.CR_Visit.AdmitDate AS [VDate], 
	                      	(SELECT CIHIValue FROM LU_CodeFile WHERE Code = dbo.CR_Visit.PaymentProgram) AS [PayProg], 
			(SELECT CIHIValue FROM LU_CodeFile WHERE Code = dbo.CR_Visit.Payee) AS [Payee], 
			dbo.CR_Visit.ReferenceProvider AS [RefProvd], 
			dbo.CR_Visit.InpatAdmitDate AS [ADate], 
			dbo.CR_Visit.RefLabNumber AS [RefLab], 
	                      	(SELECT CIHIValue FROM LU_YesNoAlpha WHERE Code = dbo.CR_Visit.ManualReviewInd) AS [MRI], 
			dbo.CR_Demographic.LastName AS [LName], 
			dbo.CR_Demographic.FirstName AS [FName], 
			(SELECT CIHIValue FROM LU_CodeFile WHERE Code = dbo.CR_Demographic.Gender) AS [Gender]
		FROM dbo.CR_Demographic INNER JOIN dbo.CR_Visit ON dbo.CR_Demographic.AbstractID = dbo.CR_Visit.AbstractID
		WHERE IsDeleted = 2 AND IsSubmited <> 1 AND ProviderNumber = @ProviderNumber
	RETURN 0



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO




--This will be used to create the file.
CREATE    PROCEDURE [L_ClinicBatchLoadItem]
	@AbstractID as int
AS 

	SELECT     
                      	(SELECT CIHIValue FROM LU_OhipFeeCodes WHERE Code = dbo.CR_Diagnosis.ServiceFee) AS [SCode], 
		dbo.CR_Diagnosis.ServiceSuffix AS [SSufx],
		dbo.CR_Diagnosis.ServiceFee AS [SFee], 
		dbo.CR_Diagnosis.ServiceQty AS [SQty], 
		(SELECT CIHIValue FROM LU_CodeFile WHERE Code = dbo.CR_Diagnosis.DiagnosisCode) AS [DCode]
	FROM dbo.CR_Diagnosis
	WHERE AbstractID = @AbstractID ORDER BY DiagnosisOccurrence

	RETURN 0



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




--This will be used to verify the clinic records
CREATE    PROCEDURE [L_ClinicBatchVerify]
	@ProviderNumber as int,
	@ReVerify as int,
	@RecordCount as int OUTPUT
AS 
	--This Get Only Un-Submitted Records not Validated
	IF @ReVerify <> 1 BEGIN
		IF @ProviderNumber = 0 
			SELECT dbo.CR_Demographic.AbstractID 
			FROM dbo.CR_Demographic INNER JOIN dbo.CR_Visit ON dbo.CR_Demographic.AbstractID = dbo.CR_Visit.AbstractID
			WHERE IsDeleted = 2 AND IsSubmited <> 1 AND IsValidated <> 4 
		ELSE 
			SELECT dbo.CR_Demographic.AbstractID 
			FROM dbo.CR_Demographic INNER JOIN dbo.CR_Visit ON dbo.CR_Demographic.AbstractID = dbo.CR_Visit.AbstractID
			WHERE IsDeleted = 2 AND IsSubmited <> 1 AND IsValidated <> 4 AND ProviderNumber = @ProviderNumber
	END

	--This will Return the Total Record count as well as get All Un-Submitted Records (If this is the RS needed the Program will use it).
	IF @ProviderNumber = 0 
		SELECT dbo.CR_Demographic.AbstractID 
		FROM dbo.CR_Demographic INNER JOIN dbo.CR_Visit ON dbo.CR_Demographic.AbstractID = dbo.CR_Visit.AbstractID
		WHERE IsDeleted = 2 AND IsSubmited <> 1
	ELSE 
		SELECT dbo.CR_Demographic.AbstractID 
		FROM dbo.CR_Demographic INNER JOIN dbo.CR_Visit ON dbo.CR_Demographic.AbstractID = dbo.CR_Visit.AbstractID
		WHERE IsDeleted = 2 AND IsSubmited <> 1 AND ProviderNumber = @ProviderNumber

	SET @RecordCount = @@RowCount
	RETURN 0



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [L_CMG]
	@Key as int
AS 
SELECT     
    AB_CMG.AbstractID, AB_CMG.OccurrenceNumber, AB_CMG.CMG_Year, ICD_Type, Diagnosis_Code, Diagnosis_Type, CMG, Complexity, MCC, MCC_Surg, AcuteQuartile, 
    CMG_RIW, MOH_RIW, RIW_Dollar, MOH_Dollar, CMG_ELOS, CMG_Trim, CMG_Description, CMGAgeCategory, ComorbidityLevel, 
    FlaggedIntervFactorCount, InterventionEventCount, InterventionOOHCount, InpatientRIWAtypicalCode, InpatientRILevel, 
    IntervCode, CMG_Partition as [DxIntervPartition], BatchGroupDate,
    FI_CardioversionFlag, FI_CellSaverFlag, FI_ChemotherapyFlag, FI_DialysisFlag, FI_HeartResuscitationFlag, 
    FI_MechanicalVentGreat96Hours, FI_MechanicalVentLess96Hours, FI_FeedingTubeFlag, FI_ParacentesisFlag, 
    FI_ParenteralNutritionFlag, FI_PleurocentesisFlag, FI_RadiotherapyFlag, FI_TracheostomyFlag, 
    FI_VascularAccessDdeviceFlag ,FI_EndoscopyFlag,FI_BiopsyFlag, FI_ECMOFlag,
    InpatientRITotalFactor, ComorbidityTotalFactor, 
    IntervEpisode, IntervAttStatus, IntervAttLocation, IntervAttExtent, MedicalCMG, InpatientTypicalRIW,
    HIG_Code, HIG_Weight, HIG_Description, HIG_AgeCategory, HIG_AtypicalCode, HIG_ELOS, HIG_FI_TotalCount, HIG_HomeCareFlag, 
    HIG_MaternalAgeFlag, HIG_PalliativeCareFlag, HIG_OOHFlag, HIG_SCUFlag, HIG_LongStayTrimDays, HIG_ShortStayTrimDays,
	HL_CMG, CMGCareLevel, CMGProviderService, CMGProviderServiceGroup, CMGTransplantFlag
FROM dbo.AB_CMG 
    left join dbo.AB_CMG_FI on AB_CMG.AbstractID = AB_CMG_FI.AbstractID
        and AB_CMG.OccurrenceNumber = AB_CMG_FI.OccurrenceNumber and AB_CMG.CMG_Year = AB_CMG_FI.CMG_Year
    left join dbo.AB_HIG on AB_CMG.AbstractID = AB_HIG.AbstractID
        and AB_CMG.OccurrenceNumber = AB_HIG.OccurrenceNumber and AB_CMG.CMG_Year = AB_HIG.GrouperYear
WHERE AB_CMG.AbstractID = @Key AND AB_CMG.OccurrenceNumber = 1 and AB_CMG.Diagnosis_Code is not null
    and isnull(AB_CMG.IsFixed, 0) = 0

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [L_CMG_Opt_Detail]
	(@AbstractID 	[int],
	@CMG_Year	[int])
AS 



SELECT     AbstractID, OccurrenceNumber, CMG_Year, ICD_Type, Diagnosis_Code, Diagnosis_Type, CMG, Complexity, MCC, AcuteQuartile, 
                      CMG_RIW, MOH_RIW, RIW_Dollar, MOH_Dollar, CMG_ELOS, CMG_Trim, CMG_Description
 From  AB_CMG WHERE ([AbstractID] = @AbstractID) and CMG_year = @CMG_Year AND OccurrenceNumber <> 1
Order by OccurrenceNumber




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [L_CMG_Opt_Summary]
	(@AbstractID 	[int])
AS 

SELECT     AbstractID, OccurrenceNumber, CMG_Year, ICD_Type, Diagnosis_Code, Diagnosis_Type, CMG, Complexity, MCC, AcuteQuartile, 
                      CMG_RIW, MOH_RIW, RIW_Dollar, MOH_Dollar, CMG_ELOS, CMG_Trim, CMG_Description
from AB_CMG WHERE ([AbstractID] = @AbstractID) and OccurrenceNumber = 1
Order by CMG_year desc




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [L_CMG_Years]
	@ICDType as VarChar(1)
AS 

	If @ICDType = 'C' 
		Set @ICDType = '9'

	Select CMGYears from CMG_Years where ICDType = @ICDType
	Order by CMGYears desc




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE       PROCEDURE [L_CMV_ChartInfo]
   @PatientID as int,
   @AbstractID as int,
   @LastName as varchar(40) output,
   @FirstName as varchar(35) output,
   @BirthDate as datetime output, 
   @InstNumber as int output,
   @ADate as datetime output, 
   @DDate as datetime output,
   @AssDate as datetime output
AS 
   
   declare @AppID as int 
   declare @AID as int 
		
   select @LastName = LastName, @FirstName = FirstName, @BirthDate = BirthDate from CM_CPI where (PatientID = @PatientID)

   select @AppID = AppID, @AID = AbstractID, @InstNumber = InstitutionNumber, @ADate = AdmitDate, @DDate = DischargeDate
   from AB_Main where UniversalID = @AbstractID

   if @AppID in (250)
	select @AssDate = AdmitDate from RH_ClientInfo

   if @AppID in (251, 253)	
	select @AssDate = DischargeDate from RH_ClientInfo

   if @AppID in (252)	
	select @AssDate = FollowUpDate from RH_ClientInfo

   if @AppID in (470, 471, 472, 473, 474, 475)	
	select @AssDate = A3 from CRS_Demographic where AbstractID = @AID

   if @AppID in (650, 651, 652, 653, 654)
	select @AssDate = A1 from OMHRS_SecA where AbstractID = @AID

   return 0




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO







-- This is called by the Load Method of the CPI Control
CREATE   PROCEDURE [L_CPI]
	@Key as int
AS 

SELECT * FROM CM_CPI WHERE PatientID = @Key
--SELECT * FROM CM_Notes WHERE PatientID = @Key
SELECT * FROM CM_Alias WHERE PatientID = @Key ORDER BY AliasOccurrence
SELECT * FROM CM_Alert WHERE PatientID = @Key ORDER BY AlertOccurrence
SELECT * FROM CM_ChartLink WHERE PatientID = @Key ORDER BY LinkChartOccurrence
SELECT * FROM CM_BabyChart WHERE PatientID = @Key ORDER BY BabyChartOccurrence
SELECT * FROM CM_Address WHERE PatientID = @Key ORDER BY Occurrence
SELECT * FROM CM_RiskFactors WHERE PatientID = @Key ORDER BY Occurrence
SELECT * FROM CM_LabHistory WHERE PatientID = @Key ORDER BY Occurrence
SELECT * FROM CM_FamilyHistory WHERE PatientID = @Key ORDER BY Occurrence
SELECT * FROM CM_Files WHERE PatientID = @Key ORDER BY Occurrence
select * from CM_UserDefined where PatientID = @Key
select * from CM_Terminal where PatientID = @Key -- EN-00043

select * from [CM_UDFieldsDate] where PatientID = @Key
select * from [CM_UDFieldsTime] where PatientID = @Key
select * from [CM_UDFieldsLookUp] where PatientID = @Key
select * from [CM_UDFieldsInteger] where PatientID = @Key
select * from [CM_UDFieldsText] where PatientID = @Key
select * from [CM_UDFieldsSmallText] where PatientID = @Key


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [L_CPI_Deficiency_List]
	@PatientID as Int,
	@HospID as int = 0
AS 

	select 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(Def_SlipMain.HospitalID, 0)) as [Hosp ID],
		Def_SlipMain.DefeciencyID AS [Def. ID], 
		LU_Provider.DisplayCode AS [Dr. #], 
		LU_Provider.UserDescription AS [Name], 
		(select convert(varchar(10), isnull(DischargeDate, AdmitDate), 111) from AB_Main where UniversalID = Def_SlipMain.DefAbstractID) as [Disch. Date]
	from Def_SlipMain left outer join LU_Provider on dbo.Def_SlipMain.DefDrNumber = dbo.LU_Provider.Code
	where (Def_SlipMain.DefPatientID = @PatientID) 
	and (dbo.Def_SlipMain.DefMainStatus not in (8, 11)) --<> 8) PR - 02842
	and (isnull(Def_SlipMain.HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(Def_SlipMain.HospitalID, 0) end)
	order by [Hosp ID], [Disch. Date] desc

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO







-- This is called by the Load Method of the CPI Control
CREATE      PROCEDURE [L_CPI_Volume]
	@Key as int,
	@PatientID as int,
    	@ValidFrom as datetime,
    	@ValidTo as datetime
AS 
set nocount on

--PR-01181
-- declare @ChartNumber varchar(12)
-- declare @HospitalID  int
-- 
-- if @Key > 0 and @ValidFrom = '1900/01/01'
--     select top 1 @ValidFrom = isnull(VolumeDateFrom, '1900/01/01')
--     from CM_CPI_Volume
--     where VolumeID = @Key
-- 
-- if @Key > 0 and @ValidTo = '2999/12/31'
--     select top 1 @ValidTo = isnull(VolumenDateTo, '2999/12/31')
--     from CM_CPI_Volume
--     where VolumeID = @Key
-- 
-- if @Key > 0
--     select top 1 @ChartNumber = ChartNumber, @HospitalID = isnull(isnull(v.HospitalID, cpi.HospitalID), 0)
--     from CM_CPI cpi inner join CM_CPI_Volume v on cpi.PatientID = v.PatientID
--     where cpi.PatientID = @PatientID and v.VolumeID = @Key
-- else
--     select top 1 @ChartNumber = ChartNumber, @HospitalID = HospitalID 
--     from CM_CPI 
--     where PatientID = @PatientID
-- 
select * from CM_CPI_Volume where VolumeID = @Key
-- 
-- --13272  To set the same as visit history
-- select UniversalID, VolumeID, 
-- 	(select DisplayCode from H_InstitutionProfile where Code = InstitutionNumber)  AS [Inst],
--     	(case 
-- 		when appid = 250 then 'R-1' 	-- REHAB ADMISSION
-- 	      	when appid = 251 then 'R-2'   -- REHAB Discharge
--   		when appid = 252 then 'R-3'   -- Rehab FellowUp
--   		when appid = 253 then 'R-4'   -- Rehab Interm
--   		when appid = 650 then 'M-A'   -- OMHRS ADMISSION
--   		when appid = 651 then 'M-S' 	-- OMHRS Short Stay
--   		when appid = 652 then 'M-Q' 	-- OMHRS Quarterly
--   		when appid = 653 then 'M-C' 	-- OMHRS Change
--   		when appid = 654 then 'M-D' 	-- OMHRS Discharge
--   		else (select DisplayCode FROM LU_CareType WHERE Code = right(AppType, 1))
--   	end) as [Care],
-- 	DischargeDate, 
-- 	AdmitDate,
--     	Error = 0,
--     	MISCode, AppID, AppType, AbstractID
--     	into #VolumeSelect
-- from AB_Main 
-- where (PatientID = @PatientID 
-- or (ChartNumber = @ChartNumber 
-- and (@HospitalID = 0 or isnull(HospitalID, 0) = 0 or isnull(HospitalID, 0) = @HospitalID)))
-- and AppID <> 0
-- order by DischargeDate desc, AdmitDate desc
-- 
-- -- Nacrs
-- update #VolumeSelect
-- set Care = isnull(LU_CodeFile.DisplayCode, Care)
-- from #VolumeSelect vs
--     inner join LU_MISCode on vs.MISCode = LU_MISCode.Code
--     inner join LU_CodeFile on LU_CodeFile.Code = LU_MISCode.AMCareType
-- where AppID in (301, 401)
-- 
-- -- CCRS
-- update #VolumeSelect
-- set 
-- 	[Care] = (case when vs.appid = 470 and d.AA8 = 14501 then 'L-0A' -- CCRS ADMISSION BG 
--                  when vs.appid = 471 and d.AA8 = 14500 then 'L-00' -- CCRS DEMO CHANGES 
--                  when vs.appid = 473 and d.AA8 = 14502 then 'L-01' -- CCRS ADMIT ASSESS 
--                  when vs.appid = 473 and d.AA8 = 14503 then 'L-02' -- CCRS FULL ASSESS
--                  when vs.appid = 473 and d.AA8 = 14504 then 'L-03' -- CCRS FULL ASSESS CHANGE
--                  when vs.appid = 473 and d.AA8 = 14505 then 'L-04' -- CCRS FULL ASSESS CORRECT 
--                  when vs.appid in (472, 473) and d.AA8 = 14506 then 'L-05' -- CCRS QUARTER ASSESS CORRECT 
--                  when vs.appid in (473, 472) and d.AA8 = 14511 then 'L-10' -- CCRS QUARTER ASSESS CHANGE/CORRECT 
--                  when vs.appid = 474 and d.AA8 = 14507 then 'L-06' -- CCRS DISCHARGE W/OUT RETURN  
--                  when vs.appid = 474 and d.AA8 = 14508 then 'L-07' -- CCRS DISCHARGE W/ RETURN 
--                  when vs.appid = 474 and d.AA8 = 14509 then 'L-08' -- CCRS DISCHARGE W/OUT ASSESSMENT
--                  when vs.appid = 475 and d.AA8 = 14510 then 'L-09' -- CCRS RE-ENTRY
--                  else vs.care end),
-- 	DischargeDate = 
--            	(case when vs.appid = 470 then d.AdmitDate       -- CCRS ADMISSION BG ignore Assessment Date
--                  when vs.appid = 471 then isnull(Z7, A3)    -- CCRS DEMO CHANGES 
--                  when vs.appid = 473 then A3                -- CCRS Full ASSESS: ADMIT, FULL, CHANGE, CORRECT 
--                  when vs.appid = 472 then A3                -- CCRS Quarterly ASSESS 
--                  --when vs.appid = 474 then discharge Date  -- CCRS DISCHARGE W/OUT RETURN  
--                  when vs.appid = 475 then isnull(AB1b, A3)  -- CCRS RE-ENTRY
--                  else vs.DischargeDate end)
-- from #VolumeSelect vs inner join CRS_Demographic d on vs.AbstractID = vs.AbstractID
-- where appid in (470, 471, 473, 474, 475)
-- 
-- --Rehab -- FollowUp
-- update #VolumeSelect
-- set DischargeDate = isnull(d.followupDate, vs.DischargeDate)
-- from #VolumeSelect vs inner join dbo.RH_ClientInfo d on vs.AbstractID = vs.AbstractID
-- where appid = 252
-- 
-- --OMHRS
-- update #VolumeSelect
-- set DischargeDate = isnull(d.A1, vs.DischargeDate)
-- from #VolumeSelect vs inner join dbo.OMHRS_SecA d on vs.AbstractID = vs.AbstractID
-- where appid between 650 and 654
-- 
-- --Set Error Number
-- update #VolumeSelect
-- set Error = 1
-- where VolumeID > 0 and @Key > 0 and 
--     (VolumeID <> @Key	
--         or (case when AppType in (5, 6, 9) then AdmitDate else isnull(DischargeDate, AdmitDate) end) 
--             not between @ValidFrom and @ValidTo)
-- 
-- --Delete some chart is not in list
-- delete from #VolumeSelect
-- where ((VolumeID <> @Key and VolumeID > 0) or isnull(VolumeID, 0) = 0) and
--       ((case when AppType in (5, 6, 9) then AdmitDate else isnull(DischargeDate, AdmitDate) end)
--       		not between @ValidFrom and @ValidTo )
-- 
-- select
-- 	UniversalID as [ ], VolumeID as [ ], 
-- 	[Inst], 
-- 	[Care],
-- 	DischargeDate, 
-- 	AdmitDate,
--     	Error 
-- from #VolumeSelect
-- 
-- -- --9855 Add CareType to the List
-- -- declare @C as varchar(50)
-- -- select @C = ChartNumber from CM_CPI where PatientID = @PatientID
-- -- 
-- -- -- INPATIENT/CCR/SDS
-- -- select AbstractID AS [ ], VolumeID as [  ], 
-- -- 	(select DisplayCode from H_InstitutionProfile where Code = InstitutionNumber)  AS [Inst],
-- --     (select DisplayCode FROM LU_CareType WHERE Code = right(CareType, 1)) AS [Care],
-- -- 	 DischargeDate, 
-- -- 	 AdmitDate  	
-- -- from AB_Abstract 
-- -- where ChartNumber = @C and IsDeleted = 2 and CareType <> 5
-- -- 
-- -- -- AMCARE - UNDEFINED
-- -- union
-- -- select AbstractID AS [ ], VolumeID as [  ], 
-- -- 	(select DisplayCode from H_InstitutionProfile where Code = InstitutionNumber)  AS [Inst],
-- --     (select DisplayCode FROM LU_CareType WHERE Code = right(CareType, 1)) AS [Care],
-- -- 	 DischargeDate, 
-- -- 	 AdmitDate  	
-- -- from AB_Abstract 
-- -- where ChartNumber = @C and IsDeleted = 2 and CareType = 5 
-- -- and isnull(EncounterSequence, 0) <= 1
-- -- and isnull(MISCode, 0) = 0
-- --    
-- -- -- AMCARE - EMERG CASES
-- -- union
-- -- select AbstractID AS [ ], VolumeID as [  ], 
-- -- 	(select DisplayCode from H_InstitutionProfile where Code = InstitutionNumber)  AS [Inst],
-- --     (select DisplayCode FROM LU_CareType WHERE Code = right(CareType, 1)) + '-E' AS [Care],
-- -- 	 DischargeDate, 
-- -- 	 AdmitDate  	
-- -- from AB_Abstract 
-- -- where ChartNumber = @C and IsDeleted = 2 and CareType = 5 
-- -- and isnull(EncounterSequence, 0) <= 1
-- -- and (isnull(MISCode, 0) <> 0 and MISCode not in 
-- -- (select Code from LU_MISCode where left (CIHIValue, 5) like '7%466' or CIHIValue like '7%34020' or left(CIHIValue, 7) like '7%34025' or CIHIValue like '7%34055' or left(CIHIValue, 5) like '7%260' or CIHIValue like '7%262' or left(CIHIValue, 5) like '7%265' or left(CIHIValue, 7) like '7%34066' or left(CIHIValue, 7) like '7%35066' or left(CIHIValue, 5) like '7%420' or left(CIHIValue, 7) like '7%53066' or left(CIHIValue, 7) like '7%34086' or left(CIHIValue, 7) like '7%53086' or left(CIHIValue, 7) like '7%41544'))
-- -- 
-- -- -- AMCARE - SDS CASES
-- -- union
-- -- select AbstractID AS [ ], VolumeID as [  ], 
-- -- 	(select DisplayCode from H_InstitutionProfile where Code = InstitutionNumber)  AS [Inst],
-- --     (select DisplayCode FROM LU_CareType WHERE Code = right(CareType, 1)) + '-D' AS [Care],
-- -- 	 DischargeDate, 
-- -- 	 AdmitDate  	
-- -- from AB_Abstract 
-- -- where ChartNumber = @C and IsDeleted = 2 and CareType = 5 
-- -- and isnull(EncounterSequence, 0) <= 1
-- -- and MISCode in 
-- -- (select Code from LU_MISCode where CIHIValue like '7%34020' or left(CIHIValue, 7) like '7%34025' or CIHIValue like '7%34055' or left(CIHIValue, 5) like '7%260' or CIHIValue like '7%262' or left(CIHIValue, 5) like '7%265')
-- -- 
-- -- -- AMCARE - CLINIC CASES
-- -- union
-- -- select AbstractID AS [ ], VolumeID as [  ], 
-- -- 	(select DisplayCode from H_InstitutionProfile where Code = InstitutionNumber)  AS [Inst],
-- --     (select DisplayCode FROM LU_CareType WHERE Code = right(CareType, 1)) + '-C' AS [Care],
-- -- 	 DischargeDate, 
-- -- 	 AdmitDate  	
-- -- from AB_Abstract 
-- -- where ChartNumber = @C and IsDeleted = 2 and CareType = 5 
-- -- and isnull(EncounterSequence, 0) <= 1
-- -- and MISCode in 
-- -- (select Code from LU_MISCode where left(CIHIValue, 5) like '7%466' or left(CIHIValue, 7) like '7%34066' or left(CIHIValue, 7) like '7%35066' or left(CIHIValue, 5) like '7%420' or left(CIHIValue, 7) like '7%53066' or left(CIHIValue, 7) like '7%34086' or left(CIHIValue, 7) like '7%53086' or left(CIHIValue, 7) like '7%41544')
-- -- 
-- -- order by DischargeDate desc, AdmitDate desc

set nocount off




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is called by the Load Method of the CPI Control
CREATE  PROCEDURE [L_CPI_Volume_AbstractList]
	@Key as int,
	@PatientID as int,
    	@ValidFrom as datetime,
    	@ValidTo as datetime,
	@HospitalID as int = 0
AS 
set nocount on

--PR-01181
declare @ChartNumber varchar(12)

if @Key > 0 and @ValidFrom = '1900/01/01'
    select top 1 @ValidFrom = isnull(VolumeDateFrom, '1900/01/01')
    from CM_CPI_Volume
    where VolumeID = @Key

if @Key > 0 and @ValidTo = '2999/12/31'
    select top 1 @ValidTo = isnull(VolumenDateTo, '2999/12/31')
    from CM_CPI_Volume
    where VolumeID = @Key

if @Key > 0
    select top 1 @ChartNumber = ChartNumber
    from CM_CPI cpi inner join CM_CPI_Volume v on cpi.PatientID = v.PatientID
    where cpi.PatientID = @PatientID and v.VolumeID = @Key
else
    select top 1 @ChartNumber = ChartNumber
    from CM_CPI 
    where PatientID = @PatientID

--13272  To set the same as visit history
select UniversalID, VolumeID, 
	(select DisplayCode from H_InstitutionProfile where Code = InstitutionNumber)  AS [Inst],
    	(case 
		when appid = 250 then 'R-1' 	-- REHAB ADMISSION
	      	when appid = 251 then 'R-2'   -- REHAB Discharge
  		when appid = 252 then 'R-3'   -- Rehab FellowUp
  		when appid = 253 then 'R-4'   -- Rehab Interm
  		when appid = 650 then 'M-A'   -- OMHRS ADMISSION
  		when appid = 651 then 'M-S' 	-- OMHRS Short Stay
  		when appid = 652 then 'M-Q' 	-- OMHRS Quarterly
  		when appid = 653 then 'M-C' 	-- OMHRS Change
  		when appid = 654 then 'M-D' 	-- OMHRS Discharge
  		else (select DisplayCode FROM LU_CareType WHERE Code = right(AppType, 1))
  	end) as [Care],
	DischargeDate, 
	AdmitDate,
	AdmitDate as AssessDate,
	Error = 0,
	MISCode, AppID, AppType, AbstractID,
	IsDigit = (case when HasDAS > 0 then 'Y' else '' end)   --TS-222
	into #VolumeSelect
from AB_Main 
where (PatientID = @PatientID 
or ChartNumber = @ChartNumber)
and (isnull(HospitalID, 0) = 0 or @HospitalID = case @HospitalID when 0 then 0 else isnull(HospitalID, 0) end) 
and AppID <> 0
order by DischargeDate desc, AdmitDate desc
-- where (PatientID = @PatientID 
-- or (ChartNumber = @ChartNumber 
-- and (@HospitalID = 0 or isnull(HospitalID, 0) = 0 or isnull(HospitalID, 0) = @HospitalID)))
-- and AppID <> 0
--order by DischargeDate desc, AdmitDate desc

--RM [No Ticket]
update #VolumeSelect set AssessDate = null

-- Nacrs
update #VolumeSelect
set Care = isnull(LU_CodeFile.DisplayCode, Care)
from #VolumeSelect vs
    inner join LU_MISCode on vs.MISCode = LU_MISCode.Code
    inner join LU_CodeFile on LU_CodeFile.Code = LU_MISCode.AMCareType
where AppID in (301, 401)

--select * From LU_CodeFile where Code = 14506

-- CCRS
update #VolumeSelect
set 
	[Care] = (case when vs.appid = 470 and d.AA8 = 14501 then 'L-0A' -- CCRS ADMISSION BG 
                 when vs.appid = 471 and d.AA8 = 14500 then 'L-00' -- CCRS DEMO CHANGES 
                 when vs.appid = 473 and d.AA8 = 14502 then 'L-01' -- CCRS ADMIT ASSESS 
                 when vs.appid = 473 and d.AA8 = 14503 then 'L-02' -- CCRS FULL ASSESS
                 when vs.appid = 473 and d.AA8 = 14504 then 'L-03' -- CCRS FULL ASSESS CHANGE
                 when vs.appid = 473 and d.AA8 = 14505 then 'L-04' -- CCRS FULL ASSESS CORRECT 
                 when vs.appid = 472 and d.AA8 = 14506 then 'L-05' -- CCRS QUARTER ASSESS CORRECT 
                 when vs.appid = 472 and d.AA8 = 14511 then 'L-10' -- CCRS QUARTER ASSESS CHANGE/CORRECT 
--                  when vs.appid in (472, 473) and d.AA8 = 14506 then 'L-05' -- CCRS QUARTER ASSESS CORRECT --PR-3443
--                  when vs.appid in (473, 472) and d.AA8 = 14511 then 'L-10' -- CCRS QUARTER ASSESS CHANGE/CORRECT --PR-3443
                 when vs.appid = 474 and d.AA8 = 14507 then 'L-06' -- CCRS DISCHARGE W/OUT RETURN  
                 when vs.appid = 474 and d.AA8 = 14508 then 'L-07' -- CCRS DISCHARGE W/ RETURN 
                 when vs.appid = 474 and d.AA8 = 14509 then 'L-08' -- CCRS DISCHARGE W/OUT ASSESSMENT
                 when vs.appid = 475 and d.AA8 = 14510 then 'L-09' -- CCRS RE-ENTRY
                 else vs.care end),
--	DischargeDate = 
--            	(case when vs.appid = 470 then d.AdmitDate       -- CCRS ADMISSION BG ignore Assessment Date
--                  when vs.appid = 471 then isnull(Z7, A3)    -- CCRS DEMO CHANGES 
--                  when vs.appid = 473 then A3                -- CCRS Full ASSESS: ADMIT, FULL, CHANGE, CORRECT 
--                  when vs.appid = 472 then A3                -- CCRS Quarterly ASSESS 
--                  --when vs.appid = 474 then discharge Date  -- CCRS DISCHARGE W/OUT RETURN  
--                  when vs.appid = 475 then isnull(AB1b, A3)  -- CCRS RE-ENTRY
--                  else vs.DischargeDate end)
	AssessDate = A3
from #VolumeSelect vs inner join CRS_Demographic d on vs.AbstractID = d.AbstractID --PR-02153
where appid in (470, 471, 472, 473, 474, 475) --PR-3443: Added 472 to the list

--Rehab -- FollowUp
update #VolumeSelect
--set DischargeDate = isnull(d.followupDate, vs.DischargeDate)
set AssessDate = d.followupDate
from #VolumeSelect vs inner join dbo.RH_ClientInfo d on vs.AbstractID = d.AbstractID --PR-02153
where appid = 252

--OMHRS
update #VolumeSelect
--set DischargeDate = isnull(d.A1, vs.DischargeDate)
set AssessDate = d.A1
from #VolumeSelect vs inner join dbo.OMHRS_SecA d on vs.AbstractID = d.AbstractID --PR-02153
where appid between 650 and 654

--Set Error Number
--PR-02819
-- update #VolumeSelect
-- set Error = 1
-- where VolumeID > 0 and @Key > 0 and 
--     (VolumeID <> @Key	
--         or (case when AppType in (5, 6, 9) then AdmitDate else isnull(DischargeDate, AdmitDate) end) 
--             not between @ValidFrom and @ValidTo)
--Error 3 - Attached to another volume
update #VolumeSelect set Error = 3
where VolumeID > 0 and @Key > 0 and VolumeID <> @Key	
--Error 2 - Out of Date Range
update #VolumeSelect set Error = 2
where (case when AppType in (5, 6, 9) then AdmitDate else isnull(DischargeDate, AdmitDate) end) not between @ValidFrom and @ValidTo
--Error 1 - Out of Range and Attached
update #VolumeSelect set Error = 1
where VolumeID > 0 and @Key > 0 and (VolumeID <> @Key and (case when AppType in (5, 6, 9) then AdmitDate else isnull(DischargeDate, AdmitDate) end) not between @ValidFrom and @ValidTo)

--PR-02819
-- --Delete some chart is not in list
-- delete from #VolumeSelect
-- where ((VolumeID <> @Key and VolumeID > 0) or isnull(VolumeID, 0) = 0) and
--       ((case when AppType in (5, 6, 9) then AdmitDate else isnull(DischargeDate, AdmitDate) end)
--       		not between @ValidFrom and @ValidTo )

select
	UniversalID as [ ], VolumeID as [ ], 
	[Inst], 
	[Care],
	DischargeDate, 
	AdmitDate,
	AssessDate,
    Error ,
    IsDigit	
from #VolumeSelect

-- --9855 Add CareType to the List
-- declare @C as varchar(50)
-- select @C = ChartNumber from CM_CPI where PatientID = @PatientID
-- 
-- -- INPATIENT/CCR/SDS
-- select AbstractID AS [ ], VolumeID as [  ], 
-- 	(select DisplayCode from H_InstitutionProfile where Code = InstitutionNumber)  AS [Inst],
--     (select DisplayCode FROM LU_CareType WHERE Code = right(CareType, 1)) AS [Care],
-- 	 DischargeDate, 
-- 	 AdmitDate  	
-- from AB_Abstract 
-- where ChartNumber = @C and IsDeleted = 2 and CareType <> 5
-- 
-- -- AMCARE - UNDEFINED
-- union
-- select AbstractID AS [ ], VolumeID as [  ], 
-- 	(select DisplayCode from H_InstitutionProfile where Code = InstitutionNumber)  AS [Inst],
--     (select DisplayCode FROM LU_CareType WHERE Code = right(CareType, 1)) AS [Care],
-- 	 DischargeDate, 
-- 	 AdmitDate  	
-- from AB_Abstract 
-- where ChartNumber = @C and IsDeleted = 2 and CareType = 5 
-- and isnull(EncounterSequence, 0) <= 1
-- and isnull(MISCode, 0) = 0
--    
-- -- AMCARE - EMERG CASES
-- union
-- select AbstractID AS [ ], VolumeID as [  ], 
-- 	(select DisplayCode from H_InstitutionProfile where Code = InstitutionNumber)  AS [Inst],
--     (select DisplayCode FROM LU_CareType WHERE Code = right(CareType, 1)) + '-E' AS [Care],
-- 	 DischargeDate, 
-- 	 AdmitDate  	
-- from AB_Abstract 
-- where ChartNumber = @C and IsDeleted = 2 and CareType = 5 
-- and isnull(EncounterSequence, 0) <= 1
-- and (isnull(MISCode, 0) <> 0 and MISCode not in 
-- (select Code from LU_MISCode where left (CIHIValue, 5) like '7%466' or CIHIValue like '7%34020' or left(CIHIValue, 7) like '7%34025' or CIHIValue like '7%34055' or left(CIHIValue, 5) like '7%260' or CIHIValue like '7%262' or left(CIHIValue, 5) like '7%265' or left(CIHIValue, 7) like '7%34066' or left(CIHIValue, 7) like '7%35066' or left(CIHIValue, 5) like '7%420' or left(CIHIValue, 7) like '7%53066' or left(CIHIValue, 7) like '7%34086' or left(CIHIValue, 7) like '7%53086' or left(CIHIValue, 7) like '7%41544'))
-- 
-- -- AMCARE - SDS CASES
-- union
-- select AbstractID AS [ ], VolumeID as [  ], 
-- 	(select DisplayCode from H_InstitutionProfile where Code = InstitutionNumber)  AS [Inst],
--     (select DisplayCode FROM LU_CareType WHERE Code = right(CareType, 1)) + '-D' AS [Care],
-- 	 DischargeDate, 
-- 	 AdmitDate  	
-- from AB_Abstract 
-- where ChartNumber = @C and IsDeleted = 2 and CareType = 5 
-- and isnull(EncounterSequence, 0) <= 1
-- and MISCode in 
-- (select Code from LU_MISCode where CIHIValue like '7%34020' or left(CIHIValue, 7) like '7%34025' or CIHIValue like '7%34055' or left(CIHIValue, 5) like '7%260' or CIHIValue like '7%262' or left(CIHIValue, 5) like '7%265')
-- 
-- -- AMCARE - CLINIC CASES
-- union
-- select AbstractID AS [ ], VolumeID as [  ], 
-- 	(select DisplayCode from H_InstitutionProfile where Code = InstitutionNumber)  AS [Inst],
--     (select DisplayCode FROM LU_CareType WHERE Code = right(CareType, 1)) + '-C' AS [Care],
-- 	 DischargeDate, 
-- 	 AdmitDate  	
-- from AB_Abstract 
-- where ChartNumber = @C and IsDeleted = 2 and CareType = 5 
-- and isnull(EncounterSequence, 0) <= 1
-- and MISCode in 
-- (select Code from LU_MISCode where left(CIHIValue, 5) like '7%466' or left(CIHIValue, 7) like '7%34066' or left(CIHIValue, 7) like '7%35066' or left(CIHIValue, 5) like '7%420' or left(CIHIValue, 7) like '7%53066' or left(CIHIValue, 7) like '7%34086' or left(CIHIValue, 7) like '7%53086' or left(CIHIValue, 7) like '7%41544')
-- 
-- order by DischargeDate desc, AdmitDate desc

set nocount off






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [L_CPI_Volume_FormList]
	@PatientID as Int,
	@HospID as int = 0
AS 


--ED-00344
declare @sql as varchar(5000)
declare @VolSort as int 
declare @HCnt as int 

select @HCnt = count(*) from H_HospitalProfile
-- For multi-hospitals, don't go to the hospital profile at all if we don't have a key
if @HCnt = 1 and @HospID = 0 select top 1 @VolSort = isnull(VolumeSort, 0) from H_HospitalProfile 
if @HospID > 0 select top 1 @VolSort = isnull(VolumeSort, 0) from H_HospitalProfile where HospitalID = @HospID
if isnull(@VolSort, 0) = 0 select top 1 @VolSort = isnull(VolumeSort, 0) from H_RegionProfile
if isnull(@VolSort, 0) = 0 set @VolSort = 200431

--EN-00057
set @sql = 'select VolumeID as [ ],
		(select DisplayCode from H_HospitalProfile where Code = CM_CPI_Volume.HospitalID) as [Hospital],
		(select DisplayCode from LU_CodeFile where Code = LabelPrinted) as [Label], 
		(select DisplayCode from LoanLU_VolumeType where Code = VolumeType) as [Type],
		VolumeNumber as [Volume #],
		convert(nvarchar(10), VolumeDateFrom, 111) as [Date From],
		convert(nvarchar(10), VolumenDateTo, 111) as [Date To],
		(select DisplayCode from LoanLU_Location where Code = PermLocation) as [Perm. Loc.],
		(select DisplayCode from LoanLU_Location where Code = CLCurrentLocation) as [Cur. Loc.],
		(select DisplayCode from LU_YesNoSystem where Code = SubVolume) as [Sub Vol.],
		(select top 1 link.VolumeNumber from CM_CPI_Volume Link where Link.VolumeID = CM_CPI_Volume.CLLinkedVolume) as [Link #],
		CLBoxNumber as [Box #],
		(select DisplayCode from LU_YesNoSystem where Code = CLMicroFilm) as [Micro.],
		CLMircoFilmNum as [Micro. #],
		(select DisplayCode from LU_YesNoSystem where Code = CLInpatient) as [Inpat.],
		(select DisplayCode from LU_YesNoSystem where Code = CLSDS) as [S.D.S],
		(select DisplayCode from LU_YesNoSystem where Code = CLOutpatient) as [Outpat.],
		(select DisplayCode from LU_YesNoSystem where Code = CLAmcare) as [AmCare],
		(select DisplayCode from dbo.LoanLU_DigitalIndicator where code = DigitalIndicator) as [Digital],    --TS-771
        isnull(convert(varchar(20), DestructionDate, 111), '''') as [Destruction Date]
	from CM_CPI_Volume 
	where (PatientID = ' + convert(varchar(10), @PatientID) + ')
	and (isnull(HospitalID, 0) = 0 or ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else isnull(HospitalID, 0) end) '

	--order by [Hospital], [Type], VolumenDateTo desc, VolumeNumber desc
	if isnull(@VolSort, 0) = 200432 -- Date To Asc
		set @sql = @sql + 'order by [Hospital], [Type], VolumenDateTo asc, VolumeNumber asc'
	else if isnull(@VolSort, 0) = 200433 -- Date From Desc
		set @sql = @sql + 'order by [Hospital], [Type], VolumeDateFrom desc, VolumeNumber desc'
	else if isnull(@VolSort, 0) = 200434 -- Date From Asc
		set @sql = @sql + 'order by [Hospital], [Type], VolumeDateFrom asc, VolumeNumber asc'
	else if isnull(@VolSort, 0) = 200435 -- Volume Number Desc
		set @sql = @sql + 'order by [Hospital], [Type], VolumeNumber desc, VolumenDateTo desc'
	else if isnull(@VolSort, 0) = 200436 -- Volume Number Asc
		set @sql = @sql + 'order by [Hospital], [Type], VolumeNumber asc, VolumenDateTo asc'
	else -- Date To Desc
		set @sql = @sql + 'order by [Hospital], [Type], VolumenDateTo desc, VolumeNumber desc'
			
	--print @sql
	exec (@sql)

-- --EN-00057
-- 	select VolumeID as [ ],
-- 		(select DisplayCode from H_HospitalProfile where Code = CM_CPI_Volume.HospitalID) as [Hospital],
-- 		--(select DisplayCode from LU_YesNoSystem where Code = LabelPrinted) as [Label],
-- 		(select DisplayCode from LU_CodeFile where Code = LabelPrinted) as [Label], --PR-02200
-- 		(select DisplayCode from LoanLU_VolumeType where Code = VolumeType) as [Type],
-- 		VolumeNumber as [Volume #],
-- 		convert(nvarchar(10), VolumeDateFrom, 111) as [Date From],
-- 		convert(nvarchar(10), VolumenDateTo, 111) as [Date To],
-- 		(select DisplayCode from LoanLU_Location where Code = PermLocation) as [Perm. Loc.],
-- 		(select DisplayCode from LoanLU_Location where Code = CLCurrentLocation) as [Cur. Loc.],
-- 		(select DisplayCode from LU_YesNoSystem where Code = SubVolume) as [Sub Vol.],
--         --PR - 01202. CLLinkedVolume as [Link #]
-- 		(select top 1 link.VolumeNumber from CM_CPI_Volume Link where Link.VolumeID = CM_CPI_Volume.CLLinkedVolume) as [Link #],
-- 		CLBoxNumber as [Box #],
-- 		(select DisplayCode from LU_YesNoSystem where Code = CLMicroFilm) as [Micro.],
-- 		CLMircoFilmNum as [Micro. #],
-- 		(select DisplayCode from LU_YesNoSystem where Code = CLInpatient) as [Inpat.],
-- 		(select DisplayCode from LU_YesNoSystem where Code = CLSDS) as [S.D.S],
-- 		(select DisplayCode from LU_YesNoSystem where Code = CLOutpatient) as [Outpat.],
-- 		(select DisplayCode from LU_YesNoSystem where Code = CLAmcare) as [AmCare]
-- 	from CM_CPI_Volume 
-- 	where (PatientID = @PatientID)
-- 	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end) 
-- 	order by [Hospital], [Type], VolumenDateTo desc, VolumeNumber desc
-- --	order by VolumenDateTo desc, VolumeNumber desc
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE    PROCEDURE [L_CPI_Volume_List]
	@PatientID as Int,
	@HospID as int = 0
AS 

--NP-00025: order by Type 
--ED-00344
declare @sql as varchar(5000)
declare @VolSort as int 

if @HospID = 0 select top 1 @VolSort = isnull(VolumeSort, 0) from H_HospitalProfile
if @HospID > 0 select top 1 @VolSort = isnull(VolumeSort, 0) from H_HospitalProfile where HospitalID = @HospID
if isnull(@VolSort, 0) = 0 select top 1 @VolSort = isnull(VolumeSort, 0) from H_RegionProfile
if isnull(@VolSort, 0) = 0 set @VolSort = 200431

set @sql = 'select  VolumeID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CM_CPI_Volume.HospitalID, 0)) as [Hosp ID],
		VolumeNumber as Volume, 
		(select DisplayCode from dbo.LoanLU_VolumeType where Code = VolumeType) as [Type], 
		(select UserDescription from dbo.LoanLU_Location where Code = PermLocation) as [Perm Location], 
		(select UserDescription from dbo.LoanLU_Location where Code = CLCurrentLocation) as [Current Location],
		DigitalIndicator,    --TS-222
        isnull(convert(varchar(20), DestructionDate, 111), '''') as [Destruction Date]
	from CM_CPI_Volume 
	where (PatientID = ' + convert(varchar(10), @PatientID) + ')
	and (isnull(HospitalID, 0) = 0 or ' + convert(varchar(10), @HospID) + ' = case ' + convert(varchar(10), @HospID) + ' when 0 then 0 else isnull(HospitalID, 0) end) '

	--order by [Hosp ID], [Type], VolumenDateTo desc, VolumeNumber desc
	if isnull(@VolSort, 0) = 200432 -- Date To Asc
		set @sql = @sql + 'order by [Hosp ID], [Type], VolumenDateTo asc, VolumeNumber asc'
	else if isnull(@VolSort, 0) = 200433 -- Date From Desc
		set @sql = @sql + 'order by [Hosp ID], [Type], VolumeDateFrom desc, VolumeNumber desc'
	else if isnull(@VolSort, 0) = 200434 -- Date From Asc
		set @sql = @sql + 'order by [Hosp ID], [Type], VolumeDateFrom asc, VolumeNumber asc'
	else if isnull(@VolSort, 0) = 200435 -- Volume Number Desc
		set @sql = @sql + 'order by [Hosp ID], [Type], VolumeNumber desc, VolumenDateTo desc'
	else if isnull(@VolSort, 0) = 200436 -- Volume Number Asc
		set @sql = @sql + 'order by [Hosp ID], [Type], VolumeNumber asc, VolumenDateTo asc'
	else -- Date To Desc
		set @sql = @sql + 'order by [Hosp ID], [Type], VolumenDateTo desc, VolumeNumber desc'
			
	--print @sql
	exec (@sql)

-- --NP-00025: order by Type 
-- 	select  VolumeID, 
-- 		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CM_CPI_Volume.HospitalID, 0)) as [Hosp ID],
-- 		VolumeNumber as Volume, 
-- 		(select DisplayCode from dbo.LoanLU_VolumeType where Code = VolumeType) as [Type], 
-- 		(select UserDescription from dbo.LoanLU_Location where Code = PermLocation) as [Perm Location], 
-- 		(select UserDescription from dbo.LoanLU_Location where Code = CLCurrentLocation) as [Current Location]
-- 	from CM_CPI_Volume 
-- 	where (PatientID = @PatientID)
-- 	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end) 
-- 	order by [Hosp ID], [Type], VolumenDateTo desc, VolumeNumber desc

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




-- This is called by the Load Method of the CPI Control
create PROCEDURE [L_CPI_VolumeAbstracts]
	@VolumeID as int
AS 
--EN-00106
set nocount on

--13272  To set the same as visit history
select UniversalID, VolumeID, 
	(select DisplayCode from H_InstitutionProfile where Code = InstitutionNumber)  AS [Inst],
	(case when appid = 250 then 'R-1' 	-- REHAB ADMISSION
		when appid = 251 then 'R-2'   -- REHAB Discharge
          	when appid = 252 then 'R-3'   -- Rehab FellowUp
          	when appid = 253 then 'R-4'   -- Rehab Interm
          	when appid = 650 then 'M-A'   -- OMHRS ADMISSION
          	when appid = 651 then 'M-S' 	-- OMHRS Short Stay
          	when appid = 652 then 'M-Q' 	-- OMHRS Quarterly
          	when appid = 653 then 'M-C' 	-- OMHRS Change
          	when appid = 654 then 'M-D' 	-- OMHRS Discharge
          	else (select DisplayCode FROM LU_CareType WHERE Code = right(AppType, 1))
          end) AS [Care],
	DischargeDate, 
	AdmitDate,
    	MISCode, 
	AppID, 
	AppType, 
	AbstractID
into #VolumeSelect
from AB_Main 
where VolumeID = @VolumeID and AppID <> 0
order by DischargeDate desc, AdmitDate desc

-- NACRS
update #VolumeSelect
set Care = isnull(LU_CodeFile.DisplayCode, Care)
from #VolumeSelect vs 
inner join LU_MISCode on vs.MISCode = LU_MISCode.Code
inner join LU_CodeFile on LU_CodeFile.Code = LU_MISCode.AMCareType
where AppID in (301, 401)

-- CCRS
update #VolumeSelect
set [Care] = (case when vs.appid = 470 and d.AA8 = 14501 then 'L-0A' -- CCRS ADMISSION BG 
                 when vs.appid = 471 and d.AA8 = 14500 then 'L-00' -- CCRS DEMO CHANGES 
                 when vs.appid = 473 and d.AA8 = 14502 then 'L-01' -- CCRS ADMIT ASSESS 
                 when vs.appid = 473 and d.AA8 = 14503 then 'L-02' -- CCRS FULL ASSESS
                 when vs.appid = 473 and d.AA8 = 14504 then 'L-03' -- CCRS FULL ASSESS CHANGE
                 when vs.appid = 473 and d.AA8 = 14505 then 'L-04' -- CCRS FULL ASSESS CORRECT 
                 when vs.appid in (472, 473) and d.AA8 = 14506 then 'L-05' -- CCRS QUARTER ASSESS CORRECT 
                 when vs.appid in (473, 472) and d.AA8 = 14511 then 'L-10' -- CCRS QUARTER ASSESS CHANGE/CORRECT 
                 when vs.appid = 474 and d.AA8 = 14507 then 'L-06' -- CCRS DISCHARGE W/OUT RETURN  
                 when vs.appid = 474 and d.AA8 = 14508 then 'L-07' -- CCRS DISCHARGE W/ RETURN 
                 when vs.appid = 474 and d.AA8 = 14509 then 'L-08' -- CCRS DISCHARGE W/OUT ASSESSMENT
                 when vs.appid = 475 and d.AA8 = 14510 then 'L-09' -- CCRS RE-ENTRY
                 else vs.care end),
    DischargeDate = 
           (case when vs.appid = 470 then d.AdmitDate       -- CCRS ADMISSION BG ignore Assessment Date
                 when vs.appid = 471 then isnull(Z7, A3)    -- CCRS DEMO CHANGES 
                 when vs.appid = 473 then A3                -- CCRS Full ASSESS: ADMIT, FULL, CHANGE, CORRECT 
                 when vs.appid = 472 then A3                -- CCRS Quarterly ASSESS 
                 --when vs.appid = 474 then discharge Date  -- CCRS DISCHARGE W/OUT RETURN  
                 when vs.appid = 475 then isnull(AB1b, A3)  -- CCRS RE-ENTRY
                 else vs.DischargeDate end)
from #VolumeSelect vs
inner join CRS_Demographic d on vs.AbstractID = vs.AbstractID
where appid in (470, 471, 473, 474, 475)

--Rehab -- FollowUp
update #VolumeSelect
set DischargeDate = isnull(d.followupDate, vs.DischargeDate)
from #VolumeSelect vs 
inner join dbo.RH_ClientInfo d on vs.AbstractID = vs.AbstractID
where appid = 252

--OMHRS
update #VolumeSelect
set DischargeDate = isnull(d.A1, vs.DischargeDate)
from #VolumeSelect vs 
inner join dbo.OMHRS_SecA d on vs.AbstractID = vs.AbstractID
where appid between 650 and 654

select 	UniversalID as [ ], 
	VolumeID as [ ], 
	[Inst], 
	[Care],
	DischargeDate, 
	AdmitDate
from #VolumeSelect

set nocount off



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




-- This is called by the Load Method of the CPI Control
CREATE    PROCEDURE [L_CPI_VolumeOrphans]
	@HospitalID as int, --PR-01877
	@PatientID as int
AS 
--EN-00106
set nocount on

declare @ChartNumber varchar(12)
--declare @HospitalID  int --PR-01877

select top 1 	@ChartNumber = ChartNumber --, --PR-01877
		--@HospitalID = HospitalID --PR-01877
from CM_CPI 
where PatientID = @PatientID

select 	[VolumeID],
	[VolumeNumber],
	[VolumeType], 
	[VolumeDateFrom],
	[VolumenDateTo]
from CM_CPI_Volume 
where PatientID = @PatientID
and (@HospitalID = 0 or isnull(HospitalID, 0) = 0 or isnull(HospitalID, 0) = @HospitalID)

--13272  To set the same as visit history
select UniversalID, VolumeID, 
	(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_Main.HospitalID, 0)) as [Hosp],
	(select DisplayCode from H_InstitutionProfile where Code = InstitutionNumber)  AS [Inst],
	(case when appid = 250 then 'R-1' 	-- REHAB ADMISSION
		when appid = 251 then 'R-2'   -- REHAB Discharge
          	when appid = 252 then 'R-3'   -- Rehab FellowUp
          	when appid = 253 then 'R-4'   -- Rehab Interm
          	when appid = 650 then 'M-A'   -- OMHRS ADMISSION
          	when appid = 651 then 'M-S' 	-- OMHRS Short Stay
          	when appid = 652 then 'M-Q' 	-- OMHRS Quarterly
          	when appid = 653 then 'M-C' 	-- OMHRS Change
          	when appid = 654 then 'M-D' 	-- OMHRS Discharge
          	else (select DisplayCode FROM LU_CareType WHERE Code = right(AppType, 1))
          end) AS [Care],
	DischargeDate, 
	AdmitDate,
    	MISCode, 
	AppID, 
	AppType, 
	AbstractID
into #VolumeSelect
from AB_Main 
where PatientID = @PatientID 
-- 	or (ChartNumber = @ChartNumber 
-- 	and (@HospitalID = 0 or isnull(HospitalID, 0) = 0 or isnull(HospitalID, 0) = @HospitalID)))
    	and AppID <> 0
 	and (@HospitalID = 0 or isnull(HospitalID, 0) = 0 or isnull(HospitalID, 0) = @HospitalID) --PR-01877
order by DischargeDate desc, AdmitDate desc

-- NACRS
update #VolumeSelect
set Care = isnull(LU_CodeFile.DisplayCode, Care)
from #VolumeSelect vs 
inner join LU_MISCode on vs.MISCode = LU_MISCode.Code
inner join LU_CodeFile on LU_CodeFile.Code = LU_MISCode.AMCareType
where AppID in (301, 401)

-- CCRS
update #VolumeSelect
set [Care] = (case when vs.appid = 470 and d.AA8 = 14501 then 'L-0A' -- CCRS ADMISSION BG 
                 when vs.appid = 471 and d.AA8 = 14500 then 'L-00' -- CCRS DEMO CHANGES 
                 when vs.appid = 473 and d.AA8 = 14502 then 'L-01' -- CCRS ADMIT ASSESS 
                 when vs.appid = 473 and d.AA8 = 14503 then 'L-02' -- CCRS FULL ASSESS
                 when vs.appid = 473 and d.AA8 = 14504 then 'L-03' -- CCRS FULL ASSESS CHANGE
                 when vs.appid = 473 and d.AA8 = 14505 then 'L-04' -- CCRS FULL ASSESS CORRECT 
                 when vs.appid in (472, 473) and d.AA8 = 14506 then 'L-05' -- CCRS QUARTER ASSESS CORRECT 
                 when vs.appid in (473, 472) and d.AA8 = 14511 then 'L-10' -- CCRS QUARTER ASSESS CHANGE/CORRECT 
                 when vs.appid = 474 and d.AA8 = 14507 then 'L-06' -- CCRS DISCHARGE W/OUT RETURN  
                 when vs.appid = 474 and d.AA8 = 14508 then 'L-07' -- CCRS DISCHARGE W/ RETURN 
                 when vs.appid = 474 and d.AA8 = 14509 then 'L-08' -- CCRS DISCHARGE W/OUT ASSESSMENT
                 when vs.appid = 475 and d.AA8 = 14510 then 'L-09' -- CCRS RE-ENTRY
                 else vs.care end),
    DischargeDate = 
           (case when vs.appid = 470 then d.AdmitDate       -- CCRS ADMISSION BG ignore Assessment Date
                 when vs.appid = 471 then isnull(Z7, A3)    -- CCRS DEMO CHANGES 
                 when vs.appid = 473 then A3                -- CCRS Full ASSESS: ADMIT, FULL, CHANGE, CORRECT 
                 when vs.appid = 472 then A3                -- CCRS Quarterly ASSESS 
                 --when vs.appid = 474 then discharge Date  -- CCRS DISCHARGE W/OUT RETURN  
                 when vs.appid = 475 then isnull(AB1b, A3)  -- CCRS RE-ENTRY
                 else vs.DischargeDate end)
from #VolumeSelect vs
inner join CRS_Demographic d on vs.AbstractID = vs.AbstractID
where appid in (470, 471, 473, 474, 475)

--Rehab -- FollowUp
update #VolumeSelect
set DischargeDate = isnull(d.followupDate, vs.DischargeDate)
from #VolumeSelect vs 
inner join dbo.RH_ClientInfo d on vs.AbstractID = vs.AbstractID
where appid = 252

--OMHRS
update #VolumeSelect
set DischargeDate = isnull(d.A1, vs.DischargeDate)
from #VolumeSelect vs 
inner join dbo.OMHRS_SecA d on vs.AbstractID = vs.AbstractID
where appid between 650 and 654

--Delete where there is a Volume linked.
delete from #VolumeSelect where isnull(VolumeID, 0) <> 0

select 	UniversalID as [ ], 
	VolumeID as [ ], 
	[Hosp],
	[Inst], 
	[Care],
	DischargeDate, 
	AdmitDate
from #VolumeSelect

set nocount off



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This is called by the Load Method of the Control File Details Sub-Form
CREATE   PROCEDURE [L_CtrlDetail]
	@AppID as int, 
	@UserID as int,
	@FKey as int
AS 

	SELECT dbo.U_Fields.FieldID, dbo.U_Fields.InHouseDesc, dbo.U_Fields.SystemName, dbo.U_Fields.PropertyName, 
		dbo.U_Fields.FieldAccess, dbo.U_Fields.IsGroup, dbo.U_UsersFields.AppID, dbo.U_UsersFields.RoleID, dbo.U_UsersFields.UserID, 
		dbo.U_UsersFields.SortOrder, dbo.U_UsersFields.GroupID, dbo.U_UsersFields.MultipleIndex, dbo.U_UsersFields.MandatoryStatus, 
		dbo.U_UsersFields.Needed, dbo.U_UsersFields.NeedForUserDef, dbo.U_UsersFields.FieldSize, dbo.U_UsersFields.DataType, dbo.U_UsersFields.SubAppID, dbo.U_UsersFields.LookUpTable, 
		dbo.U_UsersFields.CIHI_ID, dbo.U_UsersFields.Header_CIHI_English, dbo.U_UsersFields.Header_CIHI_French, 
		dbo.U_UsersFields.Header_CIHI_Spanish, dbo.U_UsersFields.Header_User, dbo.U_UsersFields.FieldEnabled, dbo.U_UsersFields.FieldVisible, 
		dbo.U_UsersFields.DefaultValue
	FROM dbo.U_Fields INNER JOIN
		dbo.U_UsersFields ON dbo.U_Fields.FieldID = dbo.U_UsersFields.FieldID
	WHERE (dbo.U_Fields.FieldID = @FKey) AND (dbo.U_UsersFields.AppID = @AppID) AND (dbo.U_UsersFields.UserID = @UserID)
	Return 0




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- This is called by the Load Method of the Control File Maint. Control
CREATE PROCEDURE [L_CtrlMain]
    @UserID	int = 0,
    @AppID	int = 0
AS 
	SELECT dbo.U_Fields.FieldID, 
		dbo.U_Fields.InHouseDesc, 
		dbo.U_Fields.SystemName, 
		dbo.U_Fields.PropertyName, 
		0 AS FieldAccess,
		dbo.U_Fields.IsGroup, 
		dbo.U_UsersFields.AppID, 
		dbo.U_UsersFields.RoleID, 
		dbo.U_UsersFields.UserID, 
		dbo.U_UsersFields.SortOrder, 
		dbo.U_UsersFields.GroupID, 
		0 AS MultipleIndex, 
		dbo.U_UsersFields.MandatoryStatus, 
		dbo.U_UsersFields.Needed, 
		dbo.U_UsersFields.NeedForUserDef,
		dbo.U_UsersFields.FieldSize, 
		(CASE WHEN dbo.U_UsersFields.DataType = 100000 THEN dbo.U_UsersFields.DataType ELSE 1200 END) AS DataType, 
		1201 AS SubAppID, 
		LookUpTable = (case when isnull(LookUpTable, '') <> '' then LookUpTable 
                            else (case when dbo.U_UsersFields.DataType = 60 then 'ICD_DiagFile10'
                                       when dbo.U_UsersFields.DataType = 61 then 'ICD_ProcFile10'
                                  end)
                       end), --PR - 04066
		dbo.U_UsersFields.CIHI_ID, 
		dbo.U_UsersFields.Header_CIHI_English, 
		dbo.U_UsersFields.Header_CIHI_French, 
		dbo.U_UsersFields.Header_CIHI_Spanish, 
		dbo.U_UsersFields.Header_User, 
		dbo.U_UsersFields.UNoteCode, 
		1 AS FieldEnabled, 
		1 AS FieldVisible, 
		dbo.U_UsersFields.DefaultValue,
		dbo.U_UsersFields.ParamProcID,
		dbo.U_UsersFields.ParamOrder,
		dbo.U_UsersFields.ParamName,
		dbo.U_UsersFields.ParamDataType,
		dbo.U_UsersFields.ParamSize
	FROM dbo.U_Fields 
	INNER JOIN dbo.U_UsersFields 
	ON dbo.U_Fields.FieldID = dbo.U_UsersFields.FieldID
	WHERE dbo.U_Fields.FieldAccess <> 1
	AND (dbo.U_UsersFields.AppID = @AppID) 
	AND (dbo.U_UsersFields.UserID = @UserID)
	ORDER BY dbo.U_UsersFields.SortOrder
	
	Return 0



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [L_DBUpdateHistory]
	@HospID as int = 0
AS
	select 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(D.HospitalID, 0)) as [Hosp ID],
		UpdateName 		as [Update Name], 
		UpdateDescription 	as [Update Information], 
		UserDescription 		as [User Updating], 
		convert(varchar(20), StartTime, 120)  	as Started, 
		convert(varchar(20), EndTime, 120) 	as Ended, 
		WRVersion 		as Version, 
		ExecPath 		as [Execution Path]
	from M_DBULogging D left outer join U_Users on D.UserID = U_Users.Code
	--where (isnull(D.HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(D.HospitalID, 0) end)
	order by StartTime DESC
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [L_Def_ChartInfo]
   @PatientID as int,
   @AbstractID as int,
   @Colour as int output,
   @Volume as int output,
   @LastName as varchar(40) output,
   @FirstName as varchar(35) output,
   @BirthDate as datetime output, 
   @InstNumber as int output,
   @SiteNumber as int output
AS 
   declare @DDate as datetime
   declare @AppID as int 
   --EN - 00183
   declare @HospID int

   if @AbstractID = 0 
           set @Colour = (select isnull(min(code), 1) from DefLU_DocColourCode where code not in (select DefColour from Def_SlipMain where (DefPatientID = @PatientID and DefAbstractID = 0))) 
   else
           set @Colour = (select isnull(min(code), 1) from DefLU_DocColourCode where code not in (select DefColour from Def_SlipMain where (DefAbstractID = @AbstractID))) 

   select @LastName = LastName, @FirstName = FirstName, @BirthDate = BirthDate, @HospID = HospitalID
    from CM_CPI where (PatientID = @PatientID)

-- PR-00616
--    select @Volume = AB.VolumeID,              
--             @InstNumber = M.InstitutionNumber,
--             @SiteNumber = AB.SiteNumber,
--             @DDate = isnull(M.DischargeDate, M.AdmitDate)
--    from dbo.AB_Abstract AB right join AB_Main M
--         on AB.AbstractID = M.AbstractID
--    where (M.UniversalID = @AbstractID)

-- PR-00616
   select 
	    @AppID = AppID,
	    @Volume = VolumeID,              
        @InstNumber = InstitutionNumber,
        @DDate = isnull(DischargeDate, AdmitDate),
        @HospID = isnull(@HospID, HospitalID)
   from AB_Main 
   where (UniversalID = @AbstractID)

   set @SiteNumber = 0
   if @AppID in (100, 101, 102, 200, 201, 202, 301, 401) 
	select 
	    	@SiteNumber = SiteNumber
	from AB_Abstract 
	where (AbstractID = @AbstractID)

--   from dbo.AB_Abstract where (AbstractID = @AbstractID)
   --11580 Some chart link invalid volumeid
   if isnull(@Volume, 0) <> 0 
   begin
       if not exists (select top 1 PatientID from CM_CPI_volume where patientid = @PatientID and VolumeID = @Volume)
        set @Volume = 0        
   end
   --If a Volume ID is not found, use the first one found in the CPI for the Date Range.
   if isnull(@Volume, 0) = 0
           set @Volume = (select top 1 VolumeID from CM_CPI_Volume 
            where (PatientID = @PatientID) and (VolumeDatefrom >= @DDate) AND (VolumenDateTo <= @DDate)
            and (ISNULL(HospitalID, 0) = 0 OR @HospID = (case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end))
            order by VolumeDateFrom desc, VolumenDateTo desc
            )

   --If a Volume ID is still not found, just use the first one in the CPI.
   if isnull(@Volume, 0) = 0
       set @Volume = (select top 1 VolumeID from dbo.CM_CPI_Volume 
        where (PatientID = @PatientID)
        and (ISNULL(HospitalID, 0) = 0 OR @HospID = (case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end))
        order by VolumeDateFrom desc, VolumenDateTo desc
        )
   
   return 0



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO


--No one call this procedure
CREATE  PROCEDURE [L_Def_Main]
	@DefID as int
AS 

	SELECT dbo.Def_SlipMain.DefeciencyID, dbo.Def_SlipMain.DefAbstractID, dbo.Def_SlipMain.DefVolumeID, dbo.Def_SlipMain.DefDrNumber, 
		dbo.Def_SlipMain.DefColour, dbo.Def_SlipMain.DefHoldStartDate, dbo.Def_SlipMain.DefHoldEndDate, dbo.Def_SlipMain.DefMainStatus, 
		dbo.Def_SlipMain.DefMainNote, dbo.CM_CPI_Volume.PatientID
	FROM dbo.Def_SlipMain LEFT OUTER JOIN
		dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID
	WHERE (DefeciencyID = @DefID)





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO


-- This is called by the Load Method of the Chart Deficiency Control
CREATE PROCEDURE [L_Deficiency]
	@Key as int
AS 
--EN-00183 
-- SELECT * FROM Def_SlipMain  WHERE DefeciencyID = @Key
-- SELECT * FROM Def_Activity WHERE HeaderDefID = @Key ORDER BY DefOccurrence
SELECT * FROM Def_SlipMain  WHERE DefID = @Key
SELECT * FROM Def_Activity WHERE DefID = @Key ORDER BY DefOccurrence


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE  PROCEDURE [L_Deficiency_Activities]
	@PatientID as int,
	@HospID as int = 0
AS 

select 
	DA.DefeciencyID as [ ],
	DA.DefID as [ ],		
	(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(m.HospitalID, 0)) as [Hosp ID],
	(select VolumeNumber from CM_CPI_Volume where VolumeID = DefVolumeID) as [Volume],
	(select (select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) from CM_CPI_Volume where VolumeID = DefVolumeID) as [Volume Type], 
	DA.DefeciencyID as [Header Reference ID],
	(select convert(varchar(10), (case when AppID in (201, 101, 100, 200, 202, 102) then DischargeDate else AdmitDate end), 111) from AB_Main where UniversalID = m.DefAbstractID)  as [Visit Date],  
	(select DisplayCode from DefLU_DeficiencyCode where Code = DefCode) as [Def Code],
	(select UserDescription from DefLU_DeficiencyCode where Code = DefCode) as [Def Code Desc],
	(select DisplayCode from DefLU_ChartStatus where Code = DefStatus) as [Status],
	(select UserDescription from DefLU_ChartStatus where Code = DefStatus) as [Status Desc],
	(select DisplayCode from LU_Provider where Code = DefDrNumber) as [Provider],
	(select UserDescription from LU_Provider where Code = DefDrNumber) as [Provider Desc],
	(select DisplayCode from DefLU_DocColourCode where Code = DefColour) as [Def Colour], 
	(select UserDescription from DefLU_DocColourCode where Code = m.DefColour) as [Def Colour Desc],
	convert(varchar(10), DA.DefStartDate, 111) AS [Start Date], 
	convert(varchar(10), DA.DefEndDate, 111) AS [End Date],
	DA.DefDays as [Deficiency Days] -- PR - 01247
from Def_Activity DA
inner join Def_SlipMain m on DA.DefID = m.DefID
where m.DefPatientID = @PatientID
and (isnull(m.HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(m.HospitalID, 0) end)
order by [Hosp ID], [Volume] desc, DA.DefeciencyID desc, [Visit Date] desc
--EN-00183
--where DA.DefID in (select DefID from Def_SlipMain where DefPatientID = @PatientID)
--where DA.HeaderDefID in (select DefeciencyID from Def_SlipMain where DefPatientID = @PatientID)


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE  PROCEDURE [L_DefSlipSummary]
	@DefID as int
AS 

	Declare @DefMax as int
	Set @DefMax = @DefID + 100

	SELECT	dbo.Def_Activity.DefeciencyID AS [Deficiancy ID], dbo.DefLU_DeficiencyCode.DisplayCode AS [Deficiency Code], 
		dbo.DefLU_DeficiencyType.DisplayCode AS [Deficiancy Type], dbo.Def_Activity.DefDays AS Days, 
		dbo.DefLU_ChartStatus.DisplayCode AS Status
	FROM dbo.Def_Activity LEFT OUTER JOIN
		dbo.DefLU_ChartStatus ON dbo.Def_Activity.DefStatus = dbo.DefLU_ChartStatus.Code LEFT OUTER JOIN
		dbo.DefLU_DeficiencyType ON dbo.Def_Activity.DefCodeType = dbo.DefLU_DeficiencyType.Code LEFT OUTER JOIN
		dbo.DefLU_DeficiencyCode ON dbo.Def_Activity.DefCode = dbo.DefLU_DeficiencyCode.Code
	WHERE (dbo.Def_Activity.DefeciencyID > @DefID AND dbo.Def_Activity.DefeciencyID < @DefMax)
	ORDER BY DefeciencyID




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--L_DisplayFields 4, 1100, 0
-- This is called by the Load Display Method of the CDisplay Object (For Filling Fields Collection).
CREATE      PROCEDURE [L_DisplayFields] 
    @UserID	int = 0,
    @AppID	int = 0,
    @MultiIndex	int = 0
AS 

declare @PermitCCM int
declare @PermitOMHRS10 int
declare @PermitRehab10 int
declare @PermitCCR10 int
declare @PermitInPat10 int
declare @PermitSDS10 int
declare @PermitAmcare10 int
declare @PermitClinic int
declare @PermitBilling int
declare @PermitScheduler int
declare @PermitCPI int
declare @PermitChartLoc int
declare @PermitChartDef int
declare @PermitTranscription int
declare @PermitMED_DSS int
declare @PermitROI int
declare @PermitCCR int
declare @PermitInPat int
declare @PermitSDS int
declare @PermitAmcare int
declare @PermitCareMap int
declare @PermitCCRS10 int
declare @PermitLookUpMaint int
declare @PermitVisitHist int
declare @PermitCJRR int 
declare @PermitReportGen int
declare @PermitHospProf int
declare @PermitInstProf int
declare @PermitProvdrMaint int
declare @PermitRegionProf int


If @Appid = 1100
Begin
	Declare @SelString as VarChar(1000)
	Declare @SQL as VarChar(1000)
	Declare @FieldIDs as varchar(1000)
	
	Set Nocount on
    --PR - 06314
    select top 1 @PermitCCM = PermitCCM, @PermitOMHRS10 = PermitOMHRS10,  @PermitRehab10 = PermitRehab10,  @PermitCCR10 = PermitCCR10,
        @PermitInPat10 = PermitInPat10,  @PermitSDS10 = PermitSDS10,  @PermitAmcare10 = PermitAmcare10, @PermitClinic = PermitClinic,
        @PermitBilling = PermitBilling, @PermitScheduler = PermitScheduler, @PermitCPI = PermitCPI, @PermitChartLoc = PermitChartLoc,
        @PermitChartDef = PermitChartDef, @PermitTranscription = PermitTranscription, @PermitMED_DSS = PermitMED_DSS,
        @PermitROI = PermitROI, @PermitCCR = PermitCCR, @PermitInPat = PermitInPat, @PermitSDS = PermitSDS, @PermitAmcare = PermitAmcare,
        @PermitCareMap = PermitCareMap, @PermitCCRS10 = PermitCCRS10, @PermitLookUpMaint=  PermitLookUpMaint,
        @PermitVisitHist = PermitVisitHist, @PermitCJRR = PermitCJRR, @PermitReportGen = PermitReportGen,
		--2.x-0386
		@PermitHospProf = PermitHospProf, @PermitInstProf = PermitInstProf, @PermitProvdrMaint = PermitProvdrMaint,
		@PermitRegionProf = PermitRegionProf
    from u_users
    where code = @Userid

	
	set @SelString = '' --PR - 06314 '41, '
	Set @FieldIDs  = '' --PR - 06314
    if @PermitCCM > 1    -- (SELECT PermitCCM FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 675, '
    if @PermitOMHRS10 > 1 -- (SELECT PermitOMHRS10 FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 650, 651, 652, 653, 654,'
	if @PermitRehab10 > 1 --(SELECT PermitRehab10 FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 250, 251, 252,'
	if @PermitCCR10 > 1 --(SELECT PermitCCR10 FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 200,'
	if @PermitInPat10 > 1 --(SELECT PermitInPat10 FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 201,'
	if @PermitSDS10 > 1 --(SELECT PermitSDS10 FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 202,'
	if @PermitAmcare10 > 1 --(SELECT PermitAmcare10 FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 401,'
	if @PermitClinic > 1 --(SELECT PermitClinic FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 451,'
	if @PermitBilling > 1 --(SELECT PermitBilling FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 725,'
	if @PermitScheduler > 1 --(SELECT PermitScheduler FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 500,'
	if @PermitCPI > 1 --(SELECT PermitCPI FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 0,'   --' 0,1,'
	if @PermitChartLoc > 1 --(SELECT PermitChartLoc FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 1,10,11,'
	if @PermitChartDef > 1 --(SELECT PermitChartDef FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 15,'
	if @PermitTranscription > 1 --(SELECT PermitTranscription FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 20,'
	if @PermitMED_DSS > 1 --(SELECT PermitMED_DSS FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 36,'
	if @PermitROI > 1 --(SELECT PermitROI FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 30,'
	if @PermitCCR > 1 --(SELECT PermitCCR FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 100,'
	if @PermitInPat > 1 --(SELECT PermitInPat FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 101,'
	if @PermitSDS > 1 --(SELECT PermitSDS FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 102,'
	if @PermitAmcare > 1 --(SELECT PermitAmcare FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 301,'
	if @PermitCareMap > 1 --(SELECT PermitCareMap FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 550,'
	if @PermitCCRS10 > 1 --(SELECT PermitCCRS10 FROM U_Users where code = @Userid) > 1
		Set @SelString = @SelString + ' 470, 471, 472, 473, 474, 475, 476, '
	--2.x-0386
	if @PermitHospProf > 1
		Set @SelString = @SelString + ' 1000, '
	if @PermitInstProf > 1
		Set @SelString = @SelString + ' 1001, '
	if @PermitRegionProf > 1
		Set @SelString = @SelString + ' 1003, '
	if @PermitProvdrMaint > 1
		Set @SelString = @SelString + ' 1104, '


    --PR - 06314
	--if @PermitLookUpMaint > 1 --(SELECT PermitLookUpMaint FROM U_Users where code = @Userid) > 1
	--	Set @SelString = @SelString + ' 1101, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 1117, 1118, 1119, 1120, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1129, 1130, 1131, 1140, 1141, '
	if @PermitVisitHist > 1 --(SELECT PermitVisitHist FROM U_Users where code = @Userid) > 1   --Add 2010/04/12 When testing LU_PatientType, 
		Set @SelString = @SelString + ' 3,'		
	if @PermitCJRR > 1 --(SELECT PermitCJRR from U_Users where code = @Userid) > 1 --SP-01071
		Set @SelString = @SelString + ' 40000, 40001, '		
    --PR - 06314
    if @PermitReportGen > 1 
        Set @FieldIDs = @FieldIDs + ' 10702, '
    if @PermitCCM > 1 or @PermitOMHRS10 > 1 or @PermitCCR10 > 1 or @PermitInPat10 > 1 or @PermitSDS10 > 1 or 
       @PermitAmcare10 > 1 or @PermitClinic > 1 or @PermitCCRS10 > 1 or @PermitVisitHist > 1 or @PermitCJRR > 1
        Set @FieldIDs = @FieldIDs + ' 10290, 10291, '   --ICD 10 Diagnosis and Intervention
    if @PermitCCR > 1 or @PermitInPat > 1 or @PermitSDS > 1 or @PermitAmcare > 1 
        Set @FieldIDs = @FieldIDs + ' 10292, 10293, 10294, 10295, '   --ICD 9/9cm Diagnosis and Intervention
    if  @PermitAmcare10 > 1 or @PermitAmcare > 1 or @PermitOMHRS10 > 1 
        Set @FieldIDs = @FieldIDs + ' 10058, '  --Provider Specialty
    if @PermitCCM > 1 or @PermitCCR10 > 1 or @PermitInPat10 > 1 or @PermitSDS10 > 1 or 
       @PermitClinic > 1 or @PermitCCR > 1 or @PermitInPat > 1 or @PermitSDS > 1 or @PermitRehab10 > 1 
        Set @FieldIDs = @FieldIDs + ' 10057, '   --Provider Service
     --if @PermitCCM > 1
     --   Set @FieldIDs = @FieldIDs + ' 10322, 10325, '
	
	Set @SelString = ltrim(rtrim(@SelString))
	if right(@SelString, 1) = ','
		Set @SelString = left(@SelString, len(@SelString) - 1)

	Set @FieldIDs = ltrim(rtrim(@FieldIDs))
	if right(@FieldIDs, 1) = ','
		Set @FieldIDs = left(@FieldIDs, len(@FieldIDs) - 1)
	
	--print @SelString 

	select * into #Temptt from  u_usersfields where appid = 1100 and userid = @Userid and fieldvisible = 1
	--PR - 05463
	--set @SQL = 'Delete #Temptt where lookuptable not in 
	--(select distinct lookuptable from u_usersfields where (userid = ' + Cast(@Userid as varchar(6)) + '  and isnull(lookuptable, '''') <> ''''
	--and appid in (' + @SelString + ')) OR fieldid in (10702, 10703, 10290, 10291, 10292, 10293, 10294, 10295, 10057, 10058, 10707, 10708,10709, 10710))'
    create table #TempL(lookuptable varchar(100) COLLATE Latin1_General_CI_AS NULL)	--PR - 05519 add collation
	set @SQL = 'insert into #TempL select distinct lookuptable from u_usersfields where (userid = ' + Cast(@Userid as varchar(6)) + '  and isnull(lookuptable, '''') <> ''''
	and appid in (' + @SelString + ')) ' + (case when len(@FieldIDs) > 0 then 'OR fieldid in (' + @FieldIDs + ') ' else '' end) + ' or lookuptable = ''LU_Region'' ' -- 10702, 10703, 10290, 10291, 10292, 10293, 10294, 10295, 10057, 10058, 10707, 10708,10709, 10710)'
	--and appid in (' + @SelString + ')) OR fieldid in (10702, 10703, 10290, 10291, 10292, 10293, 10294, 10295, 10057, 10058, 10707, 10708,10709, 10710)'
	--print @SQL
	Exec(@SQL)

	--EN - 00513 FHA custom surgery screen
	if exists (select * from u_usersfields where fieldid = 101 and appid = 201) and
	   ((SELECT PermitCCR10 FROM U_Users where code = @Userid) > 1 or 
	    (SELECT PermitInPat10 FROM U_Users where code = @Userid) > 1 or
		(SELECT PermitSDS10 FROM U_Users where code = @Userid) > 1)
        insert into #TempL select distinct LookUPtable from u_usersfields where userid = 1 and appid = 1100 and fieldid between 11200 and 11213

    create index IX_TempL_LookupTable on #TempL(lookuptable)
    create index IX_Temptt_LookupTable on #Temptt(lookuptable)
    
	
	Delete #Temptt from #Temptt a left join #TempL b on a.lookuptable = b.lookuptable where b.lookuptable is null
    drop table #TempL
    --End PR - 05463
    
	Set Nocount off
	SELECT U_Fields.*, #Temptt.* FROM U_Fields, #Temptt WHERE #Temptt.FieldID = U_Fields.FieldID 
	ORDER BY #Temptt.SortOrder
	Drop Table #Temptt
End
Else IF @MultiIndex = 0 
	SELECT U_Fields.*, U_UsersFields.* FROM U_Fields, U_UsersFields WHERE U_UsersFields.FieldID = U_Fields.FieldID AND U_UsersFields.UserID = @UserID AND U_UsersFields.AppID = @AppID ORDER BY U_UsersFields.SortOrder
ELSE
	SELECT U_Fields.*, U_UsersFields.* FROM U_Fields, U_UsersFields WHERE U_UsersFields.FieldID = U_Fields.FieldID AND U_UsersFields.UserID = @UserID AND U_UsersFields.AppID = @AppID AND U_UsersFields.MultipleIndex = @MultiIndex ORDER BY U_UsersFields.SortOrder
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is called by the Load DPG Method of the SDS Control
CREATE   PROCEDURE [L_DPG]
	@Key as int
AS 

SELECT     AbstractID, OccurrenceNumber, DPG_Year, InterventionCode, DPG, DPG_RIW, DPG_MOH_RIW, DPG_Description
FROM AB_DPG WHERE AbstractID = @Key AND OccurrenceNumber = 1 
    and isnull(IsFixed , 0) = 0
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [L_DPG_Opt_Detail]
	(@AbstractID 	[int],
	@DPG_Year	[int])
AS 

SELECT AbstractID, OccurrenceNumber, DPG_Year, InterventionCode, DPG, DPG_RIW, DPG_MOH_RIW, DPG_Description
FROM  AB_DPG WHERE ([AbstractID] = @AbstractID) AND DPG_year = @DPG_Year AND OccurrenceNumber <> 1
ORDER BY OccurrenceNumber




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [L_DPG_Opt_Summary]
	(@AbstractID 	[int])
AS 
SELECT AbstractID, OccurrenceNumber, DPG_Year, InterventionCode, DPG, DPG_RIW, DPG_MOH_RIW, DPG_Description
FROM AB_DPG WHERE ([AbstractID] = @AbstractID) and OccurrenceNumber = 1
ORDER BY DPG_Year desc




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [L_DPG_Years]
	@ICDType as VarChar(1)
AS 

	If @ICDType = 'C' 
		Set @ICDType = '9'

	Select DPGYears from DPG_Years where ICDType = @ICDType
	Order by DPGYears desc




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create Procedure [L_GetMCCPartition](
    @CMG varchar(3), @MCC varchar(2), @Partition varchar(1) output)
as
    set @Partition = (select top 1 Partition from dbo.tGrouper_CMG_MCC_PARTITION_Combination
                        where CMG = @CMG and MCC = @MCC)

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This is called by the Load Method of the Hospital Profile Control
-- NOTE: There is no need for a Key because there is only 1 Record.
CREATE PROCEDURE [L_HospProf]
	@Code as int = 0
AS 
	if @Code = 0 select h.*, m.PrivacyMessage from H_HospitalProfile h left join H_HospitalProfile_Message m on h.code = m.code
	if @Code <> 0 select h.*, m.PrivacyMessage from H_HospitalProfile h left join H_HospitalProfile_Message m on h.code = m.code where h.code = @Code



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




-- This is called by the Load Method of the Institution Profile Control
CREATE PROCEDURE [L_InstProf]
	@Key as int
AS 

SELECT * FROM H_InstitutionProfile WHERE Code = @Key






GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This is called by the Load Method of the Provider Services Sub-Form
CREATE  PROCEDURE [L_LLUProvdrServ]
	@Key AS VARCHAR(50),
	@AKey AS VARCHAR(50)
AS 

SELECT * FROM LLU_ProviderServices WHERE [Code] =   @Key AND [AssociationID] = @AKey




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This is called by the Load Method of the Provider Specialty Sub-Form
CREATE  PROCEDURE [L_LLUProvdrSpec]
	@Key AS VARCHAR(50),
	@AKey AS VARCHAR(50)
AS 

SELECT * FROM LLU_ProviderSpecialty WHERE [Code] =   @Key AND [AssociationID] = @AKey




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [L_Locator_Activities]
	@PatientID as int,
	@VolumeID as int = 0,
	@HospID as int = 0,
    @ShowAll as int = 0     --PR - 03189
as 

if @VolumeID = 0 
	select 
		CLActivityID as [ ],
		VolumeID as [  ],
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(ca.HospitalID, 0)) as [Hosp ID],  
		(select VolumeNumber from CM_CPI_Volume where VolumeID = ca.VolumeID) as [Volume], 	
		(select DisplayCode from LoanLU_VolumeType where Code = (select VolumeType from CM_CPI_Volume where VolumeID = ca.VolumeID)) as [Volume Type], 	
		(select UserDescription from LoanLU_Type where Code = ActivityType) as [Type],
		convert(varchar(10),  ActivityDateOut, 111) as [Date From], 
		convert(varchar(5), ActivityTimeOut, 14) as [Time From], 
		(select UserDescription from U_Users where Code = ActivityCoderOut) as [Coder From], 
		convert(varchar(10), ActivityDateIn, 111) as [Date To], 
		convert(varchar(5), ActivityTimeIn, 14) as [Time To], 
		(select UserDescription from U_Users where Code = ActivityCoderIn) as [Coder To], 
		(select UserDescription from LoanLU_Borrower where Code = ActivityBorrower) as [Borrower],
		(select UserDescription from LoanLU_Location where Code = ActivityLocation) as [Location],
		(select UserDescription from LoanLU_Location where Code = ActivityPrevLocation) as [Previous Location],
        isnull(ca.[ActivityNotes], '') as [Notes],
        isnull(ca.[LoanReason], '') as [Reason]
	from CL_Activity ca
	where VolumeID in 
		(select VolumeID from CM_CPI_Volume 
			where PatientID = @PatientID
 			and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end))
 	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	order by [Hosp ID], [Volume] desc, ActivityDateOut desc, CLActivityID desc
else if @ShowAll = 1
	select 
		CLActivityID as [ ],
		VolumeID as [  ],
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(ca.HospitalID, 0)) as [Hosp ID],  
		(select VolumeNumber from CM_CPI_Volume where VolumeID = ca.VolumeID) as [Volume], 	
		(select DisplayCode from LoanLU_VolumeType where Code = (select VolumeType from CM_CPI_Volume where VolumeID = ca.VolumeID)) as [Volume Type], 	
		(select UserDescription from LoanLU_Type where Code = ActivityType) as [Type],
		convert(varchar(10),  ActivityDateOut, 111) as [Date From], 
		convert(varchar(5), ActivityTimeOut, 14) as [Time From], 
		(select UserDescription from U_Users where Code = ActivityCoderOut) as [Coder From], 
		convert(varchar(10), ActivityDateIn, 111) as [Date To], 
		convert(varchar(5), ActivityTimeIn, 14) as [Time To], 
		(select UserDescription from U_Users where Code = ActivityCoderIn) as [Coder To], 
		(select UserDescription from LoanLU_Borrower where Code = ActivityBorrower) as [Borrower],
		(select UserDescription from LoanLU_Location where Code = ActivityLocation) as [Location],
		(select UserDescription from LoanLU_Location where Code = ActivityPrevLocation) as [Previous Location],
        isnull(ca.[ActivityNotes], '') as [Notes],
        isnull(ca.[LoanReason], '') as [Reason]
	from CL_Activity ca
	where VolumeID = @VolumeID 
 	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	order by [Hosp ID], [Volume] desc, ActivityDateOut desc, CLActivityID desc
else
	select 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(ca.HospitalID, 0)) as [Hosp ID], 
		(select (select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) from CM_CPI_Volume where VolumeID = @VolumeID ) as [Volume Type], 
		(select UserDescription from LoanLU_Type where Code = ActivityType) as [Type],
		convert(varchar(10), ActivityDateOut, 111) as [Date From], 
		convert(varchar(10), ActivityDateIn, 111) as [Date To]
	from CL_Activity ca
	where VolumeID = @VolumeID
	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	order by [Hosp ID], ActivityDateOut desc, CLActivityID desc

return 0


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This is called by the Load Method of the General Look Up Maint. Sub-Form
CREATE  PROCEDURE [L_LUGeneral] 
	@SearchTable AS VARCHAR(50),
	@Key AS VARCHAR(50)
AS 

	DECLARE @SQL VarChar(500)
	
	IF ISNUMERIC(@SearchTable) <> 0
		SELECT * FROM LU_CodeFile WHERE [Code] = @Key			
	ELSE	
		SELECT @SQL = 'SELECT * FROM ' + @SearchTable + ' WHERE [Code] = ' + @Key
		EXECUTE (@SQL)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [L_LUMDAS_Group]
	@Key AS VARCHAR(50)
AS 
	select * from LU_CodeFile C left join LLU_MDAS_Group_Sensitivity L on C.Code = L.LUCode
	where C.Code = @Key

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This is called by the Load Method of the General Look Up Maint. Sub-Form
CREATE  PROCEDURE [L_LUProvider]
	@Key AS VARCHAR(50)
AS 

SELECT * FROM LU_Provider  WHERE [Code] =   @Key

select * from LLU_ProviderServices where AssociationID = @Key order by Occurrence
select * from LLU_ProviderSpecialty where AssociationID = @Key order by Occurrence

SELECT * FROM LLU_Provider_Vacation  WHERE [ProviderID] =   @Key order by Occurance
SELECT * FROM LLU_Provider_Suspention  WHERE [ProviderID] =   @Key order by Occurance
SELECT * FROM LLU_Provider_Schedule WHERE [ProviderID] =   @Key order by Occurrence
SELECT * FROM LLU_ProviderPrivileges WHERE [ProviderID] =   @Key order by Occurrence
SELECT * FROM LLU_Provider_UnAvailable WHERE [ProviderID] =   @Key order by Occurrence

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- This is called by the Load Method of the General Look Up Maint. Sub-Form
CREATE  PROCEDURE [L_LUReports]
	@Key AS INT
AS 

SELECT * FROM LU_Reports  WHERE [Code] =   @Key
SELECT * FROM LLU_ReportDistribution WHERE [Code] = @Key



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE     PROCEDURE [L_NextAvailableApp]
	@Provider as int,
	@SDate as VarChar(10)
AS
	Declare @Interval as int
	Declare @StartTime as datetime
	Declare @TempTime as datetime
	Declare @FinishTime as datetime
	Declare @LunchStart as DateTime
	Declare @LunchFinish as DateTime
	Declare @MaxDate as datetime
	Declare @Tempdate as DateTime
	Declare @StartDate as DateTime
	Declare @WeekLoop as int
	
	Set @Startdate = cast(@Sdate as datetime)

	select @MaxDate = DATEADD(d, 7, isnull(max(AppointmentDate), GetDate())) from SH_Appointments where (ProviderNumber = @Provider)
	If @MaxDate < @StartDate
		set @MaxDate = DATEADD(d, 7, @Startdate)
	
	SELECT AppointmentID, AppointmentDate, AppointmentTime into #AppointmentTemp FROM dbo.SH_Appointments
	WHERE (ProviderNumber = @Provider) and AppointmentDate between @Startdate and @MaxDate

	set @Weekloop = 0
	set @Tempdate = @StartDate
	While @WeekLoop < 7
	Begin
		Declare Cur_TempSched cursor for
		SELECT  StartTime, FinishTime, isnull(IntervalLen, 0), BreakTime, DATEADD(mi, BreakLen-1, BreakTime)
		FROM dbo.LLU_Provider_Schedule LEFT OUTER JOIN
		dbo.LU_CodeFile ON dbo.LLU_Provider_Schedule.SchedDay = dbo.LU_CodeFile.Code
		WHERE (dbo.LU_CodeFile.DefaultDescription = DATENAME(dw, @TempDate)) AND (dbo.LLU_Provider_Schedule.ProviderID = @Provider)
		Open Cur_TempSched
		fetch next from Cur_TempSched
		into @StartTime, @FinishTime, @Interval, @Lunchstart, @LunchFinish
		while @@fetch_status = 0
		begin
			Set @TempTime = @StartTime
			While @TempDate <= @MaxDate and @FinishTime is not null
			Begin
				Insert into #AppointmentTemp Values (0, @TempDate, @TempTime)
				Set @TempTime = DATEADD(mi, @Interval,@TempTime)
				If @TempTime >= @FinishTime
				Begin
					Set @TempDate = DATEADD(d, 7, @TempDate)
					Set @TempTime = @StartTime
				End
			End
			Update #AppointmentTemp set appointmentid = -1 where appointmenttime between @LunchStart and @LunchFinish and appointmentid = 0
			fetch next from Cur_TempSched into @StartTime, @FinishTime, @Interval, @Lunchstart, @LunchFinish
			Delete #AppointmentTemp where Appointmenttime in (select appointmenttime from #AppointmentTemp
			Group by AppointmentDate, appointmenttime having count(appointmenttime) > 1) and appointmentid = 0
			Set @TempDate = @StartDate
			Set @TempTime = @StartTime
		End
		Close Cur_TempSched
		Deallocate Cur_TempSched
		set @Weekloop = @Weekloop + 1
	End

	Select Top 20 convert(varchar(10), AppointmentDate, 111) as [Date], convert(varchar(5), AppointmentTime, 108) as [Time] from #AppointmentTemp where AppointmentID = 0 order by AppointmentDate, AppointmentTime



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE   PROCEDURE [L_NU_CrossReference]
	@Key AS INT,
	@LangID AS INT
AS 

if @LangId=0
begin
	SELECT * FROM NU_CrossReference WHERE [Code] =   @Key
end

if @LangId=10000
begin
	SELECT * FROM NU_CrossReferenceFr WHERE [Code] =   @Key
end






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE              PROCEDURE [L_NU_LookUps]
	@SearchTable AS VARCHAR(50),
	@Key AS VARCHAR(50),
	@userId as int,
	@CodeNum as varchar(20),
	@NType as int,
	@OptStatement as varchar(10)='0'
AS 

set nocount on
create table #T ( 
	[Code] [int] NOT NULL ,
	[DisplayCode] [varchar] (15) NOT NULL ,
	[UserDescription] [nvarchar] (256) COLLATE Latin1_General_CI_AS NOT NULL ,
	[CIHIVALUE] [varchar] (12) COLLATE Latin1_General_CI_AS NULL ,
	[ValidFrom] [datetime] NULL ,
	[ValidTo] [datetime] NULL ,
	[DiagnosisGender] [varchar] (1) COLLATE Latin1_General_CI_AS NULL ,
	[AgeLow] [int] NULL ,
	[AgeHigh] [int] NULL ,
	[ICDNotes] [varchar] (255) COLLATE Latin1_General_CI_AS NULL 
)

DECLARE @SQL VarChar(500)

if @SearchTable <> 'NU_PrvNotes'
begin	
	set @SQL = 'select Code, CodeNum as [DisplayCode], CodeDesc as [UserDescription], CIHIValue, ValidFrom, ValidTo, DiagnosisGender, AgeLow, AgeHigh, ICDNotes from ' +
                    @SearchTable + ' where [Code] = ' + @Key
         
	set nocount off
	EXECUTE (@SQL)
end

if @SearchTable = 'NU_PrvNotes'
begin
	if @OptStatement='10000'
	begin
		if @NType = 1  
		begin
			INSERT INTO #T
			SELECT  TOP 1   dbo.NU_CodesFr.Code, dbo.NU_CodesFr.CodeNum AS DisplayCode, dbo.NU_CodesFr.CodeDesc AS UserDescription, dbo.NU_CodesFr.CIHIVALUE, 
	           		dbo.NU_CodesFr.validFrom, dbo.NU_CodesFr.ValidTo, dbo.NU_CodesFr.DiagnosisGender, dbo.NU_CodesFr.AgeLow, dbo.NU_CodesFr.AgeHigh, 
	           		isnull(dbo.NU_PrvNotes.PrvNote,'') as ICDNOTES 
			FROM       dbo.NU_CodesFr 
			FULL OUTER  JOIN dbo.NU_PrvNotes ON dbo.NU_CodesFr.Code = dbo.NU_PrvNotes.Code
			WHERE      (dbo.NU_CodesFr.Code = @Key AND NU_CodesFr.CodeNum = @CodeNum) 
	
			UPDATE #T
			SET ICDNOTES = (SELECT  TOP 1 isnull(dbo.NU_PrvNotes.PrvNote,'') 
			FROM       dbo.NU_CodesFr 
			FULL OUTER  JOIN dbo.NU_PrvNotes ON dbo.NU_CodesFr.Code = dbo.NU_PrvNotes.Code
			WHERE      (dbo.NU_CodesFr.Code = @Key) AND UserID = @UserID AND NU_PrvNotes.CodeNum = replace(replace(@CodeNum,'.',''),'-','') and LangID=@OptStatement)
		end
	
		if @NType = 2  
		begin
			INSERT INTO #T
			SELECT  TOP 1   dbo.NU_IntCodesFr.Code, dbo.NU_IntCodesFr.CodeNum AS DisplayCode, dbo.NU_IntCodesFr.CodeDesc AS UserDescription, dbo.NU_IntCodesFr.CIHIVALUE, 
	           		dbo.NU_IntCodesFr.validFrom, dbo.NU_IntCodesFr.ValidTo, dbo.NU_IntCodesFr.DiagnosisGender, dbo.NU_IntCodesFr.AgeLow, dbo.NU_IntCodesFr.AgeHigh, 
	           		isnull(dbo.NU_PrvNotes.PrvNote,'') as ICDNOTES 
			FROM       dbo.NU_IntCodesFr 
			FULL OUTER  JOIN dbo.NU_PrvNotes ON dbo.NU_IntCodesFr.Code = dbo.NU_PrvNotes.Code
			WHERE      (dbo.NU_IntCodesFr.Code = @Key AND NU_IntCodesFr.CodeNum = @CodeNum) 
	
			UPDATE #T
			SET ICDNOTES = (SELECT  TOP 1 isnull(dbo.NU_PrvNotes.PrvNote,'') 
			FROM       dbo.NU_IntCodesFr 
			FULL OUTER  JOIN dbo.NU_PrvNotes ON dbo.NU_IntCodesFr.Code = dbo.NU_PrvNotes.Code
			WHERE      (dbo.NU_IntCodesFr.Code = @Key) AND UserID = @UserID AND NU_PrvNotes.CodeNum = replace(replace(@CodeNum,'.',''),'-','') and LangID=@OptStatement)
		end
	end
	else if @OptStatement='0'
	begin
		if @NType = 1  
		begin
			INSERT INTO #T
			SELECT  TOP 1   dbo.NU_Codes.Code, dbo.NU_Codes.CodeNum AS DisplayCode, dbo.NU_Codes.CodeDesc AS UserDescription, dbo.NU_Codes.CIHIVALUE, 
	           		dbo.NU_Codes.validFrom, dbo.NU_Codes.ValidTo, dbo.NU_Codes.DiagnosisGender, dbo.NU_Codes.AgeLow, dbo.NU_Codes.AgeHigh, 
	           		isnull(dbo.NU_PrvNotes.PrvNote,'') as ICDNOTES 
			FROM       dbo.NU_Codes 
			FULL OUTER  JOIN dbo.NU_PrvNotes ON dbo.NU_Codes.Code = dbo.NU_PrvNotes.Code
			WHERE      (dbo.NU_Codes.Code = @Key AND NU_Codes.CodeNum = @CodeNum) 
	
			UPDATE #T
			SET ICDNOTES = (SELECT  TOP 1 isnull(dbo.NU_PrvNotes.PrvNote,'') 
			FROM       dbo.NU_Codes 
			FULL OUTER  JOIN dbo.NU_PrvNotes ON dbo.NU_Codes.Code = dbo.NU_PrvNotes.Code
			WHERE      (dbo.NU_Codes.Code = @Key) AND UserID = @UserID AND NU_PrvNotes.CodeNum = replace(replace(@CodeNum,'.',''),'-','') and LangID=@OptStatement)
		end
		if @NType = 2  
		begin
			INSERT INTO #T
			SELECT  TOP 1   dbo.NU_IntCodes.Code, dbo.NU_IntCodes.CodeNum AS DisplayCode, dbo.NU_IntCodes.CodeDesc AS UserDescription, dbo.NU_IntCodes.CIHIVALUE, 
	           		dbo.NU_IntCodes.validFrom, dbo.NU_IntCodes.ValidTo, dbo.NU_IntCodes.DiagnosisGender, dbo.NU_IntCodes.AgeLow, dbo.NU_IntCodes.AgeHigh, 
	           		isnull(dbo.NU_PrvNotes.PrvNote,'') as ICDNOTES 
			FROM       dbo.NU_IntCodes 
			FULL OUTER  JOIN dbo.NU_PrvNotes ON dbo.NU_IntCodes.Code = dbo.NU_PrvNotes.Code
			WHERE      (dbo.NU_IntCodes.Code = @Key AND NU_IntCodes.CodeNum = @CodeNum) 
	
			UPDATE #T
			SET ICDNOTES = (SELECT  TOP 1 isnull(dbo.NU_PrvNotes.PrvNote,'') 
			FROM       dbo.NU_IntCodes 
			FULL OUTER  JOIN dbo.NU_PrvNotes ON dbo.NU_IntCodes.Code = dbo.NU_PrvNotes.Code
			WHERE      (dbo.NU_IntCodes.Code = @Key) AND UserID = @UserID AND NU_PrvNotes.CodeNum = replace(replace(@CodeNum,'.',''),'-','') and LangID=@OptStatement)
		end
	end

	set nocount off
	SELECT * FROM #T
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE  procedure [L_NU_PRV_Notes]

@SearchTable AS VARCHAR(50),
	@Key AS VARCHAR(50),
	@userId as int


AS

set nocount on
create table #T ( 
	[Code] [int] NOT NULL ,
	[DisplayCode] [varchar] (15) NOT NULL ,
	[UserDescription] [nvarchar] (256) COLLATE Latin1_General_CI_AS NOT NULL ,
	[CIHIVALUE] [varchar] (12) COLLATE Latin1_General_CI_AS NULL ,
	[validFrom] [datetime] NULL ,
	[ValidTo] [datetime] NULL ,
	[DiagnosisGender] [varchar] (1) COLLATE Latin1_General_CI_AS NULL ,
	[AgeLow] [int] NULL ,
	[AgeHigh] [int] NULL ,
	[ICDNotes] [varchar] (255) COLLATE Latin1_General_CI_AS NULL 
)

DECLARE @SQL VarChar(5000)

set @SQL = '
INSERT INTO #T
	SELECT  TOP 1   dbo.' + @SearchTable + '.Code, dbo.' + @SearchTable + '.CodeNum AS DisplayCode, dbo.' + 
@SearchTable + '.CodeDesc AS UserDescription, dbo.' + @SearchTable + '.CIHIVALUE, 
	           dbo.' + @SearchTable + '.validFrom, dbo.' + @SearchTable + '.ValidTo, dbo.' + 
@SearchTable + '.DiagnosisGender, dbo.' + @SearchTable + '.AgeLow, dbo.' + @SearchTable + '.AgeHigh, 
	           isnull(dbo.NU_PrvNotes.PrvNote,'''') as ICDNOTES 
	FROM       dbo.' + @SearchTable + ' FULL OUTER  JOIN
	           dbo.NU_PrvNotes ON dbo.' + @SearchTable + '.Code = dbo.NU_PrvNotes.Code
	WHERE      (dbo.' + @SearchTable + '.Code = ' + convert(varchar(15),@Key)+ ')
	
UPDATE #T
	SET ICDNOTES = (SELECT  TOP 1  
	           isnull(dbo.NU_PrvNotes.PrvNote,'''') 
	FROM       dbo.' + @SearchTable + ' FULL OUTER  JOIN
	           dbo.NU_PrvNotes ON dbo.' + @SearchTable + '.Code = dbo.NU_PrvNotes.Code
	WHERE      (dbo.' + @SearchTable + '.Code = ' + convert(varchar(15),@Key)+ ') AND UserID = ' + 
convert(varchar(10),@UserID) + ')
'

exec (@SQL)

SELECT * FROM #T

drop table #T
set nocount off





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is called by the Load Method of the Mental Health Control
CREATE   PROCEDURE [L_OMHRS]
	@Key as int, @LogID int
AS 

select * from [OMHRS_SecAA] where AbstractID = @Key
select * from [OMHRS_SecBB] where AbstractID = @Key
select * from [OMHRS_SecCC] where AbstractID = @Key
select * from [OMHRS_SecDD] where AbstractID = @Key

select * from [OMHRS_SecA] where AbstractID = @Key
select * from [OMHRS_SecB] where AbstractID = @Key
select * from [OMHRS_SecC] where AbstractID = @Key
select * from [OMHRS_SecD] where AbstractID = @Key
select * from [OMHRS_SecE] where AbstractID = @Key
select * from [OMHRS_SecF] where AbstractID = @Key
select * from [OMHRS_SecG] where AbstractID = @Key
select * from [OMHRS_SecH] where AbstractID = @Key
select * from [OMHRS_SecI] where AbstractID = @Key
select * from [OMHRS_SecJ] where AbstractID = @Key
select * from [OMHRS_SecK] where AbstractID = @Key
select * from [OMHRS_SecL] where AbstractID = @Key
select * from [OMHRS_SecM] where AbstractID = @Key
select * from [OMHRS_SecN] where AbstractID = @Key
select * from [OMHRS_SecO] where AbstractID = @Key
select * from [OMHRS_SecP] where AbstractID = @Key
select * from [OMHRS_SecQ] where AbstractID = @Key
select * from [OMHRS_SecR] where AbstractID = @Key
select * from [OMHRS_SecS] where AbstractID = @Key

select * from [dbo].[OMHRS_MHAPS] where AbstractID = @Key
select * from [dbo].[OMHRS_Ancillary] where AbstractID = @Key
select * from [dbo].[OMHRS_BasicOption] where AbstractID = @Key
select * from [dbo].[OMHRS_UserDefined] where AbstractID = @Key
select * from [dbo].[OMHRS_RecInfo] where AbstractID = @Key
select * from [dbo].[OMHRS_IAR_CCIM] where AbstractID = @Key --EN-00526

select * from [OMHRS_UDFieldsDate] where ([AbstractID] = @Key)
select * from [OMHRS_UDFieldsTime] where ([AbstractID] = @Key)
select * from [OMHRS_UDFieldsLookUp] where ([AbstractID] = @Key)
select * from [OMHRS_UDFieldsInteger] where ([AbstractID] = @Key)
select * from [OMHRS_UDFieldsText] where ([AbstractID] = @Key)
select * from [OMHRS_UDFieldsSmallText] where ([AbstractID] = @Key)

select * from [OMHRS_Serv_Interrupt] where AbstractID = @Key order by Occurrence 
select * from [OMHRS_DSM_Diag] where AbstractID = @Key order by Occurrence 
select * from [OMHRS_Med_Diag] where AbstractID = @Key order by Occurrence 
select * from [OMHRS_Medication] where AbstractID = @Key order by Occurrence 

select * from [dbo].[OMHRS_Intervention] where AbstractID = @Key order by IntervOccurrence 
select * from [dbo].[OMHRS_Provider] where AbstractID = @Key order by ProviderOccurrence
select * from [dbo].[OMHRS_Project] where AbstractID = @Key order by ProjectOccurrence

select * from [OMHRS_DSM_Diag_II] where AbstractID = @Key order by Occurrence   --ED - 02279
select * from [OMHRS_DSM_5] where AbstractID = @Key order by Occurrence   --2.x-0295

--select * from [OMHRS_Diagnosis_CodeSmart] where AbstractID = @Key order by cSDiagnosisOccurrence   --EN - 00607
--select * from [OMHRS_Intervention_CodeSmart] where AbstractID = @Key order by cSInterventionOccurrence   --EN - 00607

declare @HID as int 
select @HID = HospitalID from U_Users where Code = @LogID
insert into dbo.OMHRS_UpdateHistory(AbstractID, HospitalID, Coder, Updated, UpdateType) values (@Key, @HID, @LogID, getdate(), 'Viewed') 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [L_PullList]
    --EN-00183
    @PullID int, -- @PullListID as VarChar(50),
--    @PullDate as datetime,
    @HospID as int,
	@PullListAll as VarChar(1)
AS 
    declare @PullListID varchar(50)
    declare @LocationID int
    --En-00183
    select @HospID = HospitalID, @PullListID = PullListID, @LocationID = PullLocation
    from cl_PullList where PullID = @PullID

    SELECT Top 1 VolumeID, 
		PullListID, 
		Convert(varchar(10), PullDate, 111) AS [PullDate], 
		CONVERT (varchar(5), PullTime, 14) AS [PullTime], 
		PullLocation, 
		Puller, 
		PullNotes, 
    		Convert(varchar(10), PullOutDate, 111) AS PullOutDate, 
    		CONVERT (varchar(5), PullOutTime, 14) AS PullOutTime, CLRequestPriority,
        HospitalID
	FROM dbo.CL_PullList
	Where PullID = @PullID --PullListID = @PullListID 
	AND ISNULL(PullListStatus, 0) <> 1
    	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	If @PullListAll = 'Y'
        select
            v.VolumeID as [ ], 
            isnull(ch.DisplayCode, '') as [Chart Hospital Link],
            --PR - 06101
    		--REPLACE(SPACE(10 - LEN(c.ChartNumber)) + c.ChartNumber, ' ', '0') AS ChartNumber, 
    		c.ChartNumber,
    		(select DisplayCode from LoanLU_VolumeType where Code = v.VolumeType) as [Volume Type], 
            vh.DisplayCode as [Volume Hospital Link],
    		v.VolumeNumber AS [Volume], 
    		ISNULL(c.LastName, '') + ', ' + ISNULL(c.FirstName, '') + ' ' + ISNULL(c.MiddleName, '') AS [Full Name], 
            isnull(D.DisplayCode, '') as [Expirted],
    		CONVERT(VarChar(10), c.BirthDate, 111) AS [Birth Date], 
    		cl.DisplayCode AS [Current Location],
            FL.DisplayCode AS [Previous Location], 
    		PL.DisplayCode AS [Permanent Location],
            v.CLBoxNumber as [Box Number],
    		CONVERT(VarChar(10), c.LastVisitDate, 111) AS [Last Visit Date], 
    		v.VolumeDateFrom AS [Date From],
    		v.VolumenDateTo AS [Date To],
            
            PullTime as [Require Time],
            --PullNotes as Notes,
            LoanNote  as Notes,
            PullID,
            PullListStatus,
            -- PR - 01678
            isnull(B.UserDescription, '') as [Borrower], --isnull(B.DisplayCode, '') as [Borrower],
            Puller,
            isnull(LoanReason, '') as [Reason for Loan],
            isnull(Digit.DisplayCode, '') as [Digital]  --TS-222
  		FROM  dbo.CL_PullList p inner join 
            CM_CPI_Volume v ON v.VolumeID = p.VolumeID inner join
            dbo.CM_CPI c ON v.PatientID = c.PatientID LEFT OUTER JOIN
            dbo.LoanLU_Location CL ON v.CLCurrentLocation = CL.Code LEFT OUTER JOIN
            dbo.LoanLU_Location PL ON v.PermLocation = PL.Code LEFT OUTER JOIN
            dbo.LoanLU_Location FL ON v.CLPreviousLocation = FL.Code LEFT OUTER JOIN
            H_HospitalProfile CH on c.HospitalID = CH.Code LEFT OUTER JOIN
            H_HospitalProfile VH on v.HospitalID = VH.Code left join
            LU_YesNoSystem D on c.DeathIndicator = D.Code left join
            LoanLU_Borrower B on p.Puller = B.Code left join
            dbo.LoanLU_DigitalIndicator Digit on v.DigitalIndicator = Digit.code --TS-222
		Where PullListID = @PullListID --and PullDate = @PullDate 
            and p.PullLocation = @LocationID
        	AND (ISNULL(p.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(p.HospitalID, 0) end)
        	--AND (ISNULL(v.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(v.HospitalID, 0) end)
        	--AND (ISNULL(c.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(c.HospitalID, 0) end)
		ORDER BY ChartNumber, v.VolumenDateTo desc, VolumeNumber desc, PullTime
	Else
        select
            v.VolumeID as [ ], 
            isnull(ch.DisplayCode, '') as [Chart Hospital Link],
            --PR - 06101
    		--REPLACE(SPACE(10 - LEN(c.ChartNumber)) + c.ChartNumber, ' ', '0') AS ChartNumber, 
    		c.ChartNumber,
    		(select DisplayCode from LoanLU_VolumeType where Code = v.VolumeType) as [Volume Type], 
            vh.DisplayCode as [Volume Hospital Link],
    		v.VolumeNumber AS [Volume], 
    		ISNULL(c.LastName, '') + ', ' + ISNULL(c.FirstName, '') + ' ' + ISNULL(c.MiddleName, '') AS [Full Name], 
            isnull(D.DisplayCode, '') as [Expirted],
    		CONVERT(VarChar(10), c.BirthDate, 111) AS [Birth Date], 
    		cl.DisplayCode AS [Current Location],
            FL.DisplayCode AS [Previous Location], 
    		PL.DisplayCode AS [Permanent Location],
            v.CLBoxNumber as [Box Number],
    		CONVERT(VarChar(10), c.LastVisitDate, 111) AS [Last Visit Date], 
    		v.VolumeDateFrom AS [Date From],
    		v.VolumenDateTo AS [Date To],
            PullTime as [Require Time],
            --PullNotes as Notes,
            LoanNote  as Notes,
            PullID,
            PullListStatus,
            -- PR - 01678
            isnull(B.UserDescription, '') as [Borrower], --isnull(B.DisplayCode, '') as [Borrower],
            Puller,
            isnull(LoanReason, '') as [Reason for Loan],
            isnull(Digit.DisplayCode, '') as [Digital]  --TS-222
  		FROM  dbo.CL_PullList p inner join 
            CM_CPI_Volume v ON v.VolumeID = p.VolumeID inner join
            dbo.CM_CPI c ON v.PatientID = c.PatientID LEFT OUTER JOIN
            dbo.LoanLU_Location CL ON v.CLCurrentLocation = CL.Code LEFT OUTER JOIN
            dbo.LoanLU_Location PL ON v.PermLocation = PL.Code LEFT OUTER JOIN
            dbo.LoanLU_Location FL ON v.CLPreviousLocation = FL.Code LEFT OUTER JOIN
            H_HospitalProfile CH on c.HospitalID = CH.Code LEFT OUTER JOIN
            H_HospitalProfile VH on v.HospitalID = VH.Code left join
            LU_YesNoSystem D on c.DeathIndicator = D.Code left join
            LoanLU_Borrower B on p.Puller = B.Code left join
            dbo.LoanLU_DigitalIndicator Digit on v.DigitalIndicator = Digit.code    --TS-222
		Where PullListID = @PullListID and isnull(PullListStatus, '0') <> 1
            and p.PullLocation = @LocationID
        	AND (ISNULL(p.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(p.HospitalID, 0) end)
        	--AND (ISNULL(v.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(v.HospitalID, 0) end)
        	--AND (ISNULL(c.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(c.HospitalID, 0) end)
		ORDER BY ChartNumber, v.VolumenDateTo desc, VolumeNumber desc, PullTime
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


--EN-00183
CREATE PROCEDURE [L_PullListForPurge]
    @HospID  int,
    @Options1  int,
    @Options2  int,
    @Options3  int,
    @Options4  int,
    @StartDate varchar(10),
    @EndDate varchar(10),   --EN - 00368
    @PullID    int
AS 
--@Options1 Not Return
--@Options2 Return
--@Options3 Unloan
--@Options4 Purged

    declare @PullListID varchar(50)
    declare @LocationID int
    declare @PullHospitalID int
    --declare @StartDate as varchar(20)
    --declare @EndDate as varchar(20)
    declare @Sql        varchar(8000)
    
    if @PullID > 0
    begin
        select @PullListID = PullListID, @LocationID = PullLocation, @PullHospitalID = HospitalID
        from CL_PullList
        where PullID = @PullID
        if @PullListID is null set @PullListID = ''
        if @LocationID is null set @LocationID = 0
        if @PullHospitalID is null set @PullHospitalID = 0
    end
--EN - 00368
--	if right(@DateFrom, 2) = '00' or substring(@DateFrom, 6, 2) = '00'
--	begin
--        if substring(@DateFrom, 6, 2) = '00'
--        begin
--            set @StartDate = left(@DateFrom, 5) + '01-01'
--            set @EndDate = left(@DateFrom, 5) + '12-31'
--        end
--        else
--        begin
--            set @StartDate = left(@DateFrom, 8) 
--            set @EndDate = left(@DateFrom, 8) 
--
--            set @StartDate = @StartDate + '01'
--            set @EndDate = @EndDate + '01'
--            if isdate(@EndDate) = 1
--                set @EndDate = cast(dateadd(day, -1, dateadd(month, 1, cast(@EndDate as datetime))) as varchar(20))
--        end
--    end
--    else
--    begin
--        set @StartDate = @DateFrom
--        set @EndDate = @DateFrom
--    end
    set @sql = ''
    if @Options1 = 1 or @Options2 = 1 or @Options3 = 1
    set @Sql = '
    select
        v.VolumeID as [ ], 
        isnull(ch.DisplayCode, '''') as [Chart Hospital Link],
		REPLACE(SPACE(10 - LEN(c.ChartNumber)) + c.ChartNumber, '' '', ''0'') AS ChartNumber, 
		(select DisplayCode from LoanLU_VolumeType where Code = v.VolumeType) as [Volume Type], 
        vh.DisplayCode as [Volume Hospital Link],
		v.VolumeNumber AS [Volume], 
		ISNULL(c.LastName, '''') + '', '' + ISNULL(c.FirstName, '''') + '' '' + ISNULL(c.MiddleName, '''') AS [Full Name], 
        isnull(D.DisplayCode, '''') as [Expirted],
		CONVERT(VarChar(10), c.BirthDate, 111) AS [Birth Date], 
		cl.DisplayCode AS [Current Location],
        FL.DisplayCode AS [Previous Location], 
		PL.DisplayCode AS [Permanent Location],
        PullTime as [Require Time],
        LoanNote  as Notes,
        PullID,
        PullListStatus,
        isnull(B.DisplayCode, '''') as [Borrower],
        Puller,
        isnull(LoanReason, '''') as [Reason for Loan],
        isnull(ph.DisplayCode, '''') as [Pull List Hospital Link],
        p.PullListID,
        p.PullDate,
        Al.DisplayCode as [Transaction Location],
        (case when PullListStatus = 1 then ''Loan'' else '''' end) as [Loan Status],
        R.DisplayCode as [Returned],
        PullNotes as [Transaction Notes]

	FROM  dbo.CL_PullList p inner join 
        CM_CPI_Volume v ON v.VolumeID = p.VolumeID inner join
        dbo.CM_CPI c ON v.PatientID = c.PatientID LEFT OUTER JOIN
        dbo.LoanLU_Location CL ON v.CLCurrentLocation = CL.Code LEFT OUTER JOIN
        dbo.LoanLU_Location PL ON v.PermLocation = PL.Code LEFT OUTER JOIN
        dbo.LoanLU_Location FL ON v.CLPreviousLocation = FL.Code LEFT OUTER JOIN
        dbo.LoanLU_Location AL ON p.PullLocation = AL.Code LEFT OUTER JOIN

        H_HospitalProfile PH on p.HospitalID = PH.Code LEFT OUTER JOIN
        H_HospitalProfile CH on c.HospitalID = CH.Code LEFT OUTER JOIN
        H_HospitalProfile VH on v.HospitalID = VH.Code left join
        LU_YesNoSystem D on c.DeathIndicator = D.Code left join
        LoanLU_Borrower B on p.Puller = B.Code left join
        LU_YesNoSystem R on p.IsReturned = R.Code 

	Where ' + (case when isnull(@HospID, 0) = 0 then '' else '
        (ISNULL(p.HospitalID, 0) = 0 OR p.HospitalID = ' + cast(@HospID as varchar(10)) + ') and ' end) + ' 
        PullDate between ''' + @StartDate + ''' and ''' + @EndDate + '''
        and PullDate < getdate() ' +
    (case when @Options1 = 1 and @Options2 = 1 and @Options3 = 1 then ''
          else (case when @Options1 = 1 or @Options2 = 1 then ' and PullListStatus = 1' else '' end) +
               (case when @Options2 = 1 then ' and IsReturned = 1' else '' end) +
               (case when @Options3 = 1 then ' and Isnull(PullListStatus, 0) = 0' else '' end) 
          end) + 
    (case when @PullID > 0 then
            ' and not (PullListID = ''' + @PullListID + ''' and PullLocation = ' + cast(@LocationID as varchar(10)) + ' and isnull(HospitalID, 0) = ' + cast(@PullHospitalID as varchar(10)) + ')'
          else ''
          end)

    if @Options4 = 1 and @sql <> ''
        set @sql = @sql + ' union '

    if @Options4 = 1
        set @sql = @sql + ' 
    select
        v.VolumeID as [ ], 
        isnull(ch.DisplayCode, '''') as [Chart Hospital Link],
		REPLACE(SPACE(10 - LEN(c.ChartNumber)) + c.ChartNumber, '' '', ''0'') AS ChartNumber, 
		(select DisplayCode from LoanLU_VolumeType where Code = v.VolumeType) as [Volume Type], 
        vh.DisplayCode as [Volume Hospital Link],
		v.VolumeNumber AS [Volume], 
		ISNULL(c.LastName, '''') + '', '' + ISNULL(c.FirstName, '''') + '' '' + ISNULL(c.MiddleName, '''') AS [Full Name], 
        isnull(D.DisplayCode, '''') as [Expirted],
		CONVERT(VarChar(10), c.BirthDate, 111) AS [Birth Date], 
		cl.DisplayCode AS [Current Location],
        FL.DisplayCode AS [Previous Location], 
		PL.DisplayCode AS [Permanent Location],
        PullTime as [Require Time],
        LoanNote  as Notes,
        PullID,
        PullListStatus,
        isnull(B.DisplayCode, '''') as [Borrower],
        Puller,
        isnull(LoanReason, '''') as [Reason for Loan],
        isnull(ph.DisplayCode, '''') as [Pull List Hospital Link],
        p.PullListID,
        p.PullDate,
        Al.DisplayCode as [Transaction Location],
        ''Purged'' as [Loan Status],
        '''' as [Returned],
        PullNotes as [Transaction Notes]

	FROM  dbo.CL_PullList_Purged p inner join 
        CM_CPI_Volume v ON v.VolumeID = p.VolumeID inner join
        dbo.CM_CPI c ON v.PatientID = c.PatientID LEFT OUTER JOIN
        dbo.LoanLU_Location CL ON v.CLCurrentLocation = CL.Code LEFT OUTER JOIN
        dbo.LoanLU_Location PL ON v.PermLocation = PL.Code LEFT OUTER JOIN
        dbo.LoanLU_Location FL ON v.CLPreviousLocation = FL.Code LEFT OUTER JOIN
        dbo.LoanLU_Location AL ON p.PullLocation = AL.Code LEFT OUTER JOIN

        H_HospitalProfile PH on p.HospitalID = PH.Code LEFT OUTER JOIN
        H_HospitalProfile CH on c.HospitalID = CH.Code LEFT OUTER JOIN
        H_HospitalProfile VH on v.HospitalID = VH.Code left join
        LU_YesNoSystem D on c.DeathIndicator = D.Code left join
        LoanLU_Borrower B on p.Puller = B.Code left join
        LU_YesNoSystem R on p.IsReturned = R.Code 

	Where ' + (case when isnull(@HospID, 0) = 0 then '' else '
        (ISNULL(p.HospitalID, 0) = 0 OR p.HospitalID = ' + cast(@HospID as varchar(10)) + ') and ' end)  + '
        PullDate between ''' + @StartDate + ''' and ''' + @EndDate + ''' '
    
    set @sql = @sql + ' order by PullDate, PullListID, ChartNumber, VolumeNumber '

    --print @sql
    exec (@sql)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is called by the Load Method of the Purge/Undelete Control
CREATE PROCEDURE [L_Purge]
	@HospID as int = 0
AS 
    set nocount on
	-- CPI
    --20582 It take too long to run 
    select T.PatientID into #a
    fROM CM_CPI T with (nolock)
    WHERE IsDeleted <> 2 
    AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
    create index idx_cpi_purge_1_AbstractID on #a(PatientID)

    select z.PatientID, max(Updated) maxDate into #b 
    from #a z inner join CM_UpdateHistory h  with (nolock) on z.PatientID = h.PatientID 
    where UpdateType = 'Deleted'
    group by z.PatientID 
    create index idx_cpi_purge_2_AbstractID on #b (PatientID)

    select z.PatientID, z.maxDate, max(coder) as Coder into #c
    from #b z inner join CM_UpdateHistory h  with (nolock) on z.PatientID = h.PatientID  and z.maxDate = h.Updated 
    where UpdateType = 'Deleted'
    group by z.PatientID, z.maxDate
    create index idx_cpi_purge_3_AbstractID on #c (PatientID)
    create index idx_cpi_purge_3_Coder on #c (PatientID)

	SELECT t.PatientID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(T.HospitalID, 0)) as [Hosp ID],
		'CPI' AS [CareType], 
		'' AS [ICDType],		
		'' AS [Inst],
		ChartNumber, 
		ISNULL(t.LastName, '') + ', ' + ISNULL(t.FirstName, '') + ' ' + ISNULL(t.MiddleName, '') AS [FullName],
		'' AS [EncounterNumber],
		'' AS [EncounterSequence],
		'' AS [VisitDate],
		'' AS [VisitTime],
    	--(select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from CM_UpdateHistory where PatientID = T.PatientID and UpdateType = 'Deleted' order by Updated desc)) as [Del Coder],
    	--(select top 1 convert(nvarchar(10), Updated, 111) from CM_UpdateHistory where PatientID = T.PatientID and UpdateType = 'Deleted' order by Updated desc) as [Del Date],
    	--(select top 1 convert(nvarchar(5), Updated, 14) from CM_UpdateHistory where PatientID = T.PatientID and UpdateType = 'Deleted' order by Updated desc) as [Del Time],
        u.DisplayCode as [Del Coder],
        convert(nvarchar(10), z.maxDate, 111) as [Del Date],
        convert(nvarchar(5), z.maxDate, 14) as [Del Time],
		'' as [CIHIDateSent], 
		'' as BatchYear,
		'' as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		'' as [IsCompleted],
		'' as [IsValidated],
		'' as [IsSubmited],
		'' as [IsCorrected],
        0 as [LinkID]
	FROM CM_CPI T with (nolock)
        inner join #c z on t.PatientID = z.PatientID
        left join U_Users u on z.coder = u.code 
	WHERE IsDeleted <> 2
--	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	-- Visit History (non-abstracted) --RM: [2006/12/14]
	SELECT UniversalID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(T.HospitalID, 0)) as [Hosp ID],
		'VH' AS [CareType],
		ICDType, 
		(SELECT top 1 DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber) AS [Inst],
		ChartNumber,
		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [FullName],
		EncounterNumber, 
		EncounterSequence AS [EncounterSequence],
		CONVERT(VARCHAR(10), AdmitDate, 111) AS [VisitDate],
   		CONVERT (VARCHAR(5), AdmitTime, 14) AS [VisitTime],
    	(select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from AB_UpdateHistory with (nolock) where AbstractID = T.AbstractID and UpdateType = 'Deleted' order by Updated desc)) as [Del Coder],
    	(select top 1 convert(nvarchar(10), Updated, 111) from AB_UpdateHistory with (nolock) where AbstractID = T.AbstractID and UpdateType = 'Deleted' order by Updated desc) as [Del Date],
    	(select top 1 convert(nvarchar(5), Updated, 14) from AB_UpdateHistory with (nolock) where AbstractID = T.AbstractID and UpdateType = 'Deleted' order by Updated desc) as [Del Time],
		'' as [CIHIDateSent], 
		'' as BatchYear,
		'' as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		'' as [IsSubmited],
		'' as [IsCorrected],
        0 as [LinkID]
	FROM AB_Main T with (nolock)
	WHERE IsDeleted <> 2 AND AppID = 3
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	-- ROI
--	UNION
	SELECT ROIID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(T.HospitalID, 0)) as [Hosp ID],
		'ROI' AS [CareType], 
		'' AS [ICDType],		
		'' AS [Inst],
		ChartNumber, 
		(SELECT TOP 1 ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') FROM CM_CPI WHERE CM_CPI.ChartNumber = T.ChartNumber) AS [FullName],
		RequestNumber AS [EncounterNumber],
		'' AS [EncounterSequence],
		'' AS [VisitDate],
		'' AS [VisitTime],
        	(select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from ROI_UpdateHistory with (nolock) where ROIID = T.ROIID order by Updated desc)) as [Del Coder],
        	(select top 1 convert(nvarchar(10), Updated, 111) from ROI_UpdateHistory with (nolock) where ROIID = T.ROIID order by Updated desc) as [Del Date],
        	(select top 1 convert(nvarchar(5), Updated, 14) from ROI_UpdateHistory with (nolock) where ROIID = T.ROIID order by Updated desc) as [Del Time],
		'' as [CIHIDateSent], 
		'' as BatchYear,
		'' as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		'' as [IsCompleted],
		'' as [IsValidated],
		'' as [IsSubmited],
		'' as [IsCorrected],
        0 as [LinkID]
	FROM ROI_Main T with (nolock) 
	WHERE IsDeleted <> 2
	AND (ISNULL(T.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(T.HospitalID, 0) end)
    --20582 It take too long to run 
    select T.AbstractID into #D
    fROM AB_Abstract T with (nolock)
    WHERE IsDeleted <> 2 --AND CareType in (1, 101, 2, 102)
    AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
    create index idx_purge_1_AbstractID on #D(AbstractID)

    select z.AbstractID, max(Updated) maxDate into #M 
    from #D z inner join AB_UpdateHistory h  with (nolock) on z.AbstractID = h.AbstractId 
    where UpdateType = 'Deleted'
    group by z.AbstractID 
    create index idx_purge_2_AbstractID on #M (AbstractID)

    select z.abstractID, z.maxDate, max(coder) as Coder into #N
    from #M z inner join AB_UpdateHistory h  with (nolock) on z.AbstractID = h.AbstractId  and z.maxDate = h.Updated 
    where UpdateType = 'Deleted'
    group by z.abstractID, z.maxDate
    create index idx_purge_3_AbstractID on #N (AbstractID)
    create index idx_purge_3_Coder on #N (Coder)

	-- INPATIENT/CCR/SDS
--	UNION
	SELECT t.AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(T.HospitalID, 0)) as [Hosp ID],
		--(SELECT DisplayCode FROM LU_CareType WHERE Code = CareType) AS [CareType],
		(case when CareType in (1, 101) then 'A' when CareType in (2, 102) then 'D' end) AS [CareType],
		ICDType, 
		(SELECT top 1 DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber) AS [Inst],
		ChartNumber,
		ISNULL(t.LastName, '') + ', ' + ISNULL(t.FirstName, '') + ' ' + ISNULL(t.MiddleName, '') AS [FullName],
		EncounterNumber, 
		'' AS [EncounterSequence],
		CONVERT(VARCHAR(10), DischargeDate, 111) AS [VisitDate],
   		CONVERT (VARCHAR(5), DischargeTime, 14) AS [VisitTime],
        	--(select top 1DisplayCode from U_Users where Code = (select top 1 Coder from AB_UpdateHistory where AbstractID = T.AbstractID and UpdateType = 'Deleted' order by Updated desc)) as [Del Coder],
        	--(select top 1 convert(nvarchar(10), Updated, 111) from AB_UpdateHistory where AbstractID = T.AbstractID and UpdateType = 'Deleted' order by Updated desc) as [Del Date],
        	--(select top 1 convert(nvarchar(5), Updated, 14) from AB_UpdateHistory where AbstractID = T.AbstractID and UpdateType = 'Deleted' order by Updated desc) as [Del Time],
        u.DisplayCode as [Del Coder],
        convert(nvarchar(10), z.maxDate, 111) as [Del Date],
        convert(nvarchar(5), z.maxDate, 14) as [Del Time],

		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		BatchNumber,
		AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		(select top 1 DisplayCode from LU_CIHICorrect where Code = IsCorrected) as [IsCorrected],
        0 as [LinkID]
	FROM AB_Abstract T with (nolock) 
        left join #N z on t.AbstractID = z.AbstractID
        left join U_Users u on z.coder = u.code 
	WHERE IsDeleted <> 2 AND CareType in (1, 101, 2, 102)
	AND (ISNULL(t.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(t.HospitalID, 0) end)

	-- AMCARE
--	UNION
	SELECT t.AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(T.HospitalID, 0)) as [Hosp ID],
		'B' AS [CareType],
		ICDType, 
		(SELECT top 1 DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber) AS [Inst],
		ChartNumber,
		ISNULL(t.LastName, '') + ', ' + ISNULL(t.FirstName, '') + ' ' + ISNULL(t.MiddleName, '') AS [FullName],
		EncounterNumber, 
		REPLACE(SPACE(3-LEN(ISNULL(CONVERT(VARCHAR(3),EncounterSequence), 0))) + ISNULL(CONVERT(VARCHAR(3),EncounterSequence), 0), ' ', '0') AS [EncounterSequence], 
		CONVERT(VARCHAR(10), AdmitDate, 111) AS [VisitDate],
   		CONVERT (VARCHAR(5), AdmitTime, 14) AS [VisitTime],
        	--(select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from AB_UpdateHistory where AbstractID = T.AbstractID and UpdateType = 'Deleted' order by Updated desc)) as [Del Coder],
        	--(select top 1 convert(nvarchar(10), Updated, 111) from AB_UpdateHistory where AbstractID = T.AbstractID and UpdateType = 'Deleted' order by Updated desc) as [Del Date],
        	--(select top 1 convert(nvarchar(5), Updated, 14) from AB_UpdateHistory where AbstractID = T.AbstractID and UpdateType = 'Deleted' order by Updated desc) as [Del Time],
        u.DisplayCode as [Del Coder],
        convert(nvarchar(10), z.maxDate, 111) as [Del Date],
        convert(nvarchar(5), z.maxDate, 14) as [Del Time],

		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		BatchNumber,
		AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		(select top 1 DisplayCode from LU_CIHICorrect where Code = IsCorrected) as [IsCorrected],
        0 as [LinkID]
	FROM AB_Abstract T with (nolock) 
        left join #N z on t.AbstractID = z.AbstractID
        left join U_Users u on z.coder = u.code 
	WHERE IsDeleted <> 2 AND CareType in (5, 105)
	AND (ISNULL(t.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(t.HospitalID, 0) end)

	-- REHAB ADMISSION
--	UNION 
	SELECT AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(RH_ClientInfo.HospitalID, 0)) as [Hosp ID],
		'R - 1' AS [CareType],
		'T' AS [ICDType],
		(SELECT top 1 DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber) AS [Inst],
		ChartNumber,
		--2.x-1060 replace CM_CPI with RH_Demographic
		(SELECT TOP 1 ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') FROM RH_Demographic WHERE RH_Demographic.AbstractID = RH_ClientInfo.AbstractID) AS [FullName],
		'' AS [EncounterNumber],
		'' AS [EncounterSequence],
		CONVERT(VARCHAR(10), AdmitDate, 111) AS [VisitDate],
    		'' AS [VisitTime],
        	'' as [Del Coder],
        	'' as [Del Date],
        	'' as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		(select top 1 DisplayCode from LU_CIHICorrect where Code = IsCorrected) as [IsCorrected],
        [LinkID]
	FROM RH_ClientInfo with (nolock) 
    	WHERE IsDeleted <> 2 AND AssessmentType = 134
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	-- REHAB INTERIM
--	UNION 
	SELECT AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(RH_ClientInfo.HospitalID, 0)) as [Hosp ID],
		'R - IA' AS [CareType],
		'T' AS [ICDType],
		(SELECT top 1 DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber) AS [Inst],
		ChartNumber,
		--2.x-1060 replace CM_CPI with RH_Demographic
		(SELECT TOP 1 ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') FROM RH_Demographic WHERE RH_Demographic.AbstractID = RH_ClientInfo.AbstractID) AS [FullName],
		'' AS [EncounterNumber],
		'' AS [EncounterSequence],
		CONVERT(VARCHAR(10), DischargeDate, 111) AS [VisitDate],
	    	'' AS [VisitTime],
	        '' as [Del Coder],
	        '' as [Del Date],
	        '' as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		(select top 1 DisplayCode from LU_CIHICorrect where Code = IsCorrected) as [IsCorrected],
        [LinkID]
	FROM RH_ClientInfo with (nolock) 
    	WHERE IsDeleted <> 2 AND AssessmentType = 156
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	-- REHAB DISCHARGE
--	UNION 
	SELECT AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(RH_ClientInfo.HospitalID, 0)) as [Hosp ID],
		'R - 2' AS [CareType],
		'T' AS [ICDType],
		(SELECT top 1 DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber) AS [Inst],
		ChartNumber,
		--2.x-1060 replace CM_CPI with RH_Demographic
		(SELECT TOP 1 ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') FROM RH_Demographic WHERE RH_Demographic.AbstractID = RH_ClientInfo.AbstractID) AS [FullName],
		'' AS [EncounterNumber],
		'' AS [EncounterSequence],
		CONVERT(VARCHAR(10), DischargeDate, 111) AS [VisitDate],
	    	'' AS [VisitTime],
        	'' as [Del Coder],
        	'' as [Del Date],
        	'' as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		(select top 1 DisplayCode from LU_CIHICorrect where Code = IsCorrected) as [IsCorrected],
        [LinkID]
	FROM RH_ClientInfo with (nolock) 
    	WHERE IsDeleted <> 2 AND AssessmentType = 135
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	-- REHAB FOLLOW UP
--	UNION 
	SELECT AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(RH_ClientInfo.HospitalID, 0)) as [Hosp ID],
		'R - 3' AS [CareType],
		'T' AS [ICDType],
		(SELECT top 1 DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber) AS [Inst],
		ChartNumber,
		--2.x-1060 replace CM_CPI with RH_Demographic
		(SELECT TOP 1 ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') FROM RH_Demographic WHERE RH_Demographic.AbstractID = RH_ClientInfo.AbstractID) AS [FullName],
		'' AS [EncounterNumber],
		'' AS [EncounterSequence],
		CONVERT(VARCHAR(10), FollowUpDate, 111) AS [VisitDate],
   		'' AS [VisitTime],
	        '' as [Del Coder],
	        '' as [Del Date],
	        '' as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		(select top 1 DisplayCode from LU_CIHICorrect where Code = IsCorrected) as [IsCorrected],
        [LinkID]
	FROM RH_ClientInfo with (nolock) 
    	WHERE IsDeleted <> 2 AND AssessmentType = 136
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	-- CCRS ADMISSION BG
--	UNION 
	SELECT AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(T.HospitalID, 0)) as [Hosp ID],
		'L - 0A' AS [CareType],
		'T' AS [ICDType], 
		(SELECT top 1 DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber) AS [Inst],
		ChartNumber, 
		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [FullName],
		'' AS [EncounterNumber],
		'' AS [EncounterSequence],
		CONVERT(VarChar(10), AdmitDate, 111) AS [VisitDate],
		'' AS [VisitTime],
	        (select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc)) as [Del Coder],
	        (select top 1 convert(nvarchar(10), Updated, 111) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Date],
        	(select top 1 convert(nvarchar(5), Updated, 14) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		'' as [IsCorrected],
        [LinkID]
	FROM CRS_Demographic T with (nolock) 
	WHERE IsDeleted <> 2 AND AA8 = 14501
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	-- CCRS DEMO CHANGES
--	UNION 
	SELECT AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(T.HospitalID, 0)) as [Hosp ID],
		'L - 00' AS [CareType],
		'T' AS [ICDType], 
		(SELECT top 1 DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber) AS [Inst],
		ChartNumber, 
		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [FullName],
		'' AS [EncounterNumber],
		'' AS [EncounterSequence],
		CONVERT(VarChar(10), Z7, 111) AS [VisitDate],
		'' AS [VisitTime],
	        (select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc)) as [Del Coder],
	        (select top 1 convert(nvarchar(10), Updated, 111) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Date],
	        (select top 1 convert(nvarchar(5), Updated, 14) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		'' as [IsCorrected],
        [LinkID]
	FROM CRS_Demographic T with (nolock) 
	WHERE IsDeleted <> 2 AND AA8 = 14500
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	-- CCRS ADMIT ASSESS
--	UNION 
	SELECT AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(T.HospitalID, 0)) as [Hosp ID],
		'L - 01' AS [CareType],
		'T' AS [ICDType], 
		(SELECT top 1 DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber) AS [Inst],
		ChartNumber, 
		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [FullName],
		'' AS [EncounterNumber],
		'' AS [EncounterSequence],
		CONVERT(VarChar(10), A3, 111) AS [VisitDate],
		'' AS [VisitTime],
	        (select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc)) as [Del Coder],
        	(select top 1 convert(nvarchar(10), Updated, 111) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Date],
	        (select top 1 convert(nvarchar(5), Updated, 14) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		'' as [IsCorrected],
        [LinkID]
	FROM CRS_Demographic T with (nolock) 
	WHERE IsDeleted <> 2 AND AA8 = 14502
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	-- CCRS FULL ASSESS
--	UNION 
	SELECT AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(T.HospitalID, 0)) as [Hosp ID],
		'L - 02' AS [CareType],
		'T' AS [ICDType], 
		(SELECT top 1 DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber) AS [Inst],
		ChartNumber, 
		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [FullName],
		'' AS [EncounterNumber],
		'' AS [EncounterSequence],
		CONVERT(VarChar(10), A3, 111) AS [VisitDate],
		'' AS [VisitTime],
	        (select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc)) as [Del Coder],
        	(select top 1 convert(nvarchar(10), Updated, 111) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Date],
	        (select top 1 convert(nvarchar(5), Updated, 14) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		'' as [IsCorrected],
        [LinkID]
	FROM CRS_Demographic T with (nolock) 
	WHERE IsDeleted <> 2 AND AA8 = 14503
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	-- CCRS FULL ASSESS CHANGE
--	UNION 
	SELECT AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(T.HospitalID, 0)) as [Hosp ID],
		'L - 03' AS [CareType],
		'T' AS [ICDType], 
		(SELECT top 1 DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber) AS [Inst],
		ChartNumber, 
		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [FullName],
		'' AS [EncounterNumber],
		'' AS [EncounterSequence],
		CONVERT(VarChar(10), A3, 111) AS [VisitDate],
		'' AS [VisitTime],
	        (select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc)) as [Del Coder],
        	(select top 1 convert(nvarchar(10), Updated, 111) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Date],
	        (select top 1 convert(nvarchar(5), Updated, 14) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		'' as [IsCorrected],
        [LinkID]
	FROM CRS_Demographic T with (nolock) 
	WHERE IsDeleted <> 2 AND AA8 = 14504
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	-- CCRS FULL ASSESS CORRECT
--	UNION 
	SELECT AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(T.HospitalID, 0)) as [Hosp ID],
		'L - 04' AS [CareType],
		'T' AS [ICDType], 
		(SELECT top 1 DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber) AS [Inst],
		ChartNumber, 
		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [FullName],
		'' AS [EncounterNumber],
		'' AS [EncounterSequence],
		CONVERT(VarChar(10), A3, 111) AS [VisitDate],
		'' AS [VisitTime],
	        (select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc)) as [Del Coder],
        	(select top 1 convert(nvarchar(10), Updated, 111) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Date],
	        (select top 1 convert(nvarchar(5), Updated, 14) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		'' as [IsCorrected],
        [LinkID]
	FROM CRS_Demographic T with (nolock) 
	WHERE IsDeleted <> 2 AND AA8 = 14505
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	-- CCRS QUARTER ASSESS
--	UNION 
	SELECT AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(T.HospitalID, 0)) as [Hosp ID],
		'L - 05' AS [CareType],
		'T' AS [ICDType], 
		(SELECT top 1 DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber) AS [Inst],
		ChartNumber, 
		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [FullName],
		'' AS [EncounterNumber],
		'' AS [EncounterSequence],
		CONVERT(VarChar(10), A3, 111) AS [VisitDate],
		'' AS [VisitTime],
	        (select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc)) as [Del Coder],
        	(select top 1 convert(nvarchar(10), Updated, 111) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Date],
	        (select top 1 convert(nvarchar(5), Updated, 14) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		'' as [IsCorrected],
        [LinkID]
	FROM CRS_Demographic T with (nolock) 
	WHERE IsDeleted <> 2 AND AA8 = 14506
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	-- CCRS QUARTER ASSESS CHANGE/CORRECT
--	UNION 
	SELECT AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(T.HospitalID, 0)) as [Hosp ID],
		'L - 10' AS [CareType],
		'T' AS [ICDType], 
		(SELECT top 1 DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber) AS [Inst],
		ChartNumber, 
		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [FullName],
		'' AS [EncounterNumber],
		'' AS [EncounterSequence],
		CONVERT(VarChar(10), A3, 111) AS [VisitDate],
		'' AS [VisitTime],
	        (select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc)) as [Del Coder],
        	(select top 1 convert(nvarchar(10), Updated, 111) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Date],
	        (select top 1 convert(nvarchar(5), Updated, 14) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		'' as [IsCorrected],
        [LinkID]
	FROM CRS_Demographic T with (nolock) 
	WHERE IsDeleted <> 2 AND AA8 = 14511
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	-- CCRS DISCHARGE W/OUT RETURN
--	UNION 
	SELECT AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(T.HospitalID, 0)) as [Hosp ID],
		'L - 06' AS [CareType],
		'T' AS [ICDType], 
		(SELECT top 1 DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber) AS [Inst],
		ChartNumber, 
		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [FullName],
		'' AS [EncounterNumber],
		'' AS [EncounterSequence],
		CONVERT(VarChar(10), DischargeDate, 111) AS [VisitDate],
		'' AS [VisitTime],
	        (select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc)) as [Del Coder],
        	(select top 1 convert(nvarchar(10), Updated, 111) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Date],
	        (select top 1 convert(nvarchar(5), Updated, 14) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		'' as [IsCorrected],
        [LinkID]
	FROM CRS_Demographic T with (nolock) 
	WHERE IsDeleted <> 2 AND AA8 = 14507
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	-- CCRS DISCHARGE W/ RETURN
--	UNION 
	SELECT AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(T.HospitalID, 0)) as [Hosp ID],
		'L - 07' AS [CareType],
		'T' AS [ICDType], 
		(SELECT top 1 DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber) AS [Inst],
		ChartNumber, 
		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [FullName],
		'' AS [EncounterNumber],
		'' AS [EncounterSequence],
		CONVERT(VarChar(10), DischargeDate, 111) AS [VisitDate],
		'' AS [VisitTime],
	        (select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc)) as [Del Coder],
        	(select top 1 convert(nvarchar(10), Updated, 111) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Date],
	        (select top 1 convert(nvarchar(5), Updated, 14) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		'' as [IsCorrected],
        [LinkID]
	FROM CRS_Demographic T with (nolock) 
	WHERE IsDeleted <> 2 AND AA8 = 14508
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	-- CCRS DISCHARGE W/OUT ASSESSMENT
--	UNION 
	SELECT AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(T.HospitalID, 0)) as [Hosp ID],
		'L - 08' AS [CareType],
		'T' AS [ICDType], 
		(SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber) AS [Inst],
		ChartNumber, 
		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [FullName],
		'' AS [EncounterNumber],
		'' AS [EncounterSequence],
		CONVERT(VarChar(10), A3, 111) AS [VisitDate],
		'' AS [VisitTime],
	        (select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc)) as [Del Coder],
        	(select top 1 convert(nvarchar(10), Updated, 111) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Date],
	        (select top 1 convert(nvarchar(5), Updated, 14) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		'' as [IsCorrected],
        [LinkID]
	FROM CRS_Demographic T with (nolock) 
	WHERE IsDeleted <> 2 AND AA8 = 14509
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	-- CCRS RE-ENTRY
--	UNION 
	SELECT AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(T.HospitalID, 0)) as [Hosp ID],
		'L - 09' AS [CareType],
		'T' AS [ICDType], 
		(SELECT top 1 DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber) AS [Inst],
		ChartNumber, 
		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [FullName],
		'' AS [EncounterNumber],
		'' AS [EncounterSequence],
		CONVERT(VarChar(10), isnull(AB1b, AdmitDate), 111) AS [VisitDate],
		'' AS [VisitTime],
	        (select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc)) as [Del Coder],
        	(select top 1 convert(nvarchar(10), Updated, 111) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Date],
	        (select top 1 convert(nvarchar(5), Updated, 14) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		'' as [IsCorrected],
        [LinkID]
	FROM CRS_Demographic T with (nolock) 
	WHERE IsDeleted <> 2 AND AA8 = 14510
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	-- CCRS Update Record
--	UNION 
	SELECT AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(T.HospitalID, 0)) as [Hosp ID],
		'L - 17' AS [CareType],
		'T' AS [ICDType], 
		(SELECT top 1 DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber) AS [Inst],
		ChartNumber, 
		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [FullName],
		'' AS [EncounterNumber],
		'' AS [EncounterSequence],
		CONVERT(VarChar(10), z12, 111) AS [VisitDate],
		'' AS [VisitTime],
	        (select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc)) as [Del Coder],
        	(select top 1 convert(nvarchar(10), Updated, 111) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Date],
	        (select top 1 convert(nvarchar(5), Updated, 14) from CRS_UpdateHistory with (nolock) where AbstractID = T.AbstractID order by Updated desc) as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		'' as [IsCorrected],
        [LinkID]
	FROM CRS_Demographic T with (nolock) 
	WHERE IsDeleted <> 2 AND AA8 = 203626
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	-- OMHRS ADMISSION 
--	UNION 
	select AA.AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AA.HospitalID, 0)) as [Hosp ID],
		'M - 3' as [CareType],
		'T' as [ICDType], 
		(select top 1 DisplayCode from H_InstitutionProfile where Code = InstitutionNumber) as [Inst],
		ChartNumber, 
		isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') as [FullName],
		AA3 as [EncounterNumber],
		'' as [EncounterSequence],
		convert(varchar(10), A1, 111) as [VisitDate],
        	convert(varchar(5), AssessTime, 14) as [VisitTime],
        	(select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from OMHRS_UpdateHistory with (nolock) where AbstractID = AA.AbstractID order by Updated desc)) as [Del Coder],
        	(select top 1 convert(nvarchar(10), Updated, 111) from OMHRS_UpdateHistory with (nolock) where AbstractID = AA.AbstractID order by Updated desc) as [Del Date],
        	(select top 1 convert(nvarchar(5), Updated, 14) from OMHRS_UpdateHistory with (nolock) where AbstractID = AA.AbstractID order by Updated desc) as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		'' as [IsCorrected],
        [LinkID]
	from OMHRS_SecAA AA with (nolock) 
    	inner join OMHRS_RecInfo R with (nolock) on AA.AbstractID = R.AbstractID 
    	left outer join OMHRS_SecA A with (nolock) on AA.AbstractID = A.AbstractID          
	where IsDeleted <> 2 and Z1 = 200373
	and (isnull(AA.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(AA.HospitalID, 0) end)

	-- OMHRS SHORT STAY
--	UNION
	select AA.AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AA.HospitalID, 0)) as [Hosp ID],
		'M - 7' as [CareType],
		'T' as [ICDType], 
		(select top 1 DisplayCode from H_InstitutionProfile where Code = InstitutionNumber) as [Inst],
		ChartNumber, 
		isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') as [FullName],
		AA3 as [EncounterNumber],
		'' as [EncounterSequence],
		convert(varchar(10), A1, 111) as [VisitDate],
        	convert(varchar(5), AssessTime, 14) as [VisitTime],
	        (select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from OMHRS_UpdateHistory with (nolock) where AbstractID = AA.AbstractID order by Updated desc)) as [Del Coder],
        	(select top 1 convert(nvarchar(10), Updated, 111) from OMHRS_UpdateHistory with (nolock) where AbstractID = AA.AbstractID order by Updated desc) as [Del Date],
	        (select top 1 convert(nvarchar(5), Updated, 14) from OMHRS_UpdateHistory with (nolock) where AbstractID = AA.AbstractID order by Updated desc) as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		'' as [IsCorrected],
        [LinkID]
	from OMHRS_SecAA AA with (nolock) 
    	inner join OMHRS_RecInfo R with (nolock) on AA.AbstractID = R.AbstractID 
    	left outer join OMHRS_SecA A with (nolock) on AA.AbstractID = A.AbstractID          
	where IsDeleted <> 2 and Z1 = 200377
	and (isnull(AA.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(AA.HospitalID, 0) end)

	-- OMHRS QUARTERLY
--	UNION
	select AA.AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AA.HospitalID, 0)) as [Hosp ID],
		'M - 4' as [CareType],
		'T' as [ICDType], 
		(select top 1 DisplayCode from H_InstitutionProfile where Code = InstitutionNumber) as [Inst],
		ChartNumber, 
		isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') as [FullName],
		AA3 as [EncounterNumber],
		'' as [EncounterSequence],
		convert(varchar(10), A1, 111) as [VisitDate],
	        convert(varchar(5), AssessTime, 14) as [VisitTime],
	        (select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from OMHRS_UpdateHistory with (nolock) where AbstractID = AA.AbstractID order by Updated desc)) as [Del Coder],
	        (select top 1 convert(nvarchar(10), Updated, 111) from OMHRS_UpdateHistory with (nolock) where AbstractID = AA.AbstractID order by Updated desc) as [Del Date],
	        (select top 1 convert(nvarchar(5), Updated, 14) from OMHRS_UpdateHistory with (nolock) where AbstractID = AA.AbstractID order by Updated desc) as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		'' as [IsCorrected],
        [LinkID]
	from OMHRS_SecAA AA with (nolock) 
    	inner join OMHRS_RecInfo R with (nolock) on AA.AbstractID = R.AbstractID 
    	left outer join OMHRS_SecA A with (nolock) on AA.AbstractID = A.AbstractID          
	where IsDeleted <> 2 and Z1 = 200374
	and (isnull(AA.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(AA.HospitalID, 0) end)

	-- OMHRS CHANGE
--	UNION
	select AA.AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AA.HospitalID, 0)) as [Hosp ID],
		'M - 6' as [CareType],
		'T' as [ICDType], 
		(select top 1 DisplayCode from H_InstitutionProfile where Code = InstitutionNumber) as [Inst],
		ChartNumber, 
		isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') as [FullName],
		AA3 as [EncounterNumber],
		'' as [EncounterSequence],
		convert(varchar(10), A1, 111) as [VisitDate],
	        convert(varchar(5), AssessTime, 14) as [VisitTime],
	        (select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from OMHRS_UpdateHistory with (nolock) where AbstractID = AA.AbstractID order by Updated desc)) as [Del Coder],
	        (select top 1 convert(nvarchar(10), Updated, 111) from OMHRS_UpdateHistory with (nolock) where AbstractID = AA.AbstractID order by Updated desc) as [Del Date],
	        (select top 1 convert(nvarchar(5), Updated, 14) from OMHRS_UpdateHistory with (nolock) where AbstractID = AA.AbstractID order by Updated desc) as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		'' as [IsCorrected],
        [LinkID]
	from OMHRS_SecAA AA with (nolock) 
    	inner join OMHRS_RecInfo R with (nolock) on AA.AbstractID = R.AbstractID 
    	left outer join OMHRS_SecA A with (nolock) on AA.AbstractID = A.AbstractID          
	where IsDeleted <> 2 and Z1 = 200376
	and (isnull(AA.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(AA.HospitalID, 0) end)

	-- OMHRS DISCHARGE
--	UNION
	select AA.AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AA.HospitalID, 0)) as [Hosp ID],
		'M - 5' as [CareType],
		'T' as [ICDType], 
		(select top 1 DisplayCode from H_InstitutionProfile where Code = InstitutionNumber) as [Inst],
		ChartNumber, 
		isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') as [FullName],
		AA3 as [EncounterNumber],
		'' as [EncounterSequence],
		convert(varchar(10), A1, 111) as [VisitDate],
	        convert(varchar(5), AssessTime, 14) as [VisitTime],
        	(select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from OMHRS_UpdateHistory with (nolock) where AbstractID = AA.AbstractID order by Updated desc)) as [Del Coder],
	        (select top 1 convert(nvarchar(10), Updated, 111) from OMHRS_UpdateHistory with (nolock) where AbstractID = AA.AbstractID order by Updated desc) as [Del Date],
	        (select top 1 convert(nvarchar(5), Updated, 14) from OMHRS_UpdateHistory with (nolock) where AbstractID = AA.AbstractID order by Updated desc) as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		BatchYear,
		(select top 1 DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		'' as [IsCorrected],
        [LinkID]
	from OMHRS_SecAA AA with (nolock) 
    	inner join OMHRS_RecInfo R with (nolock) on AA.AbstractID = R.AbstractID 
    	left outer join OMHRS_SecA A with (nolock) on AA.AbstractID = A.AbstractID          
	where IsDeleted <> 2 and Z1 = 200375
	and (isnull(AA.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(AA.HospitalID, 0) end)

	-- TRANSCRIPITON
--	UNION
	SELECT TranscriptionID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(T.HospitalID, 0)) as [Hosp ID],
		'T' AS [CareType],
		'' AS [ICDType], 
		'' AS [Inst],
		ChartNumber, 
		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [FullName],
		'' AS [EncounterNumber],
		'' AS [EncounterSequence],
		convert(nvarchar(10), TranscriptionDate, 111) AS [VisitDate],
   		convert (nvarchar(5), TranscriptionTime, 14) AS [VisitTime],
	        (select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from UH_Main where AppID = 20 and RecordID = TranscriptionID order by Updated desc)) as [Del Coder],
       		(select top 1 convert(nvarchar(10), Updated, 111) from UH_Main where AppID = 20 and RecordID = TranscriptionID order by Updated desc) as [Del Date],
        	(select top 1 convert(nvarchar(5), Updated, 14) from UH_Main where AppID = 20 and RecordID = TranscriptionID order by Updated desc) as [Del Time],
		'' as [CIHIDateSent], 
		'' as BatchYear,
		'' as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		'' as [IsCompleted],
		'' as [IsValidated],
		'' as [IsSubmited],
		'' as [IsCorrected],
        0 as [LinkID]
	FROM CM_CPI with (nolock) INNER JOIN TR_Main T with (nolock) ON CM_CPI.PatientID = T.PatientID 
	WHERE T.IsDeleted <> 2
	AND (ISNULL(CM_CPI.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(CM_CPI.HospitalID, 0) end)

	-- CCO DISEASE REGISTRATION   PR - 03296
--	UNION 
	SELECT CRI.AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CDEMO.HospitalID, 0)) as [Hosp ID],
		'CC - DIS' AS [CareType],
		'' AS [ICDType], 
		'' AS [Inst],
		CDEMO.ChartNumber,
		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '')  AS [FullName],
		'' AS [EncounterNumber],
		DiseaseSequenceNum AS [EncounterSequence],
		CONVERT(VARCHAR(10), RegisterDate, 111) AS [VisitDate],
    		'' AS [VisitTime],
        	'' as [Del Coder],
        	'' as [Del Date],
        	'' as [Del Time],
		'' as [CIHIDateSent], 
		'' as BatchYear,
		'' as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		(select top 1 DisplayCode from LU_CIHICorrect where Code = IsCorrected) as [IsCorrected],
        [LinkID]
	FROM CC_RecordInfo CRI with (nolock) , CC_Demographic CDEMO with (nolock) , CC_DiseaseRegister CDISE with (nolock) 
    	WHERE IsDeleted <> 2 AND AppID = 675 and CRI.AbstractID = CDEMO.AbstractID and CDEMO.AbstractID = CDISE.AbstractID
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	-- CCO NDFP  PR - 03296
--	UNION 
	SELECT CRI.AbstractID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CDEMO.HospitalID, 0)) as [Hosp ID],
		'CC - NDFP' AS [CareType],
		'' AS [ICDType], 
		'' AS [Inst],
		CDEMO.ChartNumber,
		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '')  AS [FullName],
		'' AS [EncounterNumber],
		'' AS [EncounterSequence],
		'' AS [VisitDate],
    		'' AS [VisitTime],
        	'' as [Del Coder],
        	'' as [Del Date],
        	'' as [Del Time],
		'' as [CIHIDateSent], 
		'' as BatchYear,
		'' as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		(select top 1 DisplayCode from LU_CIHICorrect where Code = IsCorrected) as [IsCorrected],
        [LinkID]
	FROM CC_RecordInfo CRI with (nolock) , CC_Demographic CDEMO with (nolock) 
    	WHERE IsDeleted <> 2 AND AppID = 676 and CRI.AbstractID = CDEMO.AbstractID 
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

	-- CJRR: KNEE --SP-01071
--	UNION 
	SELECT CJRR_Abstract.RecordID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CJRR_Abstract.HospitalID, 0)) as [Hosp ID],
		'CJRR - K' as [CareType],
		'' as [ICDType], 
		(select top 1 DisplayCode from H_InstitutionProfile where Code = InstitutionNumber) as [Inst],
		ChartNumber,
		isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') as [FullName],
		'' as [EncounterNumber],
		'' as [EncounterSequence],
		convert(varchar(10), SurgeryDate, 111) as [VisitDate],
		'' AS [VisitTime],
    	(select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from CJRR_UpdateHistory with (nolock) where RecordID = CJRR_Abstract.RecordID order by Updated desc)) as [Del Coder],
        (select top 1 convert(nvarchar(10), Updated, 111) from CJRR_UpdateHistory with (nolock) where RecordID = CJRR_Abstract.RecordID order by Updated desc) as [Del Date],
        (select top 1 convert(nvarchar(5), Updated, 14) from CJRR_UpdateHistory with (nolock) where RecordID = CJRR_Abstract.RecordID order by Updated desc) as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		FiscalSurgeryYear,
		'' as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		(select top 1 DisplayCode from LU_CIHICorrect where Code = IsCorrected) as [IsCorrected],
        [LinkID]
	from CJRR_Abstract with (nolock) 
	where isnull(IsDeleted, 2) <> 2 and AppID = 40000
	and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
    order by [CareType]
	-- CJRR: HIP --SP-01071
	--UNION 
	SELECT CJRR_Abstract.RecordID, 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(CJRR_Abstract.HospitalID, 0)) as [Hosp ID],
		'CJRR - H' as [CareType],
		'' as [ICDType], 
		(select top 1 DisplayCode from H_InstitutionProfile where Code = InstitutionNumber) as [Inst],
		ChartNumber,
		isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') as [FullName],
		'' as [EncounterNumber],
		'' as [EncounterSequence],
		convert(varchar(10), SurgeryDate, 111) as [VisitDate],
		'' AS [VisitTime],
    	(select top 1 DisplayCode from U_Users where Code = (select top 1 Coder from CJRR_UpdateHistory with (nolock) where RecordID = CJRR_Abstract.RecordID order by Updated desc)) as [Del Coder],
        (select top 1 convert(nvarchar(10), Updated, 111) from CJRR_UpdateHistory with (nolock) where RecordID = CJRR_Abstract.RecordID order by Updated desc) as [Del Date],
        (select top 1 convert(nvarchar(5), Updated, 14) from CJRR_UpdateHistory with (nolock) where RecordID = CJRR_Abstract.RecordID order by Updated desc) as [Del Time],
		convert(nvarchar(10), CIHIDateSent, 111) as [CIHIDateSent], 
		FiscalSurgeryYear,
		'' as [BatchPeriod],
		'' as BatchNumber,
		'' as AbstractNumber,
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsCompleted) as [IsCompleted],
		(select top 1 DisplayCode from LU_AbstractStatus where Code = IsValidated) as [IsValidated],
		(select top 1 DisplayCode from LU_YesNoSystem where Code = IsSubmited) as [IsSubmited],
		(select top 1 DisplayCode from LU_CIHICorrect where Code = IsCorrected) as [IsCorrected],
        [LinkID]
	from CJRR_Abstract with (nolock) 
	where isnull(IsDeleted, 2) <> 2 and AppID = 40001
	and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)

	 --CLINIC
--	UNION
--	SELECT dbo.CR_Demographic.AbstractID, 
--		'C' AS [CareType],
--		'' AS [ICDType], 
--		(SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber) AS [Inst],
--		ChartNumber, 
--		ISNULL(LastName, '') + ', ' + ISNULL(FirstName, '') + ' ' + ISNULL(MiddleName, '') AS [FullName],
--		EncounterNumber,
--		EncounterSequence,
--		CONVERT(VarChar(10), AdmitDate, 111) AS [VisitDate],
--    		CONVERT (VARCHAR(5), AdmitTime, 14) AS [VisitTime]
--	FROM dbo.CR_Demographic LEFT OUTER JOIN dbo.CR_Visit ON dbo.CR_Demographic.AbstractID = dbo.CR_Visit.AbstractID
--	WHERE IsDeleted <> 2
    set nocount off
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EN-00183
CREATE PROCEDURE [L_PurgedPullList]
    @HospID  int,
    @PullListID  varchar(50),
    @LocationID  int,
    @TransactionDate datetime
AS 

    if @HospID is null set @HospID = 0

    select
        v.VolumeID as [ ], 
        isnull(ch.DisplayCode, '') as [Chart Hospital Link],
		REPLACE(SPACE(10 - LEN(c.ChartNumber)) + c.ChartNumber, ' ', '0') AS ChartNumber, 
		(select DisplayCode from LoanLU_VolumeType where Code = v.VolumeType) as [Volume Type], 
        vh.DisplayCode as [Volume Hospital Link],
		v.VolumeNumber AS [Volume], 
		ISNULL(c.LastName, '') + ', ' + ISNULL(c.FirstName, '') + ' ' + ISNULL(c.MiddleName, '') AS [Full Name], 
        isnull(D.DisplayCode, '') as [Expirted],
		CONVERT(VarChar(10), c.BirthDate, 111) AS [Birth Date], 
		cl.DisplayCode AS [Current Location],
        FL.DisplayCode AS [Previous Location], 
		PL.DisplayCode AS [Permanent Location],
        PullTime as [Require Time],
        LoanNote  as Notes,
        PullID,
        PullListStatus,
        isnull(B.DisplayCode, '') as [Borrower],
        Puller,
        isnull(LoanReason, '') as [Reason for Loan],
        c.LastVisitDate,
        v.VolumeDateFrom,
        v.VolumenDateTo,
        isnull(Digit.DisplayCode, '') as [Digital]  --TS-222

	FROM  dbo.CL_PullList_Purged p inner join 
        CM_CPI_Volume v ON v.VolumeID = p.VolumeID inner join
        dbo.CM_CPI c ON v.PatientID = c.PatientID LEFT OUTER JOIN
        dbo.LoanLU_Location CL ON v.CLCurrentLocation = CL.Code LEFT OUTER JOIN
        dbo.LoanLU_Location PL ON v.PermLocation = PL.Code LEFT OUTER JOIN
        dbo.LoanLU_Location FL ON v.CLPreviousLocation = FL.Code LEFT OUTER JOIN
        dbo.LoanLU_Location AL ON p.PullLocation = AL.Code LEFT OUTER JOIN

        H_HospitalProfile PH on p.HospitalID = PH.Code LEFT OUTER JOIN
        H_HospitalProfile CH on c.HospitalID = CH.Code LEFT OUTER JOIN
        H_HospitalProfile VH on v.HospitalID = VH.Code left join
        LU_YesNoSystem D on c.DeathIndicator = D.Code left join
        LoanLU_Borrower B on p.Puller = B.Code left join
        LU_YesNoSystem R on p.IsReturned = R.Code left join
        dbo.LoanLU_DigitalIndicator Digit on v.DigitalIndicator = Digit.code --TS-222
	Where (ISNULL(p.HospitalID, 0) = @HospID )
--      AND (ISNULL(v.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(v.HospitalID, 0) end)
--	    AND (ISNULL(c.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(c.HospitalID, 0) end)
        and p.PullListID = @PullListID  
        and p.PullLocation = @LocationID 
        and p.PullDate = @TransactionDate
    order by ChartNumber, VolumeNumber



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO



-- This is called by records that use Notes.
CREATE    PROCEDURE [L_REC_Notes]
	@AppID as int,
	@RecID as int
AS 

SELECT LogID, AppID, IsNull(FieldID, 0) as FieldID, RecordID, LogNote, LogDate, LogTime, LogCoder, (SELECT CIHIValue FROM U_Users WHERE Code = LogCoder) AS LogCoderU FROM REC_Notes WHERE AppID = @AppID AND RecordID = @RecID ORDER BY LogDate DESC, LogTime DESC



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE PROCEDURE [L_RegionProf]
AS 
	select h.*, m.PrivacyMessage from H_RegionProfile h left join H_RegionProfile_Message m on h.code = m.code


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [L_RehabData]
   @AppID int,
   @UserID int,
   @AbstractID int
AS 

set nocount on 

declare @sql nvarchar(1000)
declare @result varchar(50)
declare @LookUpDate varchar(10)

-- for multi-table record counts
declare @RH_DiagnosisCount int
declare @RH_ProviderCount int
declare @RH_ServiceInteruptCount int
declare @RH_ProjectCount int
declare @RH_InterventionCount int 

-- for cursor based on #UsersFields
declare @FieldID varchar(10)
declare @SystemName varchar(50)
declare @LookupTable varchar(100)    
declare @ParamProcID int
declare @DataType int
declare @SortOrder varchar(10)

create table #LoadResults 
(
    SortOrder int, 
    FieldID int, 
    Occurrence int,
    Code int,
    DisplayCode varchar(50),
    UserDescription varchar(255),
    CIHIValue varchar(50), 
    Validfrom datetime, 
    ValidTo datetime
)

select
    dbo.RH_ClientInfo.*, 
    
    dbo.RH_Demographic.Gender,          dbo.RH_Demographic.BirthDate,        dbo.RH_Demographic.BirthDateEstimated, 
    dbo.RH_Demographic.LanguageCode,    dbo.RH_Demographic.ResidenceCountry, dbo.RH_Demographic.PostalCode, 
    dbo.RH_Demographic.Province,        dbo.RH_Demographic.LivingSpouse,     dbo.RH_Demographic.LivingFamily,     
    dbo.RH_Demographic.LivingUnPaid,    dbo.RH_Demographic.LivingPaid,       dbo.RH_Demographic.LivingAlone,     
    dbo.RH_Demographic.LivingHospital,  dbo.RH_Demographic.LivingOther,      dbo.RH_Demographic.LivingTemp, dbo.RH_Demographic.LivingAcute, 
    dbo.RH_Demographic.LivingSetting,   dbo.RH_Demographic.InformalSupport,  dbo.RH_Demographic.PaidFullTime, 
    dbo.RH_Demographic.PaidPartTime,    dbo.RH_Demographic.PaidAdjusted,     dbo.RH_Demographic.UnPaidFullTime,   
    dbo.RH_Demographic.UnPaidPartTime,  dbo.RH_Demographic.UnPaidAdjusted,   dbo.RH_Demographic.StudentFullTime,  
    dbo.RH_Demographic.StudentPartTime, dbo.RH_Demographic.StudentAdjusted,  dbo.RH_Demographic.UnEmployed,       
    dbo.RH_Demographic.RetiredAge,      dbo.RH_Demographic.RetiredDisable,   dbo.RH_Demographic.VocationNone,    
    dbo.RH_Demographic.MaidenName,      dbo.RH_Demographic.LastName,         dbo.RH_Demographic.MiddleName, 
    dbo.RH_Demographic.FirstName,       dbo.RH_Demographic.AgeCode,          dbo.RH_Demographic.AgeNumber, dbo.RH_Demographic.LanguageISO,
    dbo.RH_Demographic.AboriginalStatus, dbo.RH_Demographic.ResidenceCode,

    dbo.RH_Activity.Eating,             dbo.RH_Activity.Grooming,            dbo.RH_Activity.Bathing, 
    dbo.RH_Activity.DressUpper,         dbo.RH_Activity.DressLower,          dbo.RH_Activity.Toileting, 
    dbo.RH_Activity.Bladder,            dbo.RH_Activity.Bowel,               dbo.RH_Activity.BedTransfer, 
    dbo.RH_Activity.ToiletTransfer,     dbo.RH_Activity.ShowerTransfer,      dbo.RH_Activity.Walk, 
    dbo.RH_Activity.WalkMode,           dbo.RH_Activity.Stairs,              dbo.RH_Activity.Comprehension, 
    dbo.RH_Activity.ComprehensionMode,  dbo.RH_Activity.Expression,          dbo.RH_Activity.ExpressionMode, 
    dbo.RH_Activity.SocialInteract,     dbo.RH_Activity.ProblemSolve,        dbo.RH_Activity.Memory, 
    dbo.RH_Activity.PainPresence,       dbo.RH_Activity.PainIntensity,       dbo.RH_Activity.PainImpact, 
    dbo.RH_Activity.MealPreparation,    dbo.RH_Activity.HouseworkLight,      dbo.RH_Activity.HouseworkHeavy, 
    dbo.RH_Activity.ImpairmentPresence, dbo.RH_Activity.VerbalCom,           dbo.RH_Activity.WrittenCom, 
    dbo.RH_Activity.AuditoryCom,        dbo.RH_Activity.ReadingCom,          dbo.RH_Activity.FinanceManage, 
    dbo.RH_Activity.Orientation,        dbo.RH_Activity.HealthStatus,        dbo.RH_Activity.HealthStatRespondent, 
    dbo.RH_Activity.PainScale, dbo.RH_Activity.GlassHear,
    
    dbo.RH_Administrative.AdmitClass,      dbo.RH_Administrative.ReAdmit,          dbo.RH_Administrative.PlanReAdmit, 
    dbo.RH_Administrative.ReadyAdmitKnown, dbo.RH_Administrative.ReadyAdmitDate,   dbo.RH_Administrative.DateReadyDischarge, 
    dbo.RH_Administrative.DischReason,     dbo.RH_Administrative.ReferredFrom,     dbo.RH_Administrative.ReferralProvince, 
    dbo.RH_Administrative.InstitutionFrom, dbo.RH_Administrative.ReferredTo,       dbo.RH_Administrative.ReferredProvince, 
    dbo.RH_Administrative.InstitutionTo,   dbo.RH_Administrative.TherapyDate,      dbo.RH_Administrative.RP_ProvincePlan, 
    dbo.RH_Administrative.RP_WCB_WSIB,     dbo.RH_Administrative.RP_OtherProvince, dbo.RH_Administrative.RP_Fed_DVA, 
    dbo.RH_Administrative.RP_Fed_FNIHB,    dbo.RH_Administrative.RP_Fed_Other,     dbo.RH_Administrative.RP_CanadaSelf, 
    dbo.RH_Administrative.RP_CanadaInsure, dbo.RH_Administrative.RP_OtherSelf,     dbo.RH_Administrative.RP_ProvinceDefinition, 
    --ED - 02265, ED - 02266
    dbo.RH_Administrative.PrimaryReasonWaiting, dbo.RH_Administrative.SecondaryReasonWaiting,
    
    dbo.RH_FollowUpAssess.LivingQuarters,  dbo.RH_FollowUpAssess.Community,        dbo.RH_FollowUpAssess.TownTrips, 
    dbo.RH_FollowUpAssess.SelfCare,        dbo.RH_FollowUpAssess.WorkActivity,     dbo.RH_FollowUpAssess.Recreational, 
    dbo.RH_FollowUpAssess.SocialActivity,  dbo.RH_FollowUpAssess.FamilyRole,       dbo.RH_FollowUpAssess.PersonalRelation, 
    dbo.RH_FollowUpAssess.PersonalComfort, dbo.RH_FollowUpAssess.LifeEvents, 
    
    dbo.RH_Health.ClientGroup,             dbo.RH_Health.ASIAScale,                dbo.RH_Health.DateOnset, 
    dbo.RH_Health.Height,                  dbo.RH_Health.Weight,                   dbo.RH_Health.HospDischarge, 
    dbo.RH_Health.HospDays,                dbo.RH_Health.WrittenConditionMain,     dbo.RH_Health.WrittenCondition1, 
    dbo.RH_Health.WrittenCondition2,       dbo.RH_Health.WrittenCondition3,        dbo.RH_Health.WrittenConditionTrans, 
    
    dbo.RH_Rehabilitation.ST_Screening,    dbo.RH_Rehabilitation.SD_Screening,     dbo.RH_Rehabilitation.ST_Initial, 
    dbo.RH_Rehabilitation.SD_Initial,      dbo.RH_Rehabilitation.ST_ReAssess,      dbo.RH_Rehabilitation.SD_ReAssess, 
    dbo.RH_Rehabilitation.ST_Planning,     dbo.RH_Rehabilitation.SD_Planning,      dbo.RH_Rehabilitation.ST_Cognitive, 
    dbo.RH_Rehabilitation.SD_Cognitive,    dbo.RH_Rehabilitation.ST_Communicate,   dbo.RH_Rehabilitation.SD_Communicate, 
    dbo.RH_Rehabilitation.ST_Nutrition,    dbo.RH_Rehabilitation.SD_Nutrition,     dbo.RH_Rehabilitation.ST_Physical, 
    dbo.RH_Rehabilitation.SD_Physical,     dbo.RH_Rehabilitation.ST_PsychoSocial,  dbo.RH_Rehabilitation.SD_PsychoSocial, 
    dbo.RH_Rehabilitation.ST_Vocational,   dbo.RH_Rehabilitation.SD_Vocational,    dbo.RH_Rehabilitation.ST_Manual, 
    dbo.RH_Rehabilitation.SD_Manual,       dbo.RH_Rehabilitation.ST_Modalities,    dbo.RH_Rehabilitation.SD_Modalities, 
    dbo.RH_Rehabilitation.ST_Injections,   dbo.RH_Rehabilitation.SD_Injections,    dbo.RH_Rehabilitation.ST_Social, 
    dbo.RH_Rehabilitation.SD_Social,       dbo.RH_Rehabilitation.ST_Equipment,     dbo.RH_Rehabilitation.SD_Equipment, 
    dbo.RH_Rehabilitation.ST_Education,    dbo.RH_Rehabilitation.SD_Education,     dbo.RH_Rehabilitation.ST_Consultation, 
    dbo.RH_Rehabilitation.SD_Consultation, 

    dbo.RH_Ancillary.AncillaryField1,  dbo.RH_Ancillary.AncillaryField2,  dbo.RH_Ancillary.AncillaryField3, 
    dbo.RH_Ancillary.AncillaryField4,  dbo.RH_Ancillary.AncillaryField5,  dbo.RH_Ancillary.AncillaryField6, 
    dbo.RH_Ancillary.AncillaryField7,  dbo.RH_Ancillary.AncillaryField8,  dbo.RH_Ancillary.AncillaryField9, 
    dbo.RH_Ancillary.AncillaryField10, dbo.RH_Ancillary.AncillaryField11, dbo.RH_Ancillary.AncillaryField12, 
    dbo.RH_Ancillary.AncillaryField13, dbo.RH_Ancillary.AncillaryField14, dbo.RH_Ancillary.AncillaryField15, 
    dbo.RH_Ancillary.AncillaryField16, dbo.RH_Ancillary.AncillaryField17, 

    dbo.RH_BasicOption.BasicOption1,  dbo.RH_BasicOption.BasicOption2,  dbo.RH_BasicOption.BasicOption3, 
    dbo.RH_BasicOption.BasicOption4,  dbo.RH_BasicOption.BasicOption5,  dbo.RH_BasicOption.BasicOption6, 
    dbo.RH_BasicOption.BasicOption7,  dbo.RH_BasicOption.BasicOption8,  dbo.RH_BasicOption.BasicOption9, 
    dbo.RH_BasicOption.BasicOption10, dbo.RH_BasicOption.BasicOption11, dbo.RH_BasicOption.BasicOption12, 
    dbo.RH_BasicOption.BasicOption13, dbo.RH_BasicOption.BasicOption14, dbo.RH_BasicOption.BasicOption15, 
    dbo.RH_BasicOption.BasicOption16, dbo.RH_BasicOption.BasicOption17, dbo.RH_BasicOption.BasicOption18, 
    dbo.RH_BasicOption.BasicOption19, 

    dbo.RH_UDAbstracting.UDDate1,    dbo.RH_UDAbstracting.UDDate2,    dbo.RH_UDAbstracting.UDDate3, 
    dbo.RH_UDAbstracting.UDDate4,    dbo.RH_UDAbstracting.UDDate5,    dbo.RH_UDAbstracting.UDTime1,    dbo.RH_UDAbstracting.UDTime2, 
    dbo.RH_UDAbstracting.UDTime3,    dbo.RH_UDAbstracting.UDTime4,    dbo.RH_UDAbstracting.UDTime5,    dbo.RH_UDAbstracting.UDLookup1, 
    dbo.RH_UDAbstracting.UDLookup2,  dbo.RH_UDAbstracting.UDLookup3,  dbo.RH_UDAbstracting.UDLookup4,  dbo.RH_UDAbstracting.UDLookup5, 
    dbo.RH_UDAbstracting.UDInteger1, dbo.RH_UDAbstracting.UDInteger2, dbo.RH_UDAbstracting.UDInteger3, 
    dbo.RH_UDAbstracting.UDInteger4, dbo.RH_UDAbstracting.UDInteger5, dbo.RH_UDAbstracting.UDText1,    dbo.RH_UDAbstracting.UDText2, 
    dbo.RH_UDAbstracting.UDText3,    dbo.RH_UDAbstracting.UDText4, dbo.RH_UDAbstracting.UDText5, dbo.RH_UDAbstracting.UDSmallText1,    dbo.RH_UDAbstracting.UDSmallText2, 
    dbo.RH_UDAbstracting.UDSmallText3,    dbo.RH_UDAbstracting.UDSmallText4, dbo.RH_UDAbstracting.UDSmallText5

	--EN-00524
	,[UDDate6],[UDDate7],[UDDate8],[UDDate9],[UDDate10]
	,[UDDate11],[UDDate12],[UDDate13],[UDDate14],[UDDate15]
	,[UDDate16],[UDDate17],[UDDate18],[UDDate19],[UDDate20]
	,[UDDate21],[UDDate22],[UDDate23],[UDDate24],[UDDate25]
	,[UDTime6],[UDTime7],[UDTime8],[UDTime9],[UDTime10]
	,[UDTime11],[UDTime12],[UDTime13],[UDTime14],[UDTime15]
	,[UDTime16],[UDTime17],[UDTime18],[UDTime19],[UDTime20]
	,[UDTime21],[UDTime22],[UDTime23],[UDTime24],[UDTime25]
	,[UDLookUp6],[UDLookUp7],[UDLookUp8],[UDLookUp9],[UDLookUp10]
	,[UDLookUp11],[UDLookUp12],[UDLookUp13],[UDLookUp14],[UDLookUp15]
	,[UDLookUp16],[UDLookUp17],[UDLookUp18],[UDLookUp19],[UDLookUp20]
	,[UDLookUp21],[UDLookUp22],[UDLookUp23],[UDLookUp24],[UDLookUp25]
	,[UDInteger6],[UDInteger7],[UDInteger8],[UDInteger9],[UDInteger10]
	,[UDInteger11],[UDInteger12],[UDInteger13],[UDInteger14],[UDInteger15]
	,[UDInteger16],[UDInteger17],[UDInteger18],[UDInteger19],[UDInteger20]
	,[UDInteger21],[UDInteger22],[UDInteger23],[UDInteger24],[UDInteger25]
	,[UDText6],[UDText7],[UDText8],[UDText9],[UDText10]
	,[UDText11],[UDText12],[UDText13],[UDText14],[UDText15]
	,[UDText16],[UDText17],[UDText18],[UDText19],[UDText20]
	,[UDText21],[UDText22],[UDText23],[UDText24],[UDText25]
	,[UDSmallText6],[UDSmallText7],[UDSmallText8],[UDSmallText9],[UDSmallText10]
	,[UDSmallText11],[UDSmallText12],[UDSmallText13],[UDSmallText14],[UDSmallText15]
	,[UDSmallText16],[UDSmallText17],[UDSmallText18],[UDSmallText19],[UDSmallText20]
	,[UDSmallText21],[UDSmallText22],[UDSmallText23],[UDSmallText24],[UDSmallText25]
    --292-0012
    , TherapyTimeOT, TherapyTimePT, TherapyTimeSLP, TherapyTimeOTA, TherapyTimePTA, TherapyTimeCDA
    
into #ABMainTemp
from dbo.RH_ClientInfo 
left join dbo.RH_Demographic    on dbo.RH_ClientInfo.AbstractID = dbo.RH_Demographic.AbstractID 
left join dbo.RH_Activity       on dbo.RH_ClientInfo.AbstractID = dbo.RH_Activity.AbstractID 
left join dbo.RH_Administrative on dbo.RH_ClientInfo.AbstractID = dbo.RH_Administrative.AbstractID 
left join dbo.RH_FollowUpAssess on dbo.RH_ClientInfo.AbstractID = dbo.RH_FollowUpAssess.AbstractID 
left join dbo.RH_Health         on dbo.RH_ClientInfo.AbstractID = dbo.RH_Health.AbstractID 
left join dbo.RH_Rehabilitation on dbo.RH_ClientInfo.AbstractID = dbo.RH_Rehabilitation.AbstractID 
left join dbo.RH_UDAbstracting  on dbo.RH_ClientInfo.AbstractID = dbo.RH_UDAbstracting.AbstractID
left join dbo.RH_Ancillary      on dbo.RH_ClientInfo.AbstractID = dbo.RH_Ancillary.AbstractID
left join dbo.RH_BasicOption    on dbo.RH_ClientInfo.AbstractID = dbo.RH_BasicOption.AbstractID
left join dbo.RH_Therapy on dbo.RH_ClientInfo.AbstractID = dbo.RH_Therapy.AbstractID --292-0012
left join dbo.RH_UDFieldsDate on dbo.RH_ClientInfo.AbstractID = dbo.RH_UDFieldsDate.AbstractID --EN-00524
left join dbo.RH_UDFieldsTime on dbo.RH_ClientInfo.AbstractID = dbo.RH_UDFieldsTime.AbstractID --EN-00524
left join dbo.RH_UDFieldsLookUp on dbo.RH_ClientInfo.AbstractID = dbo.RH_UDFieldsLookUp.AbstractID --EN-00524
left join dbo.RH_UDFieldsInteger on dbo.RH_ClientInfo.AbstractID = dbo.RH_UDFieldsInteger.AbstractID --EN-00524
left join dbo.RH_UDFieldsText on dbo.RH_ClientInfo.AbstractID = dbo.RH_UDFieldsText.AbstractID --EN-00524
left join dbo.RH_UDFieldsSmallText on dbo.RH_ClientInfo.AbstractID = dbo.RH_UDFieldsSmallText.AbstractID --EN-00524

where dbo.RH_ClientInfo.AbstractID = @AbstractID


select * into #RH_Diagnosis from RH_Diagnosis where AbstractID = @AbstractID -- ParamProcID = 9
set @RH_DiagnosisCount = @@rowcount
select * into #RH_Provider from RH_Provider where AbstractID = @AbstractID   -- ParamProcID = 8
set @RH_ProviderCount = @@rowcount
select * into #RH_ServiceInterupt from RH_ServiceInterupt where AbstractID = @AbstractID -- ParamProcID = 10
set @RH_ServiceInteruptCount = @@rowcount
select * into #RH_Project from RH_Project where AbstractID = @AbstractID -- ParamProcID = 15
set @RH_ProjectCount = @@rowcount
select * into #RH_Invervention from RH_Intervention where AbstractID = @AbstractID -- ParamProcID = 15
set @RH_InterventionCount = @@rowcount

select 
    dbo.U_Fields.FieldID, 
    dbo.U_Fields.SystemName, 
    dbo.U_UsersFields.LookUpTable, 
    dbo.U_UsersFields.ParamProcID, 
    dbo.U_UsersFields.DataType, 
    dbo.U_UsersFields.SortOrder 
into #UsersFields
from dbo.U_Fields 
join dbo.U_UsersFields on dbo.U_Fields.FieldID = dbo.U_UsersFields.FieldID
where dbo.U_UsersFields.UserID = @UserID 
and dbo.U_UsersFields.AppID = @Appid 
and dbo.U_Fields.IsGroup = 0
and dbo.U_UsersFields.DataType <> 100000 
and dbo.U_Fields.FieldID not between 60000 and 70000
order by dbo.U_UsersFields.SortOrder, dbo.U_UsersFields.FieldID

update #UsersFields set LookupTable = 'LU_ProviderService'   where LookupTable = 'LLU_ProviderServices'
update #UsersFields set LookupTable = 'LU_ProviderSpecialty' where LookupTable = 'LLU_ProviderSpecialty'
update #UsersFields set LookupTable = 'LU_CodeFile'          where isnumeric(LookupTable) = 1
update #UsersFields set LookupTable = 'ICD_DiagFile10'       where DataType = 60
update #UsersFields set LookupTable = 'ICD_ProcFile10'       where DataType = 61
--PR - 03570
update #UsersFields set LookupTable = 'ICD_DiagFileNRS'       where DataType = 71

--select @LookUpDate = convert(varchar(10), AdmitDate, 101) from RH_ClientInfo where AbstractID = @AbstractID
--PR-03478
if @AppID in (251, 253)
	--PR - 03570
    --select @LookUpDate = convert(varchar(10), DischargeDate, 101) from RH_ClientInfo where AbstractID = @AbstractID
	select @LookUpDate = convert(varchar(10), isnull(DischargeDate, Admitdate), 101) from RH_ClientInfo where AbstractID = @AbstractID

if @AppID = 252
	--PR - 03570
	--select @LookUpDate = convert(varchar(10), FollowUpDate, 101) from RH_ClientInfo where AbstractID = @AbstractID
	select @LookUpDate = convert(varchar(10), isnull(isnull(FollowUpDate, DischargeDate), AdmitDate), 101) from RH_ClientInfo where AbstractID = @AbstractID
	
--PR-03570
if @LookUpDate is null select @LookUpDate = convert(varchar(10), AdmitDate, 101) from RH_ClientInfo where AbstractID = @AbstractID
if @LookUpDate is null set @LookUpDate = convert(varchar(10), getdate(), 101)  --PR - 03570 '2002/10/01'
--EN - 405
declare @RehabSubDate datetime
set @RehabSubDate = (select top 1 RehabSubDate from h_institutionprofile 
    where code = (select top 1 institutionnumber from rh_clientinfo where abstractid = @AbstractID))

--PR - 04581
declare @UpdateDate datetime
declare @UpdateYear int, @LookUpYear int, @UpdateYear_Org int
set @UpdateDate = (select max(Updated) from dbo.RH_UpdateHistory where AbstractID = @AbstractID and UpdateType = 'Saved' and coder not in (55555, 77777, 88888, 99999))
set @UpdateYear = datepart(year, @UpdateDate) - (case when datepart(month, @UpdateDate) in (1, 2, 3) then 1 else 0 end)
set @UpdateYear_Org = datepart(year, @UpdateDate)
set @LookUpYear = datepart(year, cast(@LookUpDate as datetime)) - (case when datepart(month, cast(@LookUpDate as datetime)) in (1, 2, 3) then 1 else 0 end)

if @RehabSubDate is not null and @UpdateDate > cast(@LookUpDate as datetime) and @UpdateDate >= cast('2008/05/15' as datetime)
begin
    If @LookUpYear < @UpdateYear 
        If DateDiff(day, cast(cast(@UpdateYear_Org  as varchar(10)) + '/05/15' as datetime), cast(@UpdateDate as datetime)) >= 0 Or
            DateDiff(day, cast(cast(@UpdateYear_Org as varchar(10)) + '/04/01' as datetime), cast(@UpdateDate as datetime)) < 0 
            set @LookUpDate = convert(varchar(10), @UpdateDate, 111)
        else if DateDiff(day, cast(cast(@UpdateYear_Org  as varchar(10)) + '/04/01' as datetime), @UpdateDate) >= 0
        begin
			set @UpdateYear = @UpdateYear - 1
            If @LookUpYear < @UpdateYear 
                set @LookUpDate = cast(@UpdateYear_Org as varchar(10)) + '/03/31'    --Two fiscal year early assessment
        End 
end    
    
--if @RehabSubDate is not null
--begin
--    if  @RehabSubDate > cast(@LookUpDate as datetime)
--        set @LookUpDate = convert(varchar(10), @RehabSubDate, 101)
--end

declare cur cursor fast_forward for
    select FieldID, SystemName, LookUpTable, ParamProcID, DataType, SortOrder
    from #UsersFields
    where FieldID <> 2  --2012/07/26 The LinkID is ahead of AbstractID
open cur

fetch next from cur into @FieldID, @SystemName, @LookupTable, @ParamProcID, @DataType, @SortOrder
--fetch next from cur into @FieldID, @SystemName, @LookupTable, @ParamProcID, @DataType, @SortOrder --Disable it because we don't need to skip abstractid.

while @@fetch_status = 0 begin
    set @sql = ''

    if @ParamProcID = 9 begin
        if isnull(@LookupTable, '') = '' and @RH_DiagnosisCount > 0  
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', DiagnosisOccurrence, null, null, UserDescription = ' + @SystemName + ', null, null, null from #RH_Diagnosis'
        else if @RH_DiagnosisCount > 0 
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', DiagnosisOccurrence, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo from #RH_Diagnosis t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code'
    end
    else if @ParamProcID = 8 begin
       if isnull(@LookupTable, '') = '' and @RH_ProviderCount > 0
           set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', ProviderOccurrence, null, null, UserDescription = ' + @SystemName + ', null, null, null from #RH_Provider'
       else if @RH_ProviderCount > 0
           set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', ProviderOccurrence, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo from #RH_Provider t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code'
    end
    else if @ParamProcID = 10 begin
        if isnull(@LookupTable, '') = '' and @RH_ServiceInteruptCount > 0
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', InteruptOccurrence, null, null, UserDescription = ' + @SystemName + ', null, null, null from #RH_ServiceInterupt'
        else if @RH_ServiceInteruptCount > 0            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', InteruptOccurrence, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo from #RH_ServiceInterupt t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code'
    end
    else if @ParamProcID = 15 begin
        if isnull(@LookupTable, '') = '' and @RH_ProjectCount > 0 
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', ProjectOccurrence, null, null, UserDescription = ' + @SystemName + ', null, null, null from #RH_Project'
        else if @RH_ProjectCount > 0             set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', ProjectOccurrence, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo from #RH_Project t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code'
    end
    else if @ParamProcID = 17 begin
        if isnull(@LookupTable, '') = '' and @RH_InterventionCount > 0 
            set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', IntervOccurrence, null, null, UserDescription = ' + @SystemName + ', null, null, null from #RH_Invervention'
        else if @RH_InterventionCount > 0             set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', IntervOccurrence, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo from #RH_Invervention t left join ' + @LookupTable + ' l on t.' + @SystemName + ' = l.Code'
    end
    else begin
        if isnull(@LookupTable, '') = '' begin
            if @SystemName <> 'AbstractNotes' 
                set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', 0, null, null, UserDescription = ' + @SystemName + ', null, null, null from #ABMainTemp'
        end
        else if @SystemName = 'PostalCode' begin
            set @sql = 'select @result =  ' + @SystemName + ' from #ABMainTemp'
            exec sp_executesql @sql, N'@result varchar(50) output', @result output
            set @sql = ''
            
            if isnull(@result, '') <> '' begin
                set @sql = 
                    'select top 1 ' + @SortOrder + ', ' + @FieldID + ', 0, Code, ''' + left(@result, 3) + ' ' + substring(@result, 4, 3) + ''', UserDescription, ''' + @result + ''', ValidFrom, ValidTo ' + 
                    'from LU_PostalCode ' + 
                    'where ''' + @LookUpDate + ''' between ValidFrom and ValidTo ' + 
                    'and CIHIValue in ( ' + 
                        '''' + left(@result, 6) + ''', ' + 
                        '''' + left(@result, 5) + ''', ' + 
                        '''' + left(@result, 4) + ''', ' + 
                        '''' + left(@result, 3) + ''', ' +
                        '''' + left(@result, 2) + ''', ' + 
                        '''' + left(@result, 1) + ''') ' +
                    'order by len(CIHIValue) desc'
            end
        end
        else begin
            set @sql = 'select @result = ' + @SystemName + ' from #ABMainTemp'
            exec sp_executesql @sql, N'@result varchar(50) output', @result output
            set @sql = ''

            if isnull(@result, '') <> '' 
                set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', 0, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo from ' + @LookupTable + ' where Code = ' + @result + ' '
        end
    end
   
    if len(@sql) > 0 
        insert into #LoadResults (SortOrder, FieldID, Occurrence, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo) exec (@sql)

    fetch next from cur into @FieldID, @SystemName, @LookupTable, @ParamProcID, @DataType, @SortOrder
end

close cur
deallocate cur

update #LoadResults 
set Code = 0
, Displaycode = NULL
, UserDescription = NULL
, CIHIValue = NULL 
where (ValidTo < cast(@LookUpDate as datetime) or Validfrom > cast(@LookUpDate as datetime))

update #LoadResults 
set UserDescription = convert(varchar(20), cast(UserDescription as datetime), 120) 
where isdate(UserDescription) = 1 
and len(UserDescription) > 10

set nocount off

select FieldID, Occurrence, Code, DisplayCode, UserDescription, CIHIValue 
from #LoadResults 
order by SortOrder, Occurrence

return 0

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- This is called by the Print & Mail routines to get the Distribution list
CREATE  PROCEDURE [L_ReportDistribution]
	@Key AS INT
AS 

SELECT Printers, EMailAddress, ISNULL(PrintCopy, 0) as PrintCopy FROM LLU_ReportDistribution WHERE [Code] = @Key



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO







CREATE    PROCEDURE [L_Reports]
	@AppID as int,
	@RoleID as int,
	@InstNo as int,
	@HospID as int = 0 --NP-00025
AS
	Declare @VDate as datetime
	If @Appid = 0
		Set @Appid = 2

	Set @VDate = getdate()
	select Code, UserDescription, ReportPath, AutoLaunch, AutoLaunchLoad, DistributeKey, IsInterface, InterfaceID
	from LU_Reports
	where AppID = @AppID 
	and @VDate between ValidFrom and ValidTo
	and (isnull(RoleID, 0) = 0 or RoleID = @RoleID)
	and (isnull(InstitutionNumber, 0) = 0 or InstitutionNumber = @InstNo)
	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)  --NP-00025


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO






-- This is called by the Load Method of the ROI Control
CREATE PROCEDURE [L_ROI]
	@Key as int
AS 
SELECT * FROM ROI_Main WHERE ROIID = @Key
SELECT * FROM ROI_Actions WHERE ROIID = @Key ORDER BY OccurrenceNumber
SELECT * FROM ROI_Document WHERE ROIID = @Key ORDER BY OccurrenceNumber
SELECT * FROM ROI_SentItems WHERE ROIID = @Key ORDER BY OccurrenceNumber
SELECT * FROM ROI_Payments WHERE ROIID = @Key ORDER BY OccurrenceNumber
select * from ROI_UserDefined where ROIID = @Key
select * from ROI_RequesterInfo where ROIID = @Key --EN-00274

select * from ROI_UDFieldsDate where ROIID = @Key
select * from ROI_UDFieldsTime where ROIID = @Key
select * from ROI_UDFieldsLookUp where ROIID = @Key
select * from ROI_UDFieldsInteger where ROIID = @Key
select * from ROI_UDFieldsText where ROIID = @Key
select * from ROI_UDFieldsSmallText where ROIID = @Key
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This is called by the Load Method of the Schedule Control
CREATE PROCEDURE [L_SchedAppnt]
	@Key as int
AS 
SELECT * FROM SH_Appointments WHERE AppointmentID = @Key



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE     PROCEDURE [L_Schedule]
	@Provider as int,
	@AppDate as VarChar(10)
AS
	Declare @Interval as int
	Declare @StartTime as datetime
	Declare @TempTime as datetime
	Declare @FinishTime as datetime
	Declare @LunchStart as DateTime
	Declare @LunchFinish as DateTime
	
	SELECT AppointmentID, AppointmentTime, isnull(LastName, '') + ', ' + isnull(FirstName, '') AS Patient, Duration
	Into #AppointmentTemp
	FROM SH_Appointments LEFT OUTER JOIN CM_CPI ON dbo.SH_Appointments.Patientid = dbo.CM_CPI.PatientID
	WHERE (ProviderNumber = @Provider) AND (AppointmentDate = @AppDate)

	Declare Cur_TempSched cursor for
	SELECT  StartTime, FinishTime, isnull(IntervalLen, 0), BreakTime, DATEADD(mi, BreakLen-1, BreakTime)
	FROM dbo.LLU_Provider_Schedule LEFT OUTER JOIN
	dbo.LU_CodeFile ON dbo.LLU_Provider_Schedule.SchedDay = dbo.LU_CodeFile.Code
	WHERE (dbo.LU_CodeFile.DefaultDescription = DATENAME(dw, @AppDate)) AND (dbo.LLU_Provider_Schedule.ProviderID = @Provider)
	Open Cur_TempSched
	fetch next from Cur_TempSched
	into @StartTime, @FinishTime, @Interval, @Lunchstart, @LunchFinish
	while @@fetch_status = 0
	begin
		Set @TempTime = @StartTime
		While @TempTime <= @FinishTime
		Begin
			Insert into #AppointmentTemp Values (0, @TempTime, '', '')
			Set @TempTime = DATEADD(mi, @Interval,@TempTime)
		End
		Update #AppointmentTemp set appointmentid = -1, Patient = 'Busy' where appointmenttime between @LunchStart and @LunchFinish and appointmentid = 0
		fetch next from Cur_TempSched into @StartTime, @FinishTime, @Interval, @Lunchstart, @LunchFinish
	end
	Close Cur_TempSched
	Deallocate Cur_TempSched

	Delete #AppointmentTemp where Appointmenttime in (select appointmenttime from #AppointmentTemp
	Group by appointmenttime having count(appointmenttime) > 1) and appointmentid = 0
	Select AppointmentID, convert(varchar(5), AppointmentTime, 108) as [Time], cast(Duration as varchar(6)) as [Min.], Patient from #AppointmentTemp order by AppointmentTime



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE  PROCEDURE [L_Trans_WordMerge]
	@TranscriptionID as Int
AS
SELECT     dbo.AB_Abstract.AdmitDate AS AdmissionDate, dbo.AB_Abstract.AdmitTime AS AdmissionTime, dbo.CM_CPI.AlternateAddress, 
                      Lookup6.DisplayCode AS AgeCode, Lookup6.UserDescription AS AgeCodeDesc, dbo.AB_Abstract.AgeNumber, 
                      LU_Provider_3.UserDescription AS AttendingPhysican, LU_Provider_3.ProvdrAddress AS AttendingPhyAddress, 
                      LU_Provider_3.ProvdrCity AS AttendingPhyCity, LU_Provider_3.ProvdrCredentials AS AttendingPhyCredentials, 
                      LU_Provider_3.TransInitials AS AttendingPhyInitials, LU_Provider_3.ProvdrPostal AS AttendingPhyPostal, 
                      LU_Provider_3.ProvdrProvince AS AttendingPhyProvince, LU_Provider_3.ProvdrTitle AS AttendingPhyTitle, dbo.AB_Abstract.BirthDate, 
                      dbo.CM_CPI.BirthPlace, dbo.AB_Abstract.ChartNumber, dbo.ICD_DiagFile10.DisplayCode AS DiagnosisMostResp, 
                      dbo.ICD_DiagFile10.UserDescription AS DiagnosisMostRespDesc, dbo.TR_Main.DictationDate, dbo.TR_Main.DictationTime, 
                      LU_Provider_2.UserDescription AS DictatingPhysician, DocumentName, LU_Provider_2.ProvdrAddress AS DictatingPhyAddress, 
                      LU_Provider_2.ProvdrCity AS DictatingPhyCity, LU_Provider_2.ProvdrCredentials AS DictatingPhyCredentials, 
                      LU_Provider_2.TransInitials AS DictatingPhyInitials, LU_Provider_2.ProvdrPostal AS DictatingPhyPostal, 
                      LU_Provider_2.ProvdrProvince AS DictatingPhyProvince, LU_Provider_2.ProvdrTitle AS DictatingPhyTitle, dbo.AB_Abstract.DischargeDate, 
                      dbo.AB_Abstract.DischargeTime, dbo.AB_Abstract.EncounterNumber, dbo.AB_Abstract.FirstName, dbo.AB_Abstract.HCNVersion, 
                      dbo.AB_Abstract.HealthCareNumber, dbo.ICD_ProcFile10.DisplayCode AS InterventionCode, 
                      dbo.ICD_ProcFile10.UserDescription AS InterventionCodeDesc, dbo.AB_Intervention.IntervDate AS InterventionDate, dbo.AB_Abstract.LastName, 
                      dbo.LU_PatientService.DisplayCode AS MainPatientService, dbo.LU_PatientService.UserDescription AS MainPatientServiceDesc, 
                      LU_Provider_1.UserDescription AS MainPhysician, LU_Provider_1.ProvdrAddress AS MainPhyAddress, LU_Provider_1.ProvdrCity AS MainPhyCity, 
                      LU_Provider_1.ProvdrCredentials AS MainPhyCredentials, LU_Provider_1.TransInitials AS MainPhyInitials, 
                      LU_Provider_1.ProvdrPostal AS MainPhyPostal, LU_Provider_1.ProvdrProvince AS MainPhyProvince, LU_Provider_1.ProvdrTitle AS MainPhyTitle, 
                      dbo.AB_Abstract.MiddleName, dbo.AB_Abstract.LastName + ', ' + dbo.AB_Abstract.FirstName + ' ' + dbo.AB_Abstract.MiddleName AS NameFull, 
                      dbo.CM_CPI.PhysicianNumber AS FamilyPhysician, dbo.CM_CPI.PhysicianPhone AS FamilyPhysicianPhone, dbo.CM_CPI.PrimaryAddress, 
                      dbo.CM_CPI.PrimaryPhone, dbo.AB_Abstract.PostalCode, dbo.AB_Abstract.RegisterNumber, dbo.TR_Main.TranscriptionID, 
                      dbo.U_Users.UserDescription AS Transcriptionist, dbo.U_Users.TransInitials AS TranscriptionistInitials, dbo.TR_Main.TranscriptionDate, 
                      dbo.TR_Main.TranscriptionTime
FROM         dbo.AB_PatientService RIGHT OUTER JOIN
                      dbo.CM_CPI RIGHT OUTER JOIN
                      dbo.LU_Provider LU_Provider_2 RIGHT OUTER JOIN
                      dbo.U_Users RIGHT OUTER JOIN
                      dbo.TR_Main ON dbo.U_Users.Code = dbo.TR_Main.Transcriptionist ON LU_Provider_2.Code = dbo.TR_Main.DictatingPhysician ON 
                      dbo.CM_CPI.PatientID = dbo.TR_Main.PatientID LEFT OUTER JOIN
                      dbo.LU_Provider LU_Provider_3 RIGHT OUTER JOIN
                      dbo.LU_Provider LU_Provider_1 RIGHT OUTER JOIN
                      dbo.AB_Provider ON LU_Provider_1.Code = dbo.AB_Provider.ProviderNumber LEFT OUTER JOIN
                      dbo.LU_ProviderService ON dbo.AB_Provider.ProviderService = dbo.LU_ProviderService.Code RIGHT OUTER JOIN
                      dbo.AB_Abstract ON dbo.AB_Provider.AbstractID = dbo.AB_Abstract.AbstractID ON LU_Provider_3.Code = dbo.AB_Abstract.AttendingPhysician ON 
                      dbo.TR_Main.AbstractID = dbo.AB_Abstract.AbstractID LEFT OUTER JOIN
                      dbo.AB_Intervention ON dbo.AB_Abstract.AbstractID = dbo.AB_Intervention.AbstractID LEFT OUTER JOIN
                      dbo.ICD_ProcFile10 ON dbo.AB_Intervention.IntervCode = dbo.ICD_ProcFile10.Code ON 
                      dbo.AB_PatientService.AbstractID = dbo.AB_Abstract.AbstractID LEFT OUTER JOIN
                      dbo.LU_PatientService ON dbo.AB_PatientService.PatientService = dbo.LU_PatientService.Code LEFT OUTER JOIN
                      dbo.LU_AgeCode Lookup6 ON dbo.AB_Abstract.AgeCode = Lookup6.Code LEFT OUTER JOIN
                      dbo.ICD_DiagFile10 RIGHT OUTER JOIN
                      dbo.AB_Diagnosis ON dbo.ICD_DiagFile10.Code = dbo.AB_Diagnosis.DiagnosisCode ON 
                      dbo.AB_Abstract.AbstractID = dbo.AB_Diagnosis.AbstractID
WHERE     (ISNULL(dbo.AB_Diagnosis.DiagnosisOccurrence, 1) = 1) AND (ISNULL(dbo.AB_Intervention.IntervOccurrence, 1) = 1) AND 
                      (ISNULL(dbo.AB_PatientService.ServiceOccurrence, 1) = 1) AND (ISNULL(dbo.AB_Provider.ProviderOccurrence, 1) = 1) AND 
                      (dbo.TR_Main.TranscriptionID = @TranscriptionID)

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO







CREATE    PROCEDURE [L_Transcription]
   @AppID as int,
   @UserID as int,
   @AbstractID as int
AS 
Declare @SDate as datetime
--set @SDate = getdate()

   Declare @SQL as NVarChar(1000)
   Declare @FieldID as VarChar(6)
   Declare @SystemName as VarChar(50)
   Declare @LookupTable as VarChar(100)    
   Declare @TempValue as VarChar(50)
   Declare @TempCode as VarChar(50)
   Declare @TempDisplayCode as VarChar(50)
   Declare @TempUserDesc as VarChar(255)
   Declare @TempCIHI as VarChar(50)
   Declare @ICDType as VarChar(1)
   Declare @SortOrder as VarChar(6)
   Declare @DischargeDate as datetime
   Declare @AdmitDate as datetime
   Declare @CareType as int
   Declare @AProv as VarChar(10)
   Declare @DDAte as varChar(10)
   Declare @Multi as int
   Declare @DType as int
   Declare @DiagCount as int
   Declare @IntervCount as int
   Declare @ProvCount as int
   Declare @MISCount as int
   Declare @PatCount as int
   Declare @ProjCount as int
   Declare @SCUCount as int

   Create TABLE #TableABLoad (SortOrder int, FKey int, Occ int,
       Code int,
       DisplayCode VarChar(50),
       UserDescription VarChar(255),
       CIHIValue VarChar(50), ValidFrom Datetime, ValidTo DateTime)

	SELECT dbo.TR_Main.TranscriptionID, dbo.TR_Main.AbstractID, dbo.TR_Main.PatientID, dbo.TR_Main.CareType, dbo.AB_Abstract.AdmitDate, dbo.CM_CPI.AlternateAddress, dbo.AB_Abstract.AttendingPhysician, 
	dbo.AB_Abstract.AgeNumber, dbo.AB_Abstract.BirthDate, dbo.CM_CPI.BirthPlace, dbo.AB_Abstract.ChartNumber, dbo.TR_Main.DictatingPhysician, 
	dbo.TR_Main.DictationDate, dbo.TR_Main.DictationTime, dbo.TR_Main.SignPhysician, dbo.TR_Main.SignDate, dbo.TR_Main.SignTime, dbo.AB_Abstract.DischargeDate, dbo.AB_Provider.ProviderNumber, 
	dbo.TR_Main.DocumentType, dbo.TR_Main.DocumentName, dbo.AB_Abstract.EncounterNumber, dbo.AB_Abstract.FirstName, 
	dbo.AB_Abstract.LastName, dbo.CM_CPI.PhysicianNumber, dbo.CM_CPI.PhysicianPhone, dbo.CM_CPI.PrimaryAddress, 
	dbo.AB_Abstract.AdmittingNurseArea, dbo.CM_CPI.PrimaryPhone, dbo.AB_Abstract.RegisterNumber, dbo.TR_Main.TranscriptionDate, 
	dbo.TR_Main.TranscriptionTime, dbo.TR_Main.Transcriptionist, dbo.TR_Main.StartWordCount, dbo.TR_Main.LastWordCount, 
	dbo.TR_Main.TranscriptionLength into #ABTransTemp
	FROM dbo.CM_CPI RIGHT OUTER JOIN
	dbo.TR_Main ON dbo.CM_CPI.PatientID = dbo.TR_Main.PatientID LEFT OUTER JOIN
	dbo.AB_Provider RIGHT OUTER JOIN
	dbo.AB_Abstract ON dbo.AB_Provider.AbstractID = dbo.AB_Abstract.AbstractID ON dbo.TR_Main.AbstractID = dbo.AB_Abstract.AbstractID
	WHERE (ISNULL(dbo.AB_Provider.ProviderOccurrence, 1) = 1) AND (dbo.TR_Main.TranscriptionID = @AbstractID)

   SELECT dbo.U_Fields.FieldID, dbo.U_Fields.SystemName, dbo.U_UsersFields.LookUpTable, ParamProcID, dbo.U_UsersFields.datatype, sortorder into #CurTTemp
   FROM dbo.U_Fields INNER JOIN dbo.U_UsersFields ON dbo.U_Fields.FieldID = dbo.U_UsersFields.FieldID
   WHERE (dbo.U_UsersFields.UserID = @UserID) AND (dbo.U_UsersFields.AppID = @Appid) AND (dbo.U_Fields.IsGroup <> 1)
   AND (dbo.U_UsersFields.DataType <> 100000) and U_Fields.FieldID not between 60000 and 70000
   ORDER BY dbo.U_UsersFields.SortOrder

   Update #CurTTemp set LookupTable = 'LU_ProviderService' where LookupTable = 'LLU_ProviderServices'
   Update #CurTTemp set LookupTable = 'LU_ProviderSpecialty' where LookupTable = 'LLU_ProviderSpecialty'
   Update #CurTTemp set LookupTable = 'LU_CodeFile' where isnumeric(LookupTable) = 1

   Set @DDate = convert(varchar(10), getdate(), 101)

   Declare Cur_Columns cursor fast_forward for
   Select * from #CurTTemp
   Open Cur_Columns

   fetch next from Cur_Columns
   into @FieldID, @SystemName, @LookupTable, @Multi, @DType, @SortOrder

   While @@Fetch_Status = 0
   Begin
           If isnull(@LookupTable, '') = ''
           Begin
               If @SystemName <> 'AbstractNotes'
               Begin
                   select @SQL = ' Select ' + @SortOrder + ', ' + @FieldID + ', 0, ' + @Systemname + '  from #ABTransTemp'
                   Insert into #TableABLoad (SortOrder, FKey, Occ, UserDescription) EXEC (@SQL)
               End
           End
           else if @SystemName = 'PostalCode'
           Begin
               select @SQL = 'Select @TempV =  ' + @Systemname + '  from #ABTransTemp'
               EXECUTE sp_executesql @SQL, N'@TempV VarChar(50) output', @TempValue Output

               If isnull(@TempValue, '') <> ''
               Begin
                   Select @SQL = 'SELECT top 1 ' + @SortOrder + ', ' + @fieldid + ', 0, Code, ''' + left(@TempValue, 3) + ' ' + substring(@TempValue, 4, 3) + ''', UserDescription, ''' + @TempValue + ''', ValidFrom, ValidTo 
                   FROM LU_PostalCode WHERE ([ValidFrom] <= ''' + @DDate + ''') AND (''' + @DDate + ''' <= [ValidTo]) and CIHIValue in ( 
		   left( ''' + @TempValue + ''', 6 ), left( ''' + @TempValue + ''', 5 ), left( ''' + @TempValue + ''', 4 ), left( ''' + @TempValue + ''', 3 ), 
		   left( ''' + @TempValue + ''', 2 ), left( ''' + @TempValue + ''', 1 )) Order by len(cihivalue) desc'
                   Insert into #TableABLoad (SortOrder, FKey, Occ, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo) Exec (@SQL)
               End
           End
           else
           Begin
               select @SQL = 'Select @TempV =  ' + @Systemname + '  from #ABTransTemp'
               EXECUTE sp_executesql @SQL, N'@TempV VarChar(50) output', @TempValue Output

               If isnull(@TempValue, '') <> ''
               Begin
                   Select @SQL = 'SELECT ' + @SortOrder + ', ' + @FieldID + ', 0, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo 
                   FROM ' + @LookupTable + ' WHERE (Code = ' + @TempValue + ')'
                   Insert into #TableABLoad (SortOrder, FKey, Occ, Code, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo) Exec (@SQL)
               End
           End
   
       fetch next from Cur_Columns
       into @FieldID, @SystemName, @LookupTable, @Multi, @DType, @SortOrder
   End

   Close Cur_Columns
   Deallocate Cur_Columns
   Update #TableABLoad set code = 0, Displaycode = NULL, UserDescription = NULL, CIHIValue = NULL where (ValidTo < '' + @DDate + '' or ValidFrom > '' + @DDate + '')
   update #TableABLoad set userdescription = convert(varchar(20), cast(userdescription as datetime), 120) where isdate(userdescription) = 1 and len(userdescription) > 10
   Select fkey, occ, code, displaycode, userdescription, cihivalue from #TableABLoad order by sortorder, occ
--   print datediff(ms, @SDate, getdate())

   Return 0

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is called by the Load Method of the User Profile Control
-- NOTE: User ID (Code) 1 is the Med2020 System User, Clients cannot edit this record.
CREATE          PROCEDURE [L_Users]
	@Key as int
AS 
--PR-03040
select 
	Code, DisplayCode, UserDescription, DefaultDescription, CIHIValue, ValidFrom, ValidTo, LUText, InterfaceIn, HospitalID, DefaultHospID, UserName, NTAuthority, 
	ltrim(reverse(isnull(char(ASCII(SUBSTRING((UserPassword), 1, 1)) + 10), '') +
	isnull(char(ASCII(SUBSTRING((UserPassword), 2, 1)) + 11), '') +
	isnull(char(ASCII(SUBSTRING((UserPassword), 3, 1)) + 12), '') +
	isnull(char(ASCII(SUBSTRING((UserPassword), 4, 1)) + 13), '') +
	isnull(char(ASCII(SUBSTRING((UserPassword), 5, 1)) + 14), '') +
	isnull(char(ASCII(SUBSTRING((UserPassword), 6, 1)) + 15), '') +
	isnull(char(ASCII(SUBSTRING((UserPassword), 7, 1)) + 16), '') +
	isnull(char(ASCII(SUBSTRING((UserPassword), 8, 1)) + 17), '') +
	isnull(char(ASCII(SUBSTRING((UserPassword), 9, 1)) + 18), '') +
	isnull(char(ASCII(SUBSTRING((UserPassword), 10, 1)) + 19), '') +
	isnull(char(ASCII(SUBSTRING((UserPassword), 11, 1)) + 20), '') +
	isnull(char(ASCII(SUBSTRING((UserPassword), 12, 1)) + 21), '') +
	isnull(char(ASCII(SUBSTRING((UserPassword), 13, 1)) + 22), '') +
	isnull(char(ASCII(SUBSTRING((UserPassword), 14, 1)) + 23), '') +
	isnull(char(ASCII(SUBSTRING((UserPassword), 15, 1)) + 24), ''))) as UserPassword, 
	LastName, MiddleName, FirstName, TransInitials, IsAdmin, CanSubmitI, CanSubmitS, CanSubmitA, LanguageID, UserDateFormat, DisplayMessages, DisplayChrtLinks,
	DisplayMultUser,  AutoShowLookUp, AutoShowClone, FlyCalcGrouper, EnableQuickSearch, SearchChartPrefix, ShowVIP, CanModifyCharts, CanReSetA, CanReSetR, CanReSetC, CanReSetM, FontSize,
	PermitCPI, PermitChartLoc, PermitChartDef,  PermitTranscription, PermitROI, PermitCCR, PermitInPat, PermitSDS, PermitAmcare, PermitBatchGrouper, 
	PermitCareMap, PermitMonthEnd, PermitReportGen, PermitCIHISubmit, PermitCIHICorrect, PermitBatchInterface, PermitHL7Interface, PermitUndelete, 
	PermitRegionProf, PermitHospProf, PermitInstProf, PermitUserProf, PermitLookUpMaint, PermitProvdrMaint, PermitControlFile, PasswordChanged, ChangePasswordDays, ChangePasswordDate, 
	RoleID, PermitCCR10, PermitInPat10, PermitSDS10, PermitAmcare10, CanSubmitI10, CanSubmitS10, CanSubmitA10, PermitRehab10, CanSubmitR10, PermitOMHRS10, CanSubmitM10, PermitClinic, 
	PermitBilling, PermitScheduler, CanSubmitCL, PermitCCRS10, CanSubmitC10, PermitVisitHist, PermitDAS, FlyCalcCACS, FlyCalcDPG, FlyCalcFIM,  FlyCalcRUG,
	AccessLockChart, PromptLoc, PromptDef, AmCareFacFile, CCRSFacFile, RehabFacFile, OMHRSFacFile, DADSepFile, CCRSAuditFile, ImportDADErrors, ExecTermChrt, ShowAllRegion, 
	PermitViewChartAct, PermitViewChartDef, PermitChartVolume, PermitWRUUpdates, PermitMDASLayer, PermitMDASPrivacy, MDASRecordLock, MDASSensitvity, CanPurgeVolQue, PermitAdapCS,
	PermitCCM, CanSubmitCCM, ImportOMHRSErrors, CanViewWho, FlyCalcSCIPP, CanLaunchSolCom, CanPurgeLog, DADInstFile, CanClearCPILock, PermitCodeSmart, SetLevelOneCorrection, ShowConfidentialRequest,
	ModifyRegionalID, PermitCJRR, CanSubmitCJRR, CanReSetCJRR, FolioCAFile, FolioCCIFile, SkipLoginScreen, codeSmartFile, PermitEditEngine, EditEngineFile, SelectQueue
from dbo.U_Users where Code = @Key and Code <> 1

select 	
	 [MDAS_Bulk]
	,[MDAS_Scan]
	,[MDAS_Import]
	,[MDAS_Cancel]
	,[MDAS_Revise]
	,[MDAS_Append]
	,[MDAS_AppendI]
	,[MDAS_View]
	,[MDAS_Print]
	,[MDAS_Export]
	,[MDAS_Send]
from [U_Permission] where UserID = @Key 

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE      PROCEDURE [L_VisitHistory]
	@AppID as int,
	@UserID as int,
	@AbstractID as int,
	@LogID as int
AS
	declare @SDate as datetime 
	 
	declare @sql as nvarchar(1000) 
	declare @exec_return int 
	 
	declare @FieldID as varchar(6) 
	declare @SystemName as varchar(50) 
	declare @LookupTable as varchar(100)     
	declare @TempValue as varchar(50) 
	 
	declare @ICDType as varchar(1) 
	declare @SortOrder as varchar(10) 
	declare @DischargeDate as datetime 
	declare @AdmitDate as datetime 
	declare @CareType as int 
	declare @AProv as varchar(10) 
	declare @DDAte as datetime
	declare @MultipleIndex as int 
	declare @DataType as int 
	
	 
	set nocount on 
	 
	create table #LoadResults  
	( 
	    SortOrder int,  
	    FieldID int,  
	    Occurrence int, 
	    Code int, 
	    DisplayCode varchar(50), 
	    UserDescription varchar(255), 
	    CIHIValue varchar(50),  
	    Validfrom datetime,  
	    ValidTo datetime 
	) 
	 
	select * into #ABMainTemp from AB_Main where universalid = @Abstractid
	
	select  
	    dbo.U_Fields.FieldID,  
	    dbo.U_Fields.SystemName,  
	    dbo.U_UsersFields.LookUpTable,  
	    dbo.U_UsersFields.MultipleIndex,  
	    dbo.U_UsersFields.DataType,  
	    dbo.U_UsersFields.SortOrder  
	into #UsersFields 
	from dbo.U_Fields  
	join dbo.U_UsersFields on dbo.U_Fields.FieldID = dbo.U_UsersFields.FieldID 
	where dbo.U_UsersFields.UserID = @UserID  
	and dbo.U_UsersFields.AppID = @AppID 
	and dbo.U_Fields.IsGroup = 0 
	and dbo.U_UsersFields.DataType <> 100000  
	and dbo.U_Fields.FieldID not between 60000 and 80000 
	ORDER BY dbo.U_UsersFields.SortOrder 
	 
	update #UsersFields set LookupTable = 'LU_ProviderService' where LookupTable = 'LLU_ProviderServices' 
	update #UsersFields set LookupTable = 'LU_ProviderSpecialty' where LookupTable = 'LLU_ProviderSpecialty' 
	update #UsersFields set LookupTable = 'LU_CodeFile' where isnumeric(LookupTable) = 1 
	 
	update #UsersFields set LookupTable = 'ICD_DiagFile10' where DataType = 60 
	update #UsersFields set LookupTable = 'ICD_ProcFile10' where DataType = 61 

	Select @DDate = DischargeDate, @AdmitDate = AdmitDate from #ABMainTemp
	
	if isdate(@DDate) = 0 and isnull(@AdmitDate, 0) <> 0 
	    set @DDate = convert(varchar(10), @AdmitDate, 101) 
	
	declare cur cursor fast_forward for 
	 
	    select FieldID, SystemName, LookUpTable, MultipleIndex, DataType, SortOrder  
	    from #UsersFields 
	 
	open cur 
	 
	fetch next from cur into @FieldID, @SystemName, @LookupTable, @MultipleIndex, @DataType, @SortOrder 
	 
	while @@Fetch_Status = 0 begin 
	    set @sql = '' 
	 
	        if isnull(@LookupTable, '') = '' begin 
	            if @SystemName <> 'AbstractNotes'  
	                set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', 0, null, null, ' + @SystemName + ', null, null, null from #ABMainTemp' 
	        end 
	        else begin 
	            set @sql = 'select @TempV = ' + @SystemName + ' from #ABMainTemp' 
	            exec sp_executesql @sql, N'@TempV varchar(50) output', @TempValue Output 
	            set @sql = '' 
	             
	            if isnull(@TempValue, '') <> ''  
	                set @sql = 'select ' + @SortOrder + ', ' + @FieldID + ', 0, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo from ' + @LookupTable + ' where (Code = ' + @TempValue + ')' 
	        end 

	    if isnull(@sql, '') != '' begin  
	        insert #LoadResults (SortOrder, FieldID, Occurrence, Code, DisplayCode, UserDescription, CIHIValue, Validfrom, ValidTo)  

	        exec @exec_return = sp_executesql @sql 
	         
	        if @exec_return != 0  
	            RAISERROR (@sql, 11, 1) 
	    end 
	 
	    fetch next from cur into @FieldID, @SystemName, @LookupTable, @MultipleIndex, @DataType, @SortOrder 
	end 
	 
	close cur 
	deallocate cur 

	update #LoadResults set code = 0, Displaycode = NULL, UserDescription = NULL, CIHIValue = NULL where (ValidTo < '' + @DDate + '' or Validfrom > '' + @DDate + '') 
	update #LoadResults set userdescription = convert(varchar(20), cast(userdescription as datetime), 120) where isdate(userdescription) = 1 and len(userdescription) > 10 
	--insert into AB_updateHistory values (@AbstractID, @LogID, getdate(), 'Viewed') 
	set nocount off 
	 
	select FKey = FieldID, Occ = Occurrence, Code, DisplayCode, UserDescription, CIHIValue  
	from #LoadResults  
	order by SortOrder, Occurrence




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE procedure [M_BAKUP_TABLE]
    @table_name nvarchar(50), 
    @bakup_name nvarchar(50) out
as
declare @sql nvarchar(250)
    
set @bakup_name = N'zz_bak_' + @table_name + ' ' + convert(nvarchar(20), getdate(), 120)
set @sql = N'select * into ' + quotename(@bakup_name) + ' from ' + quotename(@table_name)
print @sql
exec(@sql)
return





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [M_CheckUpdate]
	@UpdateID as int,
	@UpdateOK bit output
AS
	If exists (select * from M_DBULogging where UpdateID = @UpdateID and EndTime is not null and isnull(multirun, 0) = 0)
		Set @UpdateOK = 1
	Else
		Set @UpdateOK = 0




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE     procedure [M_CreateBackup]
    @ServerName sysname,
    @db sysname, 
    @path nvarchar(260),
    @ExecuteTime datetime = '02:00:00.000'
AS 

-- Create Bakup Job
declare @id BINARY(16)  
declare @BakCommand nvarchar(1200)
declare @DateStart int
declare @ExecuteTimeInt int
declare @ret int
declare @DateCompare datetime
declare @DeviceName as sysname
declare @JobName as sysname
declare @ScheduleName as sysname

-- remove any leading and/or trailing spaces
set @ServerName = ltrim(rtrim(@ServerName))
set @db         = ltrim(rtrim(@db))
set @path       = ltrim(rtrim(@path))

set @JobName    = N'Med2020 ' + @db + ' Bakup'
set @DeviceName = N'Med2020' + @db + 'Bakup'


-- exit if the job already exists
if exists(select * from msdb..sysjobs where name = N'Med2020 ' + @db + ' Bakup') 
begin 
    set @path = '''Med2020 ' + @db + ' Bakup'' already exists.  To modify it, ' +
            'first delete it using dbo.BAK_DeleteBakupForMed2020WinRecs2.'
    raiserror (@path, 18, 1)
    goto exit_procedure
end

if exists(select * from master..sysdevices where name = @DeviceName)
begin
    print 'Bakup device ''Med2020' + @db + 'Bakup'' already exists.'
    print 'To modify it, delete it with dbo.M_DeleteBackup first.'
    print 'Continuing to create bakup...'
end
else
begin

    if (right(@path, 1) <> N'\') set @path = @path + N'\'
 
    create table #fileexists ( 
        doesexist smallint,
        fileisdir smallint,
        direxist smallint
    )
    
    insert #fileexists exec master..xp_fileexist @path

    if exists (select * from #fileexists fe where fe.fileisdir = 0) 
    begin
        raiserror ('The specified path: "%s" does not exist', 18, 1, @path)
        goto exit_procedure
    end

    drop table #fileexists

    set @path = @path + N'MD20WR20.bak'
    exec @ret = master..sp_addumpdevice 
        @devtype = 'disk', 
        @logicalname = @DeviceName, 
        @physicalname = @path
    if (@@error <> 0 or @ret <> 0) goto exit_proc_rollback

end 


set @BakCommand = 
    N'BACKUP DATABASE [' + @db + '] TO [' + @DeviceName + '] ' + 
    N'WITH  INIT ,  NOUNLOAD ,  NAME = N''' + @JobName + ''', ' +
    N'NOSKIP ,  STATS = 10,  DESCRIPTION = N''Database Bakup for Med2020 WinRecs2: [' + @db + ']'',  NOFORMAT '

set @ExecuteTimeInt = convert(int, left(replace(convert(varchar(20), @ExecuteTime, 14), ':', ''), 6))

set @DateCompare = convert(datetime, convert(varchar(10), getdate(), 111) + ' ' + convert(varchar(12), @ExecuteTime, 14))

if (@DateCompare < getdate()) 
    set @DateStart = convert(int, replace(convert(varchar(10), dateadd(Day, 1, getdate()), 111), '/', ''))
else
    set @DateStart = convert(int, replace(convert(varchar(10), getdate(), 111), '/', ''))

begin tran create_bakup
    exec @ret = msdb..sp_add_job 
        @job_name = @JobName, 
        @enabled = 1, 
        @description = 'Job: Bakup Database for Med2020 WinRecs 2',
        @start_step_id = 1, 
        @owner_login_name = N'sa',
        @notify_level_eventlog = 2, 
        @notify_level_email = 0, 
        @notify_level_netsend = 0, 
        @notify_level_page = 0, 
        @delete_level = 0, 
        @category_name = N'Database Maintenance', 
        @job_id = @id OUTPUT  
    if (@@error <> 0 or @ret <> 0) goto exit_proc_rollback
    
    exec @ret = msdb..sp_add_jobstep 
        @job_id = @id , 
        @step_id = 1, 
        @cmdexec_success_code = 0, 
        @on_success_action = 1, 
        @on_success_step_id = 0, 
        @on_fail_action = 2, 
        @on_fail_step_id = 0, 
        @retry_attempts = 0, 
        @retry_interval = 0, 
        @os_run_priority = 0, 
        @flags = 0, 
        @step_name = N'MED2020 Step 1', 
        @subsystem = N'TSQL', 
        @command = @BakCommand, 
        @database_name = N'master'
    if (@@error <> 0 or @ret <> 0) goto exit_proc_rollback
    
    set  @ScheduleName = N'Schedule Med2020 ' + @db + ' Bakup'

    exec @ret = msdb..sp_add_jobschedule 
        @job_id = @id, 
        @name = @ScheduleName, 
        @enabled = 1, 
        @freq_type = 4, 
        @freq_interval = 1, 
        @freq_subday_type = 1, 
        @freq_subday_interval = 0, 
--         @freq_subday_type = 4, 
--         @freq_subday_interval = 1, 
        @freq_relative_interval = 0, 
        @freq_recurrence_factor = 1, 
        @active_start_date = @DateStart, 
        @active_end_date = 99991231, 
        @active_start_time = @ExecuteTimeInt, 
        @active_end_time = 235959
    if (@@error <> 0 or @ret <> 0) goto exit_proc_rollback
    
    exec @ret = msdb..sp_add_jobserver 
        @job_id = @id, 
        @server_name = @ServerName
    if (@@error <> 0 or @ret <> 0) goto exit_proc_rollback

commit tran create_bakup
print 'Bakup was successfully created'
goto exit_procedure

exit_proc_rollback:
    if (@@trancount > 0) rollback tran create_bakup
    raiserror ('Bakup was NOT created successfully.  There was an error.', 18, 1)

exit_procedure:




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE  procedure [M_CreateIndex]
    @idxid int
as 

declare @exec_return int, @sql nvarchar(1000)

declare @IndexName sysname, @TableName sysname, @ColumnName sysname, @IndexType nchar(2), @IsCluster bit
declare @ColumnList nvarchar(500), @ObjectRename sysname

select 
    @TableName = TableName,
    @ColumnName = ColumnName,
    @IndexType = IndexType,
    @IsCluster = IsCluster
from M_Indexes, information_schema.tables
where idxid = @idxid and Table_Name = tablename

if @IndexType = 'IX' begin

    -- CHECK TO SEE IF THE COLUMN ALREADY HAS AN INDEX
    select @IndexName = i.name 
    from sysindexes I 
    where I.id = object_id(@TableName) 
    and I.indid > 0 
    and I.indid < 255 
    and INDEXPROPERTY(I.id, I.name, N'IsStatistics') = 0 
    and INDEXPROPERTY(I.id, I.name, N'IsHypothetical') = 0 
    and I.name not in 
    (
        select O.name 
        from sysobjects O 
        where O.parent_obj = I.id 
        and OBJECTPROPERTY(O.id, N'isConstraint') = 1
    )
    and I.indid in 
    (
        select indid 
        from sysindexkeys K
        where id = I.id
        and colid in 
        (
            select colid 
            from syscolumns 
            where id = K.id
            and name = @ColumnName
        )
    )

    -- IF IT DOES NOT EXIST, CREATE THE INDEX
    if (@IndexName is null) begin

        set @IndexName = 'IX_' + @TableName + '_' + @ColumnName
        
        set @sql = N'CREATE INDEX ' + quotename(@IndexName) + ' ON [dbo].' + quotename(@TableName) + '(' + quotename(@ColumnName) + ') ON [PRIMARY]'
        
    end
    -- OTHERWISE, REBUILD THE INDEX
    else begin 
        
        set @ObjectRename = 'IX_' + @TableName + '_' + @ColumnName
    
        if @ObjectRename != @IndexName begin
            set @IndexName = quotename(@TableName) + '.' + quotename(@IndexName)
            -- print 'sp_rename ' + @IndexName + ', ' + @ObjectRename + ', ''INDEX'''
            exec sp_rename @IndexName, @ObjectRename, 'INDEX'
            set @IndexName = @ObjectRename
        end

        set @sql = N'DBCC DBREINDEX (' + @TableName + ', ' + @IndexName + ')'

    end

end

else if @IndexType = 'PK' begin

    -- IF THE CONSTRAINT DOES NOT EXIST, CREATE IT.
    if not exists
    (
        select *
        from sysobjects 
        where parent_obj = object_id(@TableName)
        and type = N'K'
        and xtype = N'PK'
    ) begin

        set @IndexName = N'PK_' + @TableName
        set @ColumnList = ''


        if @IsCluster = 1 begin
           
            declare CurCols cursor local fast_forward for
                select ColumnName 
                from M_Indexes
                where TableName = @TableName
                and IsCluster = @IsCluster
                and IndexType = @IndexType

            open CurCols

            while(1=1)begin
                fetch next from CurCols into @ColumnName
                if @@fetch_status <> 0 break
                
                set @ColumnList = @ColumnList + '|' + quotename(@ColumnName) + '|'
            end

            close CurCols
            deallocate CurCols

            set @ColumnList = replace(@ColumnList, '||', ', ')
            set @ColumnList = replace(@ColumnList, '|', '')
        end
        else
            set @ColumnList = quotename(@ColumnName)
    
        set @sql = N'' + 
            'ALTER TABLE ' + quotename(@TableName) + ' ADD CONSTRAINT ' + quotename(@IndexName) + ' PRIMARY KEY  CLUSTERED ' + 
        	'(' + @ColumnList + ') ON [PRIMARY]'

    end
    -- OTHERWISE REBUILD IT
    else begin
        select @IndexName = name
        from sysobjects 
        where parent_obj = object_id(@TableName)
        and type = N'K'
        and xtype = N'PK'

        set @ObjectRename = N'PK_' + @TableName

        if @ObjectRename != @IndexName begin
            -- print 'sp_rename ' + @IndexName + ', ' + @ObjectRename + ', ''OBJECT'''
            exec sp_rename @IndexName, @ObjectRename, 'OBJECT'
            set @IndexName = @ObjectRename
        end

        set @sql = N'DBCC DBREINDEX (' + @TableName + ', ' + @IndexName + ')'
    end

end
else if isnull(@TableName, '') <> ''
    RAISERROR ( 'INVALID INDEX TYPE', 11, 1 )


print @sql
-- print ''
-- print ''
-- print ''


exec @exec_return = sp_executesql @sql
if @exec_return <> 0 
    RAISERROR ( @sql, 11, 1 )

return 0



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE procedure [M_DeleteBackup]
    @dbName sysname
AS 
declare @JobName sysname
declare @DeviceName sysname

set @JobName    = N'Med2020 ' + ltrim(rtrim(@dbName)) + ' Bakup'
set @DeviceName = N'Med2020' + ltrim(rtrim(@dbName)) + 'Bakup'

if exists(select * from msdb..sysjobs where name = @JobName)
    exec msdb..sp_delete_job @job_name = @JobName

if exists(select * from master..sysdevices where name = @DeviceName)
    exec msdb..sp_dropdevice  @logicalname = @DeviceName




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE procedure [M_DetectDuplicates]
    @UpdateID int = 0
as

set nocount on

declare @sql as nvarchar(1000)
declare 
    @tbl_name nvarchar(50),
    @err_message nvarchar(250)


declare 
    @tbl varchar(30),
    @fld varchar(30),
    @occ varchar(30),
    @err varchar(30)

declare 
    @cur cursor

set @tbl_name = 
    'zzDuplicates' + 
        replace( 
        replace( 
        replace( 
        replace( 
            convert( varchar(25), getdate(), 120 )
        , ' ', '')
        , '/', '')
        , '-', '')
        , ':', '') 

if (select object_id( N'tempdb..#duplicates' )) is not null 
    drop table #duplicates

create table #duplicates
(
    num int not null,
    val int not null,
    tbl varchar(30) not null,
    fld varchar(30) not null,
    err varchar(30) not null
)


set @cur = cursor local fast_forward for
    select tbl, fld, occ, err
    from 
    (
        select tbl = 'AB_Blood',            fld = 'AbstractID', occ = '',                    err = 'Duplicate Values' union
        select tbl = 'AB_Diagnosis',        fld = 'AbstractID', occ = 'DiagnosisOccurrence', err = 'Duplicate Values' union
        select tbl = 'AB_Intervention',     fld = 'AbstractID', occ = 'IntervOccurrence',    err = 'Duplicate Values' union
        select tbl = 'AB_Ancillary',        fld = 'AbstractID', occ = '',                    err = 'Duplicate Values' union
        select tbl = 'AB_MIS',              fld = 'AbstractID', occ = 'MISOccurrence',       err = 'Duplicate Values' union
        select tbl = 'AB_BasicOption',      fld = 'AbstractID', occ = '',                    err = 'Duplicate Values' union
        select tbl = 'AB_Provider',         fld = 'AbstractID', occ = 'ProviderOccurrence',  err = 'Duplicate Values' union
        select tbl = 'AB_Project',          fld = 'AbstractID', occ = 'ProjectOccurrence',   err = 'Duplicate Values' union
        select tbl = 'AB_ReproductiveCare', fld = 'AbstractID', occ = '',                    err = 'Duplicate Values' union
        select tbl = 'AB_SpecialCareUnit',  fld = 'AbstractID', occ = 'SCUOccurrence',       err = 'Duplicate Values' union
        select tbl = 'AB_Therapeutic',      fld = 'AbstractID', occ = '',                    err = 'Duplicate Values' union
        select tbl = 'AB_PatientService',   fld = 'AbstractID', occ = 'ServiceOccurrence',   err = 'Duplicate Values' 
    ) tbls
    where tbl <> ''

open @cur

while (1=1) begin
    fetch next from @cur into @tbl, @fld, @occ, @err
    if @@fetch_status <> 0 break

    set @sql = N'' +
        'select ' + 
            'num = count(*), ' + 
            'val = ' + @fld + ', ' +
            'tbl = @tbl, ' + 
            'fld = @fld, ' + 
            'err = @err ' + 
        'from ' + @tbl + ' ' + 
        'group by ' + @fld + case when @occ <> '' then ', ' else '' end + @occ + ' ' + 
        'having count(*) > 1 ' 

    insert #duplicates ( num, val, tbl, fld, err ) 
    exec sp_executesql @sql, N'@tbl varchar(30), @fld varchar(30), @err varchar(30)', @tbl, @fld, @err

end

close @cur
deallocate @cur


set @cur = cursor local fast_forward for 
    select distinct tbl = table_name 
    from information_schema.columns 
    where table_name like 'LU[_]%' 
    and column_name = 'Code' 
    and table_name <> 'LU_CACS_TECH'

open @cur

while 1=1 begin
    fetch next from @cur into @tbl
    if @@fetch_status <> 0 break

    set @sql = N'' + 
        'select ' + 
            'num = count(Code), ' + 
            'val = Code, ' + 
            'tbl = @tbl, ' + 
            'fld = ''Code'', ' + 
            'err = ''Duplicate Values'' ' + 
        'from ' + @tbl + ' ' +
        'group by Code ' + 
        case 
            when @tbl = 'LU_CodeFile' then ', LookUpID '
            else ''
        end +
        'having count(*) > 1'
    
    insert #duplicates ( num, val, tbl, fld, err ) 
    exec sp_executesql @sql, N'@tbl varchar(30)', @tbl

end 

close @cur 
deallocate @cur


set @sql = N'' + 
    'select * ' + 
    'into ' + @tbl_name + ' ' + 
    'from #duplicates'
exec ( @sql )



if (select count(*) from #duplicates) > 0 begin

    set @cur = cursor local fast_forward for
        select distinct tbl 
        from #duplicates 

    set @err_message = 'ERROR - duplicates found: '
    
    open @cur

    while (1=1) begin
    
        fetch next from @cur into @tbl
        if @@fetch_status <> 0 break
        
        set @err_message = @err_message + '|' + @tbl + '|' 
    
    end

    close @cur
    deallocate @cur

    set @err_message = replace( @err_message, '||', ', ')
    set @err_message = replace( @err_message, '|', ' ')
    

    set @err_message = @err_message + '(' + @tbl_name + ')' 

    if @UpdateID > 0 begin

        update dbo.M_DBULogging 
        set UpdateDescription = left( UpdateDescription + @err_message, 255 )
        where UpdateID = @UpdateID 
        and EndTime is null
        and UpdateDescription <> '%' + @err_message + '%'
    
        raiserror ( @err_message, 16, 1 )
    end
end


if (select object_id( N'tempdb..#duplicates' )) is not null 
    drop table #duplicates

set nocount off

set @sql = N'select * from ' + @tbl_name
exec( @sql )




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [M_EnableViewProcess]
    @Login varchar(50),
    @CPI   char(1), @Location char(1), @Deficiency char(1),
    @ROI char(1), @Transcription char(1), @System Char(1), @VisitHistory char(1),
    @DAD char(1), @NACRS char(1), @Rehab char(1), @CCRS char(1),
    @OMHRS char(1), @CCM char(1)
as
    declare @tbl varchar(100), @sql varchar(2000)

    declare cur_tbls cursor for
        select [name]
        from dbo.sysobjects
        where xtype ='U' 
            and [name] not like 'BI%'
            and [name] not like 'CMG%' 
            and [name] not like 'Grouper%'
            and [name] not like 'tGrouper%'
            and [name] not like 'H[_]%' 
            and [name] not like 'ICD%' 
            and [name] not like 'LL%' 
            and [name] not like 'LoanLU%' 
            and [name] not like 'LookUp%' 
            and [name] not like 'LU%' 
            and [name] not like 'DefLU%' 
            and [name] not like 'NU%' 
            and [name] not like 'W%' 
            and [name] not like 'X%' 
            and [name] not like 'Y%' 
            and [name] not like 'z%' 
            and [name] <> 'U_Users' 
        order by [Name]
    open cur_tbls
    fetch next from cur_tbls into @tbl
    while(@@fetch_status = 0)
    begin
        set @sql = 'DENY  SELECT, insert, update, delete  ON [dbo].[' + @tbl + '] TO ' + @Login + ' CASCADE '
        exec (@sql)
        fetch next from cur_tbls into @tbl
    end
    close cur_tbls
    deallocate cur_tbls

    declare cur_views cursor for
    select [Name]
    from dbo.sysobjects 
    where xtype = 'V' 
        and (
        (@CPI = 'Y' and ([Name] like 'Central_Patient%VR' or [Name] = 'ChartNumberMasked_VR')) or
        (@Location = 'Y' and [name] like 'ChartLocator%VR') or
        (@Deficiency = 'Y' and [name] like 'Chart_Deficiency%VR') or
        (@ROI = 'Y' and ([name] like 'RelOI%VR' or [name] = 'ReIOIMain_VR')) or
        (@Transcription = 'Y' and [name] like 'I10_Transcription%VR') or
        (@System = 'Y' and ([name] like 'M%' or [name] like 'Sec%' or 
            [Name] in ('Signature_VR', 'UserProfile_VR', 'WorkloadMeasurement_VR', 'wrSysUFields'))) or
        (@VisitHistory = 'Y' and [name] = 'VisitHistory_VR') or
        (@DAD = 'Y' and ([name] like 'DAD%VR' or 
                    ([name] like 'I10[_]%' and [name] not like 'I10[_]AmCare%' and [name] not like 'I10[_]Transcription%') or
                    ([name] like 'I9[_]%' and [name] not like 'I9[_]AmCare%') or
                    [name] in ('AbstractingErrorsWarnings_VR', 'CMG_Benchmarks_VR', 'Grouper_Audit_VR'))) or
        (@NACRS = 'Y' and ([name] like 'I9[_]AmCare%' or [name] like 'I10[_]AmCare%' or [name] like 'Amcare%VR' or
                    [name] in ('PAC10_CACS_VR'))) or
        (@Rehab = 'Y' and [name] like 'Rehab%VR') or
        (@CCRS = 'Y' and ([name] like 'CCRS%' or [name] = 'I10_CRS_General_VR')) or
        (@OMHRS = 'Y' and [name] like 'OMHRS%') or
        (@CCM = 'Y' and [name] like 'CCM%') or
        ([name] like 'BI%VR' or [Name] like 'LU%VR' or [Name] = 'Purged_Record_VR' or [name] like 'UD%' or [name] like 'W%' or [name] like 'V%')
        )


    open cur_views
    fetch next from cur_views into @tbl
    while(@@fetch_status = 0)
    begin
        set @sql = 'GRANT  SELECT  ON [dbo].[' + @tbl + '] TO ' + @Login 
        exec (@sql)
        fetch next from cur_views into @tbl
    end
    close cur_views
    deallocate cur_views




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [M_IndexCleanup]
AS
SET NOCOUNT ON
DECLARE @tablename VARCHAR (128)
DECLARE @execstr   VARCHAR (255)
DECLARE @objectid  INT
DECLARE @indexid   INT
DECLARE @frag      DECIMAL
DECLARE @maxfrag   DECIMAL

-- Decide on the maximum fragmentation to allow
SELECT @maxfrag = 15.0

-- Declare cursor
DECLARE tables CURSOR FOR
   SELECT TABLE_NAME
   FROM INFORMATION_SCHEMA.TABLES
   WHERE TABLE_TYPE = 'BASE TABLE'

-- Create the table
CREATE TABLE #fraglist (
   ObjectName CHAR (255),
   ObjectId INT,
   IndexName CHAR (255),
   IndexId INT,
   Lvl INT,
   CountPages INT,
   CountRows INT,
   MinRecSize INT,
   MaxRecSize INT,
   AvgRecSize INT,
   ForRecCount INT,
   Extents INT,
   ExtentSwitches INT,
   AvgFreeBytes INT,
   AvgPageDensity INT,
   ScanDensity DECIMAL,
   BestCount INT,
   ActualCount INT,
   LogicalFrag DECIMAL,
   ExtentFrag DECIMAL)

-- Open the cursor
OPEN tables

-- Loop through all the tables in the database
FETCH NEXT
   FROM tables
   INTO @tablename

WHILE @@FETCH_STATUS = 0
BEGIN
-- Do the showcontig of all indexes of the table
   INSERT INTO #fraglist 
   EXEC ('DBCC SHOWCONTIG (''' + @tablename + ''') 
      WITH FAST, TABLERESULTS, ALL_INDEXES, NO_INFOMSGS')
   FETCH NEXT
      FROM tables
      INTO @tablename
END

-- Close and deallocate the cursor
CLOSE tables
DEALLOCATE tables

-- Declare cursor for list of indexes to be defragged
DECLARE indexes CURSOR FOR
   SELECT ObjectName, ObjectId, IndexId, LogicalFrag
   FROM #fraglist
   WHERE LogicalFrag >= @maxfrag
      AND INDEXPROPERTY (ObjectId, IndexName, 'IndexDepth') > 0

-- Open the cursor
OPEN indexes

-- loop through the indexes
FETCH NEXT
   FROM indexes
   INTO @tablename, @objectid, @indexid, @frag

WHILE @@FETCH_STATUS = 0
BEGIN
   PRINT 'Executing DBCC INDEXDEFRAG (0, ' + RTRIM(@tablename) + ',
      ' + RTRIM(@indexid) + ') - fragmentation currently '
       + RTRIM(CONVERT(varchar(15),@frag)) + '%'
   SELECT @execstr = 'DBCC INDEXDEFRAG (0, ' + RTRIM(@objectid) + ',
       ' + RTRIM(@indexid) + ')'
   EXEC (@execstr)

   FETCH NEXT
      FROM indexes
      INTO @tablename, @objectid, @indexid, @frag
END

-- Close and deallocate the cursor
CLOSE indexes
DEALLOCATE indexes

-- Delete the temporary table
DROP TABLE #fraglist




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [M_IndexCleanupNew]
AS
Declare @TTName as VarChar(100)
Declare @SQL as VarChar(1000)

declare  cur_Btables cursor for
select table_name from information_schema.tables where TABLE_TYPE = 'BASE TABLE' 
and Table_name not like 'z%'
Open cur_Btables
fetch next from cur_Btables
into @TTName
while @@fetch_status = 0
begin
	set @SQL = 'DBCC DBREINDEX ([' + @TTName + '])'
	print @SQL
	Exec(@SQL)
	fetch next from cur_Btables 
	into @TTName
end
Close cur_Btables
Deallocate cur_Btables
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE procedure [M_IndexesInsert]
    @TableName varchar(50),
    @ColumnName varchar(50),
    @IndexType char(2),
    @IsCluster bit,
    @Comments varchar(255) = ''
as

if exists (
    select * 
    from M_Indexes 
    where TableName = @TableName
    and ColumnName = @ColumnName
) begin
    select Message = 'ERROR: An index is already defined for ' + @TableName + '.' + @ColumnName
    
    select * from M_Indexes 
    where TableName = @TableName
    and ColumnName = @ColumnName
    
    return 0
end

declare @idxid int

set @idxid = isnull((select max(idxid) from M_Indexes), 0) + 1

insert M_Indexes ( idxid, TableName, ColumnName, IndexType, IsCluster, Comments )
values ( @idxid, @TableName, @ColumnName, @IndexType, @IsCluster, @Comments )

select Message = 'SUCCESS: Index was added for ' + @TableName + '.' + @ColumnName

select * from M_Indexes where idxid = @idxid

return 0






GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE   PROCEDURE [M_NewIndexFind]
AS
	Declare @CurserValue as Varchar(255)
	
	Declare Cur_Temp cursor for
	select dbo.M_Indexes.idxid FROM dbo.M_Indexes INNER JOIN dbo.M_IndexType 
	ON dbo.M_Indexes.IndexType = dbo.M_IndexType.IndexType where 
	dbo.M_Indexes.IndexType + '_' + dbo.M_Indexes.TableName + '_' + 
	dbo.M_Indexes.ColumnName  not in (select name From sysindexes) and 
	dbo.M_Indexes.IndexType = 'IX'
	Open Cur_Temp    
	fetch next from Cur_Temp    
	into @CurserValue  
	while @@fetch_status = 0    
	begin    
		exec M_CreateIndex @CurserValue

		fetch next from Cur_Temp    
		into @CurserValue    
	end
	Close Cur_Temp
	Deallocate Cur_Temp



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO






/*This procedure is used for MED2020 Maintenance to
view tables, views and stored procedures*/
CREATE  PROCEDURE [M_OjectSearch]
	@Type as VarChar(10),
	@DBName as VarChar(50)
AS 

	Declare @SQL as VarChar(500)

	If @Type = 'Table'
	Begin
		Select @SQL = 'Select Table_Name from ' + @DBName + '.information_Schema.tables where 
		Table_Catalog = ''' + @DBName + ''' and table_Type = ''base table'' order by Table_Name'
		Exec (@SQL)
	end
	Else If @Type = 'View'
	Begin
		Select @SQL = 'Select Table_Name, View_Definition from ' + @DBName + '.information_Schema.VIEWS where 
		Table_Catalog = ''' + @DBName + ''' order by Table_Name'
		Exec (@SQL)
	end
	Else
	Begin
		Select @SQL = 'Select specific_name, Last_altered, Routine_Definition from ' + @DBName + '.information_Schema.ROUTINES 
		where specific_Catalog = ''' + @DBName + ''' Order by specific_name'
		Exec (@SQL)
	end

	Return 0




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO







CREATE   PROCEDURE [M_RecoveryMode]
	 @IsSimple bit = 1
AS 

declare @sql nvarchar(100)

set @sql = N'alter database ' + db_name() + ' set recovery ' + case @IsSimple when 1 then 'simple' else 'full' end
exec(@sql)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [M_SecurityMed2020]
	@DBName as VarChar(50)
AS 

	Declare @TableName as VarChar(100)
	Declare @SQL as VarChar(500)
	
	exec sp_grantdbaccess 'MED2020MAIN'
	--some hospital don't like to use WinRecs user  exec sp_grantdbaccess 'WinRecs'
	Exec sp_addsrvrolemember med2020main,  sysadmin
	
	Declare cur_temp cursor for 
	Select table_name from INFORMATION_SCHEMA.tables
		where table_catalog = @DBName
	Open cur_temp
	fetch next from cur_temp
	into @TableName
		While @@Fetch_Status = 0
		Begin
			Select @SQL = 'GRANT SELECT, INSERT, DELETE, REFERENCES, UPDATE
			ON [' + @TableName + '] TO MED2020MAIN'
			Exec (@SQL)
			fetch next from cur_temp
			into @TableName
		End
	Close Cur_Temp
	Deallocate Cur_Temp
	
	declare cur_temp1 cursor for 
	select specific_name from INFORMATION_SCHEMA.ROUTINES  
		where specific_catalog = @DBName
	Open cur_temp1
	fetch next from cur_temp1
	into @TableName
		While @@Fetch_Status = 0
		Begin
			Select @SQL = 'GRANT Execute
			ON [' + @TableName + '] TO MED2020MAIN'
			Exec (@SQL)
			fetch next from cur_temp1
			into @TableName
		End
	Close Cur_Temp1
	Deallocate Cur_Temp1
	
	declare cur_temp2 cursor for 
	select table_name from INFORMATION_SCHEMA.VIEWS  
		where table_catalog = @DBName
	Open cur_temp2
	fetch next from cur_temp2
	into @TableName
		While @@Fetch_Status = 0
		Begin
			Select @SQL = 'GRANT SELECT, INSERT, DELETE, REFERENCES, UPDATE
			ON [' + @TableName + '] TO MED2020MAIN'
			Exec (@SQL)
			fetch next from cur_temp2
			into @TableName
		End
	Close Cur_Temp2
	Deallocate Cur_Temp2
	
	----some hospital don't like to use WinRecs user 
	--declare cur_temp3 cursor for 
	--select table_name from INFORMATION_SCHEMA.VIEWS  
	--	where table_catalog = @DBName and (Table_Name like '%_VR'
 --           or Table_Name in ('I10_Abstracting ', 'I10_AbstractCIHIErrors_VR', 
 --               'I10_AmcareCIHIErrors', 'I10_CMG_2002Percentile'))
	--Open cur_temp3
	--fetch next from cur_temp3
	--into @TableName
	--	While @@Fetch_Status = 0
	--	Begin
	--		Select @SQL = 'GRANT SELECT ON [' + @TableName + '] TO WinRecs'
	--		Exec (@SQL)
	--		fetch next from cur_temp3
	--		into @TableName
	--	End
	--Close Cur_Temp3
	--Deallocate Cur_Temp3
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE procedure [M_ServerMemory]
    @min_mem int out, 
    @max_mem int out,
    @ram_mem int out
as

create table #sp_configure 
(
    name nvarchar(70),  -- Name of the configuration option. 
    minimum int,        -- Minimum value of the configuration option. 
    maximum int,        -- Maximum value of the configuration option. 
    config_value int,   -- Value to which the configuration option was set using sp_configure (value in sysconfigures.value). 
    run_value int       -- Value for the configuration option (value in syscurconfigs.value). 
)


insert #sp_configure
exec sp_configure @configname = N'min server memory (MB)' 

insert #sp_configure
exec sp_configure @configname = N'max server memory (MB)'

select @min_mem = run_value from #sp_configure where name = 'min server memory (MB)'
select @max_mem = run_value from #sp_configure where name = 'max server memory (MB)'

drop table #sp_configure


create table #xp_msver
(
    idx int,
    Name nvarchar(70),
    Internal_Value nvarchar(70),
    Character_Value nvarchar(70)
)

insert #xp_msver
exec master..xp_msver N'PhysicalMemory' 

select @ram_mem = Internal_Value from #xp_msver where name = N'PhysicalMemory'

drop table #xp_msver


return 0




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [M_SetViewPermission]
    @UserName as varchar(100) = 'WinRecs'
as
--EN - 00399
declare @CDKey varchar(50)
declare @PermitABS int
declare @PermitAMC int
declare @PermitDEF int
declare @PermitLOC int
declare @PermitROI int
declare @PermitTRN int
declare @PermitCPI int
declare @PermitCMG int
declare @PermitDPG int
declare @PermitCACS int
declare @PermitNRS int
declare @PermitCCRS int
declare @PermitOMH int
declare @PermitFLDA int
declare @PermitCC int
declare @PermitDAS int
declare @PermitCJRR int
declare @Value int

set @PermitABS = 0
set @PermitAMC = 0
set @PermitDEF = 0
set @PermitLOC = 0
set @PermitROI = 0
set @PermitTRN = 0
set @PermitCPI = 0
set @PermitCMG = 0
set @PermitDPG = 0
set @PermitCACS = 0
set @PermitNRS = 0
set @PermitCCRS = 0
set @PermitOMH = 0
set @PermitFLDA = 0
set @PermitCC = 0
set @PermitDAS = 0

if User_Id(@UserName ) is null
    Goto ExitSetting

if exists (select code from H_HospitalProfile where UseCJRR = 1)
    set @PermitCJRR = 1
else
    set @PermitCJRR = 0

declare cur_hospital cursor for
	select CDKey from H_HospitalProfile where len(CDKey) > 26
open cur_hospital
fetch next from cur_hospital into @CDKey
while(@@fetch_status = 0)
begin
	set @Value = ascii(substring(@CDKey, 2, 1))
	set @PermitABS = (case when (@Value % 2) = 0 or (@Value % 3) = 0 then 1 else @PermitABS end)
	set @Value = ascii(substring(@CDKey, 3, 1))
    set @PermitAMC = (case when (@Value % 2) = 0 or (@Value % 3) = 0 then 1 else @PermitAMC end)
	set @Value = ascii(substring(@CDKey, 5, 1))
    set @PermitDEF = (case when (@Value % 2) = 0 or (@Value % 3) = 0 then 1 else @PermitDEF end)
	set @Value = ascii(substring(@CDKey, 6, 1))
    set @PermitLOC = (case when (@Value % 2) = 0 or (@Value % 3) = 0 then 1 else @PermitLOC end)
	set @Value = ascii(substring(@CDKey, 8, 1))
    set @PermitROI = (case when (@Value % 2) = 0 or (@Value % 3) = 0 then 1 else @PermitROI end)
	set @Value = ascii(substring(@CDKey, 9, 1))
    set @PermitTRN = (case when (@Value % 2) = 0 or (@Value % 3) = 0 then 1 else @PermitTRN end)
	set @Value = ascii(substring(@CDKey, 12, 1))
    set @PermitCMG = (case when (@Value % 2) = 0 or (@Value % 3) = 0 then 1 else @PermitCMG end)

	set @Value = ascii(substring(@CDKey, 14, 1))
    set @PermitDPG = (case when (@Value % 2) = 0 or (@Value % 3) = 0 then 1 else @PermitDPG end)
	set @Value = ascii(substring(@CDKey, 15, 1))
    set @PermitCACS = (case when (@Value % 2) = 0 or (@Value % 3) = 0 then 1 else @PermitCACS end)

	set @Value = ascii(substring(@CDKey, 18, 1))
    set @PermitNRS = (case when (@Value % 2) = 0 or (@Value % 3) = 0 then 1 else @PermitNRS end)
	set @Value = ascii(substring(@CDKey, 20, 1))
    set @PermitCCRS = (case when (@Value % 2) = 0 or (@Value % 3) = 0 then 1 else @PermitCCRS end)
	set @Value = ascii(substring(@CDKey, 21, 1))
    set @PermitFLDA = (case when (@Value % 2) = 0 or (@Value % 3) = 0 then 1 else @PermitFLDA end)	--Audit
	set @Value = ascii(substring(@CDKey, 23, 1))
    set @PermitCC = (case when (@Value % 2) = 0 or (@Value % 3) = 0 then 1 else @PermitCC end) --Cancer
	set @Value = ascii(substring(@CDKey, 24, 1))
    set @PermitDAS = (case when (@Value % 2) = 0 or (@Value % 3) = 0 then 1 else @PermitDAS end)
	set @Value = ascii(substring(@CDKey, 25, 1))
    set @PermitOMH = (case when (@Value % 2) = 0 or (@Value % 3) = 0 then 1 else @PermitOMH end)

	fetch next from cur_hospital into @CDKey
end
close cur_hospital
deallocate cur_hospital
--Grant Permission
declare @TableName varchar(100)
declare @SQL varchar(2000)

declare cur_temp3 cursor for 
	select table_name from INFORMATION_SCHEMA.VIEWS  
	where (Table_Name like '%_VR'
        or Table_Name in ('I10_Abstracting ', 'I10_AbstractCIHIErrors_VR', 
            'I10_AmcareCIHIErrors', 'I10_CMG_2002Percentile'))
		and Table_Name not in ('I10_Abstracting_TEMISKAMING_VR', 'I10_Amcare_TEMISKAMING_VR') --0352
Open cur_temp3
fetch next from cur_temp3 into @TableName
	While @@Fetch_Status = 0
	Begin
		Select @SQL = 'GRANT SELECT ON [' + @TableName + '] TO ' + @UserName
		Exec (@SQL)
		fetch next from cur_temp3 into @TableName
	End
Close Cur_Temp3
Deallocate Cur_Temp3

--Deny permission

declare cur_views cursor for
select [Name]
from dbo.sysobjects 
where xtype = 'V' 
    and (
    --All module should in clude CPI. (@CPI = 0 and ([Name] like 'Central_Patient%VR' or [Name] = 'ChartNumberMasked_VR')) or 
    (@PermitLOC = 0 and [name] like 'ChartLocator%VR') or
    (@PermitDEF = 0 and [name] like 'Chart_Deficiency%VR') or
    (@PermitROI = 0 and ([name] like 'RelOI%VR' or [name] = 'ReIOIMain_VR' or [name] = 'UD_RelOI_VR')) or
    (@PermitTRN = 0 and [name] like 'I10_Transcription%VR') or
    (@PermitFLDA = 0 and (([name] like 'Sec%' and [name] not in ('Sec_SubmissionAudit', 'Sec_SubmissionRecord_VR', 'Sec_LoginAudit_VR', 'Sec_EncoderLog_VR')) or 
        [Name] in ('Signature_VR', 'WorkloadMeasurement_VR', 'wrSysUFields', 'Grouper_Audit_VR'))) or
    --'UserProfile_VR',  --PR - 05970    
    --(@VisitHistory = 0 and [name] = 'VisitHistory_VR') or
    (@PermitABS = 0 and ([name] like 'DAD%VR' or 
                ([name] like 'I10[_]%' and [name] not like 'I10[_]AmCare%' and [name] not like 'I10[_]Transcription%') or
                ([name] like 'I9[_]%' and [name] not like 'I9[_]AmCare%') or
                [name] in ('AbstractingErrorsWarnings_VR', 'CMG_Benchmarks_VR', 'Grouper_Audit_VR', 'I10_MB_ReproductiveNewborn_VR'))) or
    (@PermitAMC = 0 and ([name] like 'I9[_]AmCare%' or [name] like 'I10[_]AmCare%' or [name] like 'Amcare%VR' or
                [name] in ('PAC10_CACS_VR'))) or
    (@PermitNRS = 0 and [name] like 'Rehab%VR') or
    (@PermitCCRS = 0 and ([name] like 'MDS%' or [name] = 'I10_CRS_General_VR')) or
    (@PermitOMH = 0 and [name] like 'OMHRS%') or
    (@PermitCC = 0 and [name] like 'CCM%') or
    (@PermitDAS = 0 and [name] like 'MDAS%') or
    (@PermitCMG = 0 and ([name] like '%CMG%' or [name] like '%HIG%')) or
    (@PermitDPG = 0 and [name] like '%DPG%') or
    (@PermitCACS = 0 and [name] like '%CACS%')or
    (@PermitCJRR = 0 and [name] like 'CJRR%') 
    
    )


open cur_views
fetch next from cur_views into @TableName
while(@@fetch_status = 0)
begin
    set @sql = 'DENY  SELECT, insert, update, delete ON [dbo].[' + @TableName + '] TO ' + @UserName
    exec (@sql)
    fetch next from cur_views into @TableName
end
close cur_views
deallocate cur_views


set @sql = 'GRANT execute ON [R_ControlFile] TO ' + @UserName  --PR - 05773
exec (@sql)
set @sql = 'GRANT execute ON [R_DataDictionary] TO ' + @UserName  --PR - 05773
exec (@sql)
set @sql = 'GRANT execute ON [R_LookupDetail] TO ' + @UserName  --PR - 05773
exec (@sql)
set @sql = 'GRANT execute ON [R_LookupDetailByApplication] TO ' + @UserName  --PR - 05773
exec (@sql)
set @sql = 'GRANT execute ON [R_RehabSubmissionLog] TO ' + @UserName  --PR - 05773
exec (@sql)
set @sql = 'GRANT execute ON [R_Check_RecordLock] TO ' + @UserName  --PR - 05773
exec (@sql)
set @sql = 'GRANT execute ON [P_FetchDeficiencyLettersByProvider] TO ' + @UserName  --PR - 05773
exec (@sql)
set @sql = 'GRANT execute ON [P_FetchDeficiencyLettersForReport] TO ' + @UserName  --PR - 05773
exec (@sql)
set @sql = 'GRANT execute ON [R_Calculate_CodingDuration] TO ' + @UserName  --PR - 05773
exec (@sql)




set @sql = 'Deny SELECT ON [SU_SELECT_CCRS] TO ' + @UserName  --PR - 05773
exec (@sql)
set @sql = 'Deny SELECT ON [SU_SELECT_OMHRS] TO ' + @UserName  --PR - 05773
exec (@sql)
set @sql = 'Deny SELECT ON [SUF_GetQuery] TO ' + @UserName  --PR - 05773
exec (@sql)

--QBP Reports
if OBJECT_ID('GI_IndexCategory') > 0
begin
    set @sql = 'GRANT select ON GI_IndexCategory TO WinRecs'
    exec (@sql)
end
if OBJECT_ID('GI_InterventionGroup') > 0
begin
    set @sql = 'GRANT select ON GI_InterventionGroup TO WinRecs'
    exec (@sql)
end
if OBJECT_ID('GI_Mapping') > 0
begin
    set @sql = 'GRANT select ON GI_Mapping TO WinRecs'
    exec (@sql)
end
if OBJECT_ID('GI_MetalStentMap') > 0
begin
    set @sql = 'GRANT select ON GI_MetalStentMap TO WinRecs'
    exec (@sql)
end
if OBJECT_ID('GI_WeightUnit') > 0
begin
    set @sql = 'GRANT select ON GI_WeightUnit TO WinRecs'
    exec (@sql)
end
if exists (select * from information_schema.tables where table_name = 'zzGI_NACRS_ID')
begin
    set @sql = 'GRANT select ON zzGI_NACRS_ID TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT update ON zzGI_NACRS_ID TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT delete ON zzGI_NACRS_ID TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT insert ON zzGI_NACRS_ID TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT control ON zzGI_NACRS_ID TO ' + @UserName
    exec (@sql)
end
if exists (select * from information_schema.tables where table_name = 'zzGI_NACRS_CCI')
begin
    set @sql = 'GRANT select ON zzGI_NACRS_CCI TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT update ON zzGI_NACRS_CCI TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT delete ON zzGI_NACRS_CCI TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT insert ON zzGI_NACRS_CCI TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT control ON zzGI_NACRS_CCI TO ' + @UserName
    exec (@sql)
end
if exists (select * from information_schema.tables where table_name = 'zzGI_DAD_ID')
begin
    set @sql = 'GRANT select ON zzGI_DAD_ID TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT update ON zzGI_DAD_ID TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT delete ON zzGI_DAD_ID TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT insert ON zzGI_DAD_ID TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT control ON zzGI_DAD_ID TO ' + @UserName
    exec (@sql)
end
if exists (select * from information_schema.tables where table_name = 'zzGI_DAD_CCI')
begin
    set @sql = 'GRANT select ON zzGI_DAD_CCI TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT update ON zzGI_DAD_CCI TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT delete ON zzGI_DAD_CCI TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT insert ON zzGI_DAD_CCI TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT control ON zzGI_DAD_CCI TO ' + @UserName
    exec (@sql)
end
if exists (select * from information_schema.tables where table_name = 'zzGI_Weight')
begin
    set @sql = 'GRANT select ON zzGI_Weight TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT update ON zzGI_Weight TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT delete ON zzGI_Weight TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT insert ON zzGI_Weight TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT control ON zzGI_Weight TO ' + @UserName
    exec (@sql)
end
if OBJECT_ID('zzGI_DAD_Project_316') > 0
begin
    set @sql = 'GRANT select ON zzGI_DAD_Project_316 TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT update ON zzGI_DAD_Project_316 TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT delete ON zzGI_DAD_Project_316 TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT insert ON zzGI_DAD_Project_316 TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT control ON zzGI_DAD_Project_316 TO ' + @UserName
    exec (@sql)
end
if OBJECT_ID('zzGI_NACRS_Project_316') > 0
begin
    set @sql = 'GRANT select ON zzGI_NACRS_Project_316 TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT update ON zzGI_NACRS_Project_316 TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT delete ON zzGI_NACRS_Project_316 TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT insert ON zzGI_NACRS_Project_316 TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT control ON zzGI_NACRS_Project_316 TO ' + @UserName
    exec (@sql)
end
if OBJECT_ID('zzGI_MetalWeight') > 0
begin
    set @sql = 'GRANT select ON zzGI_MetalWeight TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT update ON zzGI_MetalWeight TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT delete ON zzGI_MetalWeight TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT insert ON zzGI_MetalWeight TO ' + @UserName
    exec (@sql)
    set @sql = 'GRANT control ON zzGI_MetalWeight TO ' + @UserName
    exec (@sql)
end
if exists (select * from information_schema.ROUTINES where ROUTINE_NAME = 'R_GI_Endoscopy_QBP')
begin
    set @sql = 'GRANT execute ON R_GI_Endoscopy_QBP TO ' + @UserName
    exec (@sql)
end
if OBJECT_ID('R_GI_MetalStentEndoscopy_QBP') > 0
begin
    set @sql = 'GRANT EXECUTE ON R_GI_MetalStentEndoscopy_QBP TO ' + @UserName
    exec (@sql)
end
if OBJECT_ID('R_GI_ExcisionRevision') > 0
begin
    set @sql = 'GRANT EXECUTE ON R_GI_ExcisionRevision TO ' + @UserName
    exec (@sql)
end
if OBJECT_ID('R_GI_CapsuleEndoscopy_QBP') > 0
begin
    set @sql = 'GRANT EXECUTE ON R_GI_CapsuleEndoscopy_QBP TO ' + @UserName
    exec (@sql)
end
if OBJECT_ID('GI_GetMetalType_Top3') > 0
begin
    set @sql = 'GRANT EXECUTE ON GI_GetMetalType_Top3 TO ' + @UserName
    exec (@sql)
end
if OBJECT_ID('GI_GetPrice_Top3') > 0
begin
    set @sql = 'GRANT EXECUTE ON GI_GetPrice_Top3 TO ' + @UserName
    exec (@sql)
end

ExitSetting:
    return 0
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO








CREATE    PROCEDURE [M_ShrinkDB]
	 @db sysname
AS 

declare @sql nvarchar(100)

set @db = db_name()

dbcc shrinkdatabase (@db)




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





/*Get contents of table for MED2020 maintenance*/
CREATE PROCEDURE [M_TableContents]
	@TableName as VarChar(50)
AS 

	Declare @SQL as VarChar(200)

	Select @SQL = 'Select * From ' + @TableName
	Exec (@SQL)
	Return 0




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO












CREATE  PROCEDURE [MG_GetMessageInfo]
	@MessageKey  as VarChar(10)
AS 

SELECT     	msgs.MessageKey, 
		msgs.MessageType, 
		msgs.MessageText, 
		msgs.ResponseType, 
		msgfld.FieldKey, 
		msgfld.MessageKey
FROM         	dbo.MG_Messages as msgs 
LEFT JOIN 	dbo.MG_MessageFields as msgfld 
ON 		msgs.MessageKey = msgfld.MessageKey
WHERE     	(msgs.MessageKey = @MessageKey)











GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO












CREATE  PROCEDURE [MG_GetMessageInfo2]
AS 

SELECT     	msgs.MessageKey as MK, 
		msgs.MessageType, 
		msgs.MessageText, 
		msgs.ResponseType, 
		msgfld.FieldKey, 
		msgfld.MessageKey
FROM         	dbo.MG_Messages as msgs 
LEFT JOIN 	dbo.MG_MessageFields as msgfld 
ON 		msgs.MessageKey = msgfld.MessageKey
ORDER BY	msgs.MessageKey, msgfld.FieldKey










GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO











CREATE   PROCEDURE [MG_GetMessageInfoFr]
AS 

SELECT     	msgs.MessageKey as MK, 
		msgs.MessageType, 
		msgs.MessageTextF, 
		msgs.ResponseType, 
		msgfld.FieldKey, 
		msgfld.MessageKey
FROM         	dbo.MG_Messages as msgs 
LEFT JOIN 	dbo.MG_MessageFields as msgfld 
ON 		msgs.MessageKey = msgfld.MessageKey
ORDER BY	msgs.MessageKey, msgfld.FieldKey











GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [NewLookUpKey] 
AS
begin
	set nocount on

	declare @i as int
	declare @lookUpID as int
	declare @engn as int
	declare @newID as int	

	set @i = 1
	set @lookUpID = (select cast(isnull([LookUpID], 0) as int) from [dbo].[W3_RecordKey])
	set @engn = (select cast(isnull(max([RecordID]), 0) as int) + 1 from [dbo].[ENGN_Edit])
	set @newID = (select cast(isnull([LookUpID], 0) as int) + 1 from [dbo].[W3_RecordKey])
	--make sure that the recordID is a new value
	if (@newID < @engn)
		set @newID = @engn

	while (@i < 50)
	begin
		update [dbo].[W3_RecordKey] set LookUpID = @newID where LookUpID = @lookUpID
		if @@ROWCOUNT > 0 break 
		--If it fails to update it means there was a colision (try again)
		set @lookUpID = (select cast(isnull([LookUpID], 0) as int) from [dbo].[W3_RecordKey])
		set @newID = @lookUpID + 1
		set @i = @i + 1	
	end
	if @i >= 50 set @newID = -1
	set nocount off;
	return @newID
end
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO















CREATE  PROCEDURE [NU_CodeSearch]
			@SearchCode varchar(15) ,		
			@SwitchFlag as int,
		        @OptionalStmt as varchar(10)
 AS

IF @OptionalStmt = '0' BEGIN
if @SwitchFlag = 2
    begin
	Select * FROM  dbo.NU_IntCodes 
		 WHERE  dbo.NU_IntCodes.CodeId <> 0 AND  
        		 CodeNum =   @SearchCode  ORDER BY   dbo.NU_IntCodes.CodeId  ASC
    end
if  @SwitchFlag = 1
     begin
	Select * FROM  dbo.NU_Codes
		 WHERE  dbo.NU_Codes.CodeId <> 0 AND  
          	 	 CodeNum =   @SearchCode  ORDER BY dbo.NU_Codes.CodeId ASC
     end
END
IF @OptionalStmt = '10000' BEGIN
if @SwitchFlag = 2
    begin
	Select * FROM  dbo.NU_IntCodesFr 
		 WHERE  dbo.NU_IntCodesFr.CodeId <> 0 AND  
        		 CodeNum =   @SearchCode  ORDER BY   dbo.NU_IntCodesFr.CodeId  ASC
    end
if  @SwitchFlag = 1
     begin
	Select * FROM  dbo.NU_CodesFr
		 WHERE  dbo.NU_CodesFr.CodeId <> 0 AND  
          	 	 CodeNum =   @SearchCode  ORDER BY dbo.NU_CodesFr.CodeId ASC
     end

END












GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
















Create   PROCEDURE [NU_CodeSearch2]
			@SearchCode varchar(15) ,		
			@SwitchFlag as int,
		        @OptionalStmt as varchar(10)
 AS

IF @OptionalStmt = '0' BEGIN
if @SwitchFlag = 2
    begin
	Select * FROM  dbo.NU_IntCodes 
		 WHERE  --dbo.NU_IntCodes.CodeId <> 0 AND  
        		 CodeNum =   @SearchCode  ORDER BY   dbo.NU_IntCodes.CodeId  ASC
    end
if  @SwitchFlag = 1
     begin
	Select * FROM  dbo.NU_Codes
		 WHERE  --dbo.NU_Codes.CodeId <> 0 AND  
          	 	 CodeNum =   @SearchCode  ORDER BY dbo.NU_Codes.CodeId ASC
     end
END
IF @OptionalStmt = '10000' BEGIN
if @SwitchFlag = 2
    begin
	Select * FROM  dbo.NU_IntCodesFr 
		 WHERE  --dbo.NU_IntCodesFr.CodeId <> 0 AND  
        		 CodeNum =   @SearchCode  ORDER BY   dbo.NU_IntCodesFr.CodeId  ASC
    end
if  @SwitchFlag = 1
     begin
	Select * FROM  dbo.NU_CodesFr
		 WHERE  --dbo.NU_CodesFr.CodeId <> 0 AND  
          	 	 CodeNum =   @SearchCode  ORDER BY dbo.NU_CodesFr.CodeId ASC
     end

END













GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO








CREATE      PROCEDURE [NU_CreatePrototypeDrugsEnglish] AS

-- Author: Brenda Vargas : Jan 24, 2007
-- Latest Change: 	   Feb 1, 2007
-- Creates new table  NU_DrugsLast  to be used by Drugs Prototype 
-- Pending:
	-- Change Name of tmp_DrugsLast Table when definitive
	-- Change it in TMP_LookUpDrugs_B as well 

-- Update:
	--- Changed tmp_DrugsLast Table for NU_DrugsLast 

-- Update: April 17, 2009 As per Folio 2009
	-- Not longer drop Nu_drugslast ONLY truncate table.

	
--NU_Drugs /  tmp_Drugs
declare @autoid as integer
declare @headerid integer
declare @SubHeaderId integer
declare	@SubHeaderId1 integer
declare	@SubHeaderId2 integer
declare	@SubHeaderId3 integer
declare @headerdesc varchar(255)
declare @headersearch varchar(255)
declare	@Chapter_XIX varchar (15)
declare	@Accidental varchar (15)
declare	@Intentional_Self_Harm varchar (15)
declare @Undetermined_Intent varchar (15)
declare	@Adverse_effect_in_therapeutic_use varchar (15)


declare @pt int
declare @strtmp  varchar(500)

declare @counter integer
declare @id integer
declare @itmp int

declare @tmplink1 varchar (15)
declare @tmplink2 varchar (15)
declare @tmplink3 varchar (15)
declare @tmplink4 varchar (15)

declare @tempoautoid as integer
declare @tempoheaderid integer
declare @tempoSubHeaderId integer
declare @tempoSubHeaderId1 integer
declare @tempoSubHeaderId2 integer
declare @tempoSubHeaderId3 integer
declare	@tempoChapter_XIX varchar (15)
declare	@tempoAccidental varchar (15)


CREATE TABLE tmp_Drugs (
	[AutoId] [int] NOT NULL ,
	[HeaderId] [int] NULL ,
	[SubHeaderId] [int] NULL ,
	[SubHeaderId1] [int] NULL ,
	[SubHeaderId2] [int] NULL ,
	[SubHeaderId3] [int] NULL ,
	[HeaderDesc] [varchar] (255)COLLATE Latin1_General_CI_AS NULL,
	[HeaderSearch] [varchar] (255) COLLATE Latin1_General_CI_AS NULL ,
	[Chapter_XIX] [varchar] (15) COLLATE Latin1_General_CI_AS NULL,
	[Accidental] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Intentional_Self_Harm] [varchar] (15) COLLATE Latin1_General_CI_AS NULL,
        [Undetermined_Intent] [varchar] (15) COLLATE Latin1_General_CI_AS NULL,
	[Adverse_effect_in_therapeutic_use] [varchar] (15) COLLATE Latin1_General_CI_AS NULL
	
) ON [PRIMARY]

truncate table NU_DrugsLast --- April 17, 2009 done for Folio 2009 

-- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Nu_DrugsLast]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
-- drop table [dbo].[Nu_DrugsLast]
-- 
-- 
-- CREATE TABLE NU_DrugsLast (
-- 	[AutoId] [int] NOT NULL ,
-- 	[HeaderId] [int] NULL ,
-- 	[SubHeaderId] [int] NULL ,
-- 	[SubHeaderId1] [int] NULL ,
-- 	[SubHeaderId2] [int] NULL ,
-- 	[SubHeaderId3] [int] NULL ,
-- 	[HeaderDesc] [varchar] (255) COLLATE Latin1_General_CI_AS NULL,
-- 	[HeaderSearch] [varchar] (255) COLLATE Latin1_General_CI_AS NULL ,
-- 	[Chapter_XIX] [varchar] (15) COLLATE Latin1_General_CI_AS NULL,
-- 	[Accidental] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
-- 	[Intentional_Self_Harm] [varchar] (15) COLLATE Latin1_General_CI_AS NULL,
--         [Undetermined_Intent] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
-- 	[Adverse_effect_in_therapeutic_use] [varchar] (15)COLLATE Latin1_General_CI_AS NULL
-- 	
-- ) ON [PRIMARY]


-- COLUMN Chapter XIX
INSERT INTO tmp_Drugs (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Chapter_XIX )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, codelink 
from NU_Drugs  where headerdesc like '%Chapter XIX%' 

-- COLUMN Accidental
INSERT INTO tmp_Drugs (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Accidental )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, codelink 
from NU_Drugs  where headerdesc like '%Accidental%'

-- COLUMN Intentional 
INSERT INTO tmp_Drugs (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Intentional_Self_Harm )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, codelink 
from NU_Drugs  where headerdesc like '%Intentional%'

-- COLUMN Undetermined 
INSERT INTO tmp_Drugs (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Undetermined_Intent )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, codelink 
from NU_Drugs  where headerdesc like '%Undetermined%'

-- COLUMN Adverse effect 
INSERT INTO tmp_Drugs (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Adverse_effect_in_therapeutic_use )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, codelink 
from NU_Drugs  where headerdesc like '%Adverse effect%'

------------------------------------- LEAVING JUST ONE ROW FOR HEADER IN NU_DrugsLast 
-- COLUMN Charter XIX
INSERT INTO NU_DrugsLast  (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Chapter_XIX )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Chapter_XIX from tmp_drugs  where Chapter_XIX is not null 

-- OTHERS COLUMNS 
declare cursor_NU_DrugsLast CURSOR FOR
select * from NU_DrugsLast  
open cursor_Nu_DrugsLast

FETCH NEXT FROM cursor_NU_DrugsLast 
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @HeaderDesc, @HeaderSearch, @Chapter_XIX, @Accidental, @Intentional_Self_Harm, @Undetermined_Intent, @Adverse_effect_in_therapeutic_use


-- LEAVING JUST ONE ROW FOR HEADER
WHILE @@FETCH_STATUS = 0
BEGIN
	set @tmplink1 = null
	set @tmplink2 = null
	set @tmplink3 = null
	set @tmplink4 = null

       	select @tmplink1= Accidental from tmp_drugs 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and Accidental is not null
	select @tmplink2= Intentional_Self_Harm from tmp_drugs 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and Intentional_Self_Harm is not null
	select @tmplink3= Undetermined_Intent from tmp_drugs 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and Undetermined_Intent is not null
	select @tmplink4= Adverse_effect_in_therapeutic_use from tmp_drugs 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and Adverse_effect_in_therapeutic_use is not null


	UPDATE Nu_DrugsLast
		SET Accidental = @tmplink1,
		Intentional_Self_Harm = @tmplink2,
		Undetermined_Intent = @tmplink3,
		Adverse_effect_in_therapeutic_use = @tmplink4
		WHERE   headerid     =  @headerid and 
			subheaderid  = @subheaderid and  
			subheaderid1 = @Subheaderid1 and
			subheaderid2 = @Subheaderid2 and
			subheaderid3 = @Subheaderid3
	
FETCH NEXT FROM cursor_Nu_DrugsLast
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @HeaderDesc, @HeaderSearch, @Chapter_XIX, @Accidental, @Intentional_Self_Harm, @Undetermined_Intent, @Adverse_effect_in_therapeutic_use

END


CLOSE cursor_Nu_DrugsLast
DEALLOCATE cursor_Nu_DrugsLast


-- FIXING DUPLICATE ROWS 
select * into tempo_drugslast from NU_DrugsLast --: created backup table 

--INSERT INTO NU_DrugsLast select *  from tempo_drugslast  

declare @count as integer

declare cur_NU_DrugsLast CURSOR FOR
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, Chapter_XIX, Accidental
	 from NU_DrugsLast order by autoid
open cur_Nu_DrugsLast

FETCH NEXT FROM cur_NU_DrugsLast 
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @Chapter_XIX, @Accidental

WHILE @@FETCH_STATUS = 0
BEGIN
	-- Inner cursor
	declare cur_tempo CURSOR FOR
	select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, Chapter_XIX, Accidental from tempo_drugslast   
	WHERE 	headerid = @headerid and subheaderid = @subheaderid and SubHeaderId1 = @SubHeaderId1 and SubHeaderId2 = @SubHeaderId2 
		and  SubHeaderId3 = @SubHeaderId3

	open cur_tempo

	set @count = 0 
	
	FETCH NEXT FROM cur_tempo 
	INTO @tempoautoid, @tempoheaderid, @tempoSubHeaderId, @tempoSubHeaderId1, @tempoSubHeaderId2, @tempoSubHeaderId3, @tempoChapter_XIX, @tempoAccidental
	
	WHILE @@FETCH_STATUS = 0
	BEGIN
		--PRINT @COUNT 
		set @count = @count + 1
	 
		if @count = 2  
		begin 
			-- Update first row of the Nu_DrugsLast
			
			UPDATE NU_DrugsLast SET Accidental = @tempoChapter_XIX
			WHERE   headerid = @headerid and 
				subheaderid = @subheaderid and 
				SubHeaderId1 = @SubHeaderId1 and 
				SubHeaderId2 = @SubHeaderId2 and
				SubHeaderId3 = @SubHeaderId3 and 
				autoid = @autoid

			-- Delete second row of the Nu_DrugsLast
			
			DELETE NU_DrugsLast 
			WHERE 	headerid = @headerid and 
				subheaderid  = @subheaderid anD 
				subheaderid1 = @Subheaderid1 and 
				SubHeaderId2 = @SubHeaderId2 and
				SubHeaderId3 = @SubHeaderId3 and 
				autoid = @tempoautoid 
                   
		end

	        FETCH NEXT FROM cur_tempo
	INTO @tempoautoid, @tempoheaderid, @tempoSubHeaderId, @tempoSubHeaderId1, @tempoSubHeaderId2, @tempoSubHeaderId3, @tempoChapter_XIX, @tempoAccidental	

			
	END
	CLOSE cur_tempo
	DEALLOCATE cur_tempo
	
FETCH NEXT FROM cur_Nu_DrugsLast
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @Chapter_XIX, @Accidental

END


CLOSE cur_Nu_DrugsLast
DEALLOCATE cur_Nu_DrugsLast

-- Remove words "Chapter XIX" at the end --

--select ltrim(rtrim(substring(headersearch,1,len(headersearch)- 21))), headersearch, headerdesc
-- from NU_DrugsLast where headersearch like '%Chapter XIX%' 


UPDATE Nu_DrugsLast
		SET headerdesc = rtrim(substring(headerdesc,1,len(headerdesc)- 21)),
		  headersearch = rtrim(substring(headersearch,1,len(headersearch)- 21))
		WHERE  headerdesc like '%Chapter XIX%' 



-- CODELINK = ''  dejar de ultimo
INSERT INTO NU_DrugsLast (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch)
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch 
from NU_Drugs  where codelink = ''


drop table tmp_Drugs
drop table tempo_drugslast







GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE    PROCEDURE [NU_CreatePrototypeDrugsFrench] AS

-- Author: Brenda Vargas : Jan 24, 2007
-- Latest change:	   Feb 1, 2007
-- Creates new table  Nu_DrugsFrLast  to be used by Drugs Prototype 
-- Pending:
	-- Change Name of tmp_DrugsFrLast Table when definitive
	-- Change it on TMP_LookUpDrugs_B
-- Modified Aug 22, 2007
	-- Changed tmp_DrugsFrLast Table to Nu_DrugsFrLast
	

--NU_DrugsFr /  tmp_DrugsFr / Nu_DrugsFrLast

declare @autoid as integer
declare @headerid integer
declare @SubHeaderId integer
declare	@SubHeaderId1 integer
declare	@SubHeaderId2 integer
declare	@SubHeaderId3 integer
declare @headerdesc varchar(255)
declare @headersearch varchar(255)
declare	@Chapter_XIX varchar (15)
declare	@Accidental varchar (15)
declare	@Intentional_Self_Harm varchar (15)
declare @Undetermined_Intent varchar (15)
declare	@Adverse_effect_in_therapeutic_use varchar (15)

declare @pt int
declare @strtmp  varchar(500)

declare @counter integer
declare @id integer
declare @itmp int

declare @tmplink1 varchar (15)
declare @tmplink2 varchar (15)
declare @tmplink3 varchar (15)
declare @tmplink4 varchar (15)

declare @tempoautoid as integer
declare @tempoheaderid integer
declare @tempoSubHeaderId integer
declare @tempoSubHeaderId1 integer
declare @tempoSubHeaderId2 integer
declare @tempoSubHeaderId3 integer
declare	@tempoChapter_XIX varchar (15)
declare	@tempoAccidental varchar (15)


CREATE TABLE tmp_DrugsFr (
	[AutoId] [int] NOT NULL ,
	[HeaderId] [int] NULL ,
	[SubHeaderId] [int] NULL ,
	[SubHeaderId1] [int] NULL ,
	[SubHeaderId2] [int] NULL ,
	[SubHeaderId3] [int] NULL ,
	[HeaderDesc] [varchar] (255)COLLATE Latin1_General_CI_AS NULL,
	[HeaderSearch] [varchar] (255) COLLATE Latin1_General_CI_AS NULL ,
	[Chapter_XIX] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Accidental] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Intentional_Self_Harm] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
        [Undetermined_Intent] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Adverse_effect_in_therapeutic_use] [varchar] (15) COLLATE Latin1_General_CI_AS NULL
	
) ON [PRIMARY]

drop table Nu_DrugsFrLast 

CREATE TABLE Nu_DrugsFrLast (
	[AutoId] [int] NOT NULL ,
	[HeaderId] [int] NULL ,
	[SubHeaderId] [int] NULL ,
	[SubHeaderId1] [int] NULL ,
	[SubHeaderId2] [int] NULL ,
	[SubHeaderId3] [int] NULL ,
	[HeaderDesc] [varchar] (255) COLLATE Latin1_General_CI_AS NULL,
	[HeaderSearch] [varchar] (255)COLLATE Latin1_General_CI_AS NULL ,
	[Chapter_XIX] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Accidental] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Intentional_Self_Harm] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
        [Undetermined_Intent] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Adverse_effect_in_therapeutic_use] [varchar] (15)COLLATE Latin1_General_CI_AS NULL
	
) ON [PRIMARY]

-- IMPORTANT!!!!!!         For FRENCH I'LL USE HEADERSEARCH INSTEAD OF HEADERDESC (Because of accent) 

-- COLUMN Chapitre XIX
INSERT INTO tmp_DrugsFr (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Chapter_XIX )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, codelink 
from NU_DrugsFr  where headersearch like '%Chapitre XIX%' 

-- COLUMN Accidentel
INSERT INTO tmp_DrugsFr (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Accidental )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, codelink 
from NU_DrugsFr  where headersearch like '%Accidentel%'

-- COLUMN Intentionnel auto-induit
INSERT INTO tmp_DrugsFr (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Intentional_Self_Harm )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, codelink 
from NU_DrugsFr  where headersearch like '%Intentionnel auto-induit%'

-- COLUMN Intention non-determinee
INSERT INTO tmp_DrugsFr (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Undetermined_Intent )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, codelink 
from NU_DrugsFr  where  headersearch like  '%Intention non-determinee%'

-- COLUMN Effet indesirable en usage therapeutique
INSERT INTO tmp_DrugsFr (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Adverse_effect_in_therapeutic_use )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, codelink 
from NU_DrugsFr  where headersearch like '%indesirable en usage therapeutique%'

------------------------------------- LEAVING JUST ONE ROW FOR HEADER IN Nu_DrugsFrLast 
-- COLUMN Charter XIX
INSERT INTO Nu_DrugsFrLast  (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Chapter_XIX )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Chapter_XIX from tmp_DrugsFr  where Chapter_XIX is not null 

-- OTHERS COLUMNS 
declare cursor_Nu_DrugsFrLast CURSOR FOR
select * from Nu_DrugsFrLast  
open cursor_Nu_DrugsFrLast

FETCH NEXT FROM cursor_Nu_DrugsFrLast 
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @HeaderDesc, @HeaderSearch, @Chapter_XIX, @Accidental, @Intentional_Self_Harm, @Undetermined_Intent, @Adverse_effect_in_therapeutic_use


-- LEAVING JUST ONE ROW FOR HEADER
WHILE @@FETCH_STATUS = 0
BEGIN
	set @tmplink1 = null
	set @tmplink2 = null
	set @tmplink3 = null
	set @tmplink4 = null

       	select @tmplink1= Accidental from tmp_DrugsFr 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and Accidental is not null
	select @tmplink2= Intentional_Self_Harm from tmp_DrugsFr 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and Intentional_Self_Harm is not null
	select @tmplink3= Undetermined_Intent from tmp_DrugsFr 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and Undetermined_Intent is not null
	select @tmplink4= Adverse_effect_in_therapeutic_use from tmp_DrugsFr 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and Adverse_effect_in_therapeutic_use is not null


	UPDATE Nu_DrugsFrLast
		SET Accidental = @tmplink1,
		Intentional_Self_Harm = @tmplink2,
		Undetermined_Intent = @tmplink3,
		Adverse_effect_in_therapeutic_use = @tmplink4
		WHERE   headerid     =  @headerid and 
			subheaderid  = @subheaderid and  -- Jan 22
			subheaderid1 = @Subheaderid1 and
			subheaderid2 = @Subheaderid2 and
			subheaderid3 = @Subheaderid3
	
FETCH NEXT FROM cursor_Nu_DrugsFrLast
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @HeaderDesc, @HeaderSearch, @Chapter_XIX, @Accidental, @Intentional_Self_Harm, @Undetermined_Intent, @Adverse_effect_in_therapeutic_use

END


CLOSE cursor_Nu_DrugsFrLast
DEALLOCATE cursor_Nu_DrugsFrLast


-- CODELINK = ''  dejar de ultimo
INSERT INTO Nu_DrugsFrLast (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch)
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch 
from NU_DrugsFr  where codelink = ''

  
-- FIXING DUPLICATE ROWS 
select * into tempo_drugsFrlast from Nu_DrugsFrLast --: created backup table 

--INSERT INTO Nu_DrugsFrLast select *  from tempo_drugsfrlast  
--Drop table tempo_drugsFrlast

delete Nu_DrugsFrLast

declare @myAutoid as integer

declare cur_tempo_DrugsFrlast CURSOR FOR
select *  from tempo_DrugsFrlast order by autoid
open cur_tempo_DrugsFrlast


FETCH NEXT FROM cur_tempo_DrugsFrlast 
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @HeaderDesc, @HeaderSearch, @Chapter_XIX, @Accidental,  @Intentional_Self_Harm, @Undetermined_Intent, @Adverse_effect_in_therapeutic_use

set @myAutoid = 0

WHILE @@FETCH_STATUS = 0
BEGIN
	
	if @myAutoid <> @Autoid
	begin 
	  -- Insert only the first row found
	  INSERT INTO Nu_DrugsFrLast  (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Chapter_XIX, Accidental,  Intentional_Self_Harm, Undetermined_Intent, Adverse_effect_in_therapeutic_use )
	  VALUES  (@Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @HeaderDesc, @HeaderSearch, @Chapter_XIX, @Accidental,  @Intentional_Self_Harm, @Undetermined_Intent, @Adverse_effect_in_therapeutic_use )
	
	  set @myAutoid = @Autoid
	          
	end
	        
	FETCH NEXT FROM cur_tempo_DrugsFrlast
        INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @HeaderDesc, @HeaderSearch, @Chapter_XIX, @Accidental,  @Intentional_Self_Harm, @Undetermined_Intent, @Adverse_effect_in_therapeutic_use


END

CLOSE cur_tempo_DrugsFrlast
DEALLOCATE cur_tempo_DrugsFrlast

-- Remove words "Empoisonnement Chapitre XIX codelink" at the end --

--select ltrim(rtrim(substring(headersearch,1,len(headersearch)- 21))), headersearch, headerdesc
-- from Nu_DrugsFrLast where headersearch like '%Poisoning Chapter XIX' 


UPDATE Nu_DrugsFrLast
		SET headerdesc = rtrim(substring(headerdesc,1,len(headerdesc)- (Len(Chapter_XiX)+29))),
		  headersearch = rtrim(substring(headersearch,1,len(headersearch)- (Len(Chapter_XiX)+29)))
		WHERE  headerdesc like '%Empoisonnement Chapitre XIX%' 



drop table tmp_DrugsFr
drop table tempo_DrugsFrLast





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO







CREATE                                            PROCEDURE [NU_CreatePrototypeNeoplasmEnglish] AS

-- Author: Brenda Vargas : Jan 26, 2007
-- Latest change: 	   Feb 1, 2007
-- Creates new table  tmp_NeoplasmLast  to be used by Neoplasm Prototype 
-- Pending:
	-- Change Name of tmp_NeoplasmLast Table when definitive
	-- Change it on TMP_LookUpNeoplasm_B

-- Important !!!!! Jan 31:   
-- This sp will run taking WR284_NU_Neoplasm table from WinRecs 2.8.4 - The current NU_Neoplasm is out of alignment 
-- I will replace NU_Neoplasm for WR284_NU_Neoplasm

-- Important !!!!  Feb 12:
-- I'm using NU_NeoplasmTmp table :this is New Simon parsed table from NFO
-- I'll replace WR284_NU_Neoplasm for NU_NeoplasmTmp

-- Important !!!!  Feb 13:
-- I'm using NU_NeoplasmNewEn table :this is New Simon parsed table from NFO
-- I'll replace NU_NeoplasmTmp for NU_NeoplasmNewEn
-- Namiul August 03:
-- The NU_NeoplasmNewEn no longer exists with new Parse of English Tables [August 03, 2007] Replacing NU_NeoplasmNewEn with NU_Neoplasm
-- Add subheader4 in NU_Neoplasm if it does not exists

-- bv Aug 21, 2007:
-- Changed tmp_NeoplasmLast Table to Nu_NeoplasmLast


-- NU_Neoplasm/  tmp_Neoplasm /NU_NeoplasmLast
declare @autoid as integer
declare @headerid integer
declare @SubHeaderId integer
declare	@SubHeaderId1 integer
declare	@SubHeaderId2 integer
declare	@SubHeaderId3 integer
declare	@SubHeaderId4 integer
declare @headerdesc varchar(255)
declare @headersearch varchar(255)
declare	@Malignant_Primary varchar (15)
declare	@Malignant_Secondary varchar (15)
declare	@In_Situ varchar (15)
declare @Benign varchar (15)
declare	@Uncertain_or_Unknown_Behaviour varchar (15)

declare @pt int
declare @strtmp  varchar(500)

declare @counter integer
declare @id integer
declare @itmp int

declare @tmplink1 varchar (15)
declare @tmplink2 varchar (15)
declare @tmplink3 varchar (15)
declare @tmplink4 varchar (15)

declare @tempoautoid as integer
declare @tempoheaderid integer
declare @tempoSubHeaderId integer
declare @tempoSubHeaderId1 integer
declare @tempoSubHeaderId2 integer
declare @tempoSubHeaderId3 integer
declare	@tempoMalignant_Primary varchar (15)
declare	@tempoMalignant_Secondary varchar (15)


CREATE TABLE tmp_Neoplasm (
	[AutoId] [int] NOT NULL ,
	[HeaderId] [int] NULL ,
	[SubHeaderId] [int] NULL ,
	[SubHeaderId1] [int] NULL ,
	[SubHeaderId2] [int] NULL ,
	[SubHeaderId3] [int] NULL ,
	[SubHeaderId4] [int] NULL ,
	[HeaderDesc] [varchar] (255) COLLATE Latin1_General_CI_AS NULL,
	[HeaderSearch] [varchar] (255)COLLATE Latin1_General_CI_AS NULL ,
	[Malignant_Primary] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Malignant_Secondary] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[In_Situ] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
        [Benign] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Uncertain_or_Unknown_Behaviour] [varchar] (15)COLLATE Latin1_General_CI_AS NULL
	
) ON [Primary]

-- April 17, 2009 as Folio 2009 
truncate table  NU_NeoplasmLast

-- -- ---Namiul
-- -- if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[NU_NeoplasmLast]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
-- -- drop table [dbo].[NU_NeoplasmLast]
-- -- 
-- -- ----Namiul
-- -- if not exists (select * from dbo.syscolumns where [name] like 'SubHeaderId4' AND  id = object_id(N'[dbo].[NU_Neoplasm]') and OBJECTPROPERTY(id, N'IsUserTable') = 1 ) AND 
-- -- (exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[NU_Neoplasm]') and OBJECTPROPERTY(id, N'IsUserTable') = 1))  
-- -- 	ALTER TABLE NU_Neoplasm ADD  [SubHeaderId4] [int] NOT NULL  DEFAULT (0)
-- -- 
-- -- 
-- -- 
-- -- CREATE TABLE NU_NeoplasmLast (
-- -- 	[AutoId] [int] NOT NULL ,
-- -- 	[HeaderId] [int] NULL ,
-- -- 	[SubHeaderId] [int] NULL ,
-- -- 	[SubHeaderId1] [int] NULL ,
-- -- 	[SubHeaderId2] [int] NULL ,
-- -- 	[SubHeaderId3] [int] NULL ,
-- -- 	[SubHeaderId4] [int] NULL ,
-- -- 	[HeaderDesc] [varchar] (255) COLLATE Latin1_General_CI_AS NULL,
-- -- 	[HeaderSearch] [varchar] (255)COLLATE Latin1_General_CI_AS NULL ,
-- -- 	[Malignant_Primary] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
-- -- 	[Malignant_Secondary] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
-- -- 	[In_Situ] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
-- --         [Benign] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
-- -- 	[Uncertain_or_Unknown_Behaviour] [varchar] (15)COLLATE Latin1_General_CI_AS NULL
-- -- 	
-- -- ) ON [Primary]


-- COLUMN Malignant_Primary
INSERT INTO tmp_Neoplasm (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Malignant_Primary )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, codelink 
from NU_Neoplasm where headerdesc like '%Primary%' 

-- COLUMN Malignant_Secondary
INSERT INTO tmp_Neoplasm (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Malignant_Secondary )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, codelink 
from NU_Neoplasm where headerdesc like '%Secondary%'

-- COLUMN In situ
INSERT INTO tmp_Neoplasm (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, In_Situ )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, codelink 
from NU_Neoplasm where headerdesc like '%In situ%'

-- COLUMN Benign
INSERT INTO tmp_Neoplasm (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Benign )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, codelink 
from NU_Neoplasm where headerdesc like '%Benign%'

-- COLUMN Uncertain or unknown behaviour
INSERT INTO tmp_Neoplasm (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Uncertain_or_Unknown_Behaviour )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, codelink 
from NU_Neoplasm where headerdesc like '%Uncertain Or Unknown%'

------------------------------------- LEAVING JUST ONE ROW FOR HEADER IN NU_NeoplasmLast 
-- COLUMN Malignant_Primary
INSERT INTO NU_NeoplasmLast  (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Malignant_Primary )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Malignant_Primary from tmp_Neoplasm  where Malignant_Primary is not null 

-- OTHERS COLUMNS 
declare cursor_NU_NeoplasmLast CURSOR FOR
select * from NU_NeoplasmLast  
open cursor_NU_NeoplasmLast

FETCH NEXT FROM cursor_NU_NeoplasmLast 
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @SubHeaderId4, @HeaderDesc, @HeaderSearch, @Malignant_Primary, @Malignant_Secondary, @In_Situ, @Benign, @Uncertain_or_Unknown_Behaviour


-- LEAVING JUST ONE ROW FOR HEADER
WHILE @@FETCH_STATUS = 0
BEGIN
	set @tmplink1 = null
	set @tmplink2 = null
	set @tmplink3 = null
	set @tmplink4 = null

       	select @tmplink1= Malignant_Secondary from tmp_Neoplasm 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and subheaderid4 = @subheaderid4
				and Malignant_Secondary is not null
	select @tmplink2= In_Situ from tmp_Neoplasm 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and subheaderid4 = @subheaderid4
				and In_Situ is not null
	select @tmplink3= Benign from tmp_Neoplasm 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and subheaderid4 = @subheaderid4
				and Benign is not null
	select @tmplink4= Uncertain_or_Unknown_Behaviour from tmp_Neoplasm 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and subheaderid4 = @subheaderid4
				and Uncertain_or_Unknown_Behaviour is not null


	UPDATE NU_NeoplasmLast
		SET Malignant_Secondary = @tmplink1,
		In_Situ = @tmplink2,
		Benign = @tmplink3,
		Uncertain_or_Unknown_Behaviour = @tmplink4
		WHERE   Autoid 	     = @Autoid and 
			headerid     = @headerid and 
			subheaderid  = @subheaderid and
			subheaderid1 = @Subheaderid1 and
			subheaderid2 = @Subheaderid2 and
			subheaderid3 = @Subheaderid3 and
			subheaderid4 = @subheaderid4
	
FETCH NEXT FROM cursor_NU_NeoplasmLast
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @SubHeaderId4, @HeaderDesc, @HeaderSearch, @Malignant_Primary, @Malignant_Secondary, @In_Situ, @Benign, @Uncertain_or_Unknown_Behaviour

END

CLOSE cursor_NU_NeoplasmLast
DEALLOCATE cursor_NU_NeoplasmLast


-- Remove words "Malignes Primitives codelinks" at the end --

UPDATE NU_NeoplasmLast
		SET headerdesc = rtrim(substring(Headerdesc,1,CHARINDEX('Malignant Primary', headerdesc, 1)-1 )),
		    headersearch = rtrim(substring(headerSearch,1,CHARINDEX('Malignant Primary', headerSearch, 1)-1 ))	
	WHERE  headerdesc like '%Malignant Primary%' 


-- Do not execute this part.  It's not necesary after latest Simon parse 
-- CODELINK = ''  leave at the end
--INSERT INTO tmp_NeoplasmFrLAST (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4,
--HeaderDesc, HeaderSearch)
--select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch 
--from NU_NeoplasmLastFr  where codelink = ''


UPDATE NU_NeoplasmLast SET  Malignant_Primary = null  WHERE Malignant_Primary = ''  


-- Replace character "|" for "-" resolve problem in VB
UPDATE NU_NeoplasmLast SET headerdesc=replace(headerdesc,char(150),char(45)) 



-- Original when use NU_Neoplam
--UPDATE NU_NeoplasmLast
--		SET headerdesc = rtrim(substring(headerdesc,1,len(headerdesc)- (Len(Malignant_Primary)+18))), 
--		    headersearch =' ' +  rtrim(substring(headersearch,1,len(headersearch)- (Len(Malignant_Primary)+19)))
--		WHERE  headerdesc like '%Malignant Primary%' 


-- To run with WR284 table 
------------------- Commented for now. Feb 12, 2007
--UPDATE NU_NeoplasmLast
--		SET headerdesc = rtrim(substring(headerdesc,1,len(headerdesc)- (Len(Malignant_Primary)+19))), 
--		    headersearch = rtrim(substring(headersearch,1,len(headersearch)- (Len(Malignant_Primary)+21)))
--		WHERE  headerdesc like '%Malignant Primary%' 


-- add space to last codes inserted  Important!!!! Not necessary when run with WinRecs284 Table 
--UPDATE NU_NeoplasmLast
--SET   headersearch= ' ' +  headersearch
-- where malignant_Primary is null


-- Drop tables
drop table tmp_Neoplasm









GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO












CREATE                                             PROCEDURE [NU_CreatePrototypeNeoplasmFrench] AS

-- Author: Brenda Vargas : Jan 29, 2007
-- Latest change: 	 : Feb 1, 2007
-- Creates new table  tmp_NeoplasmFrLast  to be used by Neoplasm Prototype 
-- Pending:
	-- Change Name of tmp_NeoplasmFrLast Table when definitive
	-- Change it on TMP_LookUpNeoplasm_B as well
-- Important I'm using NU_NeoplasmLastFr table :this is New Simon parsed table
-- (ORIGINAL TABLE IS NU_NeoplasmFrTmp Feb 8, 2007). I replace NU_NeoplasmFr for 
-- NU_NeoplasmLastFr
	

-- NU_NeoplasmLastFr /  tmp_NeoplasmFr /tmp_NeoplasmFrLast
declare @autoid as integer
declare @headerid integer
declare @SubHeaderId integer
declare	@SubHeaderId1 integer
declare	@SubHeaderId2 integer
declare	@SubHeaderId3 integer
declare	@SubHeaderId4 integer
declare @headerdesc varchar(255)
declare @headersearch varchar(255)
declare	@Malignant_Primary varchar (15)
declare	@Malignant_Secondary varchar (15)
declare	@In_Situ varchar (15)
declare @Benign varchar (15)
declare	@Uncertain_or_Unknown_Behaviour varchar (15)

declare @pt int
declare @strtmp  varchar(500)

declare @counter integer
declare @id integer
declare @itmp int

declare @tmplink1 varchar (15)
declare @tmplink2 varchar (15)
declare @tmplink3 varchar (15)
declare @tmplink4 varchar (15)

declare @tempoautoid as integer
declare @tempoheaderid integer
declare @tempoSubHeaderId integer
declare @tempoSubHeaderId1 integer
declare @tempoSubHeaderId2 integer
declare @tempoSubHeaderId3 integer
declare	@tempoMalignant_Primary varchar (15)
declare	@tempoMalignant_Secondary varchar (15)


CREATE TABLE tmp_NeoplasmFr (
	[AutoId] [int] NOT NULL ,
	[HeaderId] [int] NULL ,
	[SubHeaderId] [int] NULL ,
	[SubHeaderId1] [int] NULL ,
	[SubHeaderId2] [int] NULL ,
	[SubHeaderId3] [int] NULL ,
        [SubHeaderId4] [int] NULL ,
	[HeaderDesc] [varchar] (255) COLLATE Latin1_General_CI_AS NULL,
	[HeaderSearch] [varchar] (255)COLLATE Latin1_General_CI_AS NULL ,
	[Malignant_Primary] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Malignant_Secondary] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[In_Situ] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
        [Benign] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Uncertain_or_Unknown_Behaviour] [varchar] (15)COLLATE Latin1_General_CI_AS NULL
) ON [Primary]

drop table tmp_NeoplasmFrLast

CREATE TABLE tmp_NeoplasmFrLast (
	[AutoId] [int] NOT NULL ,
	[HeaderId] [int] NULL ,
	[SubHeaderId] [int] NULL ,
	[SubHeaderId1] [int] NULL ,
	[SubHeaderId2] [int] NULL ,
	[SubHeaderId3] [int] NULL ,
	[SubHeaderId4] [int] NULL ,
        [HeaderDesc] [varchar] (255) COLLATE Latin1_General_CI_AS NULL,
	[HeaderSearch] [varchar] (255)COLLATE Latin1_General_CI_AS NULL ,
	[Malignant_Primary] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Malignant_Secondary] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[In_Situ] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
        [Benign] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Uncertain_or_Unknown_Behaviour] [varchar] (15)COLLATE Latin1_General_CI_AS NULL
) ON [Primary]

-- IMPORTANT!!!!!!         For FRENCH I'LL BE USING HEADERSEARCH INSTEAD OF HEADERDESC (Because of accent) 

-- COLUMN Malignant_Primary
INSERT INTO tmp_NeoplasmFr (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Malignant_Primary )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3,SubHeaderId4,  HeaderDesc, HeaderSearch, codelink 
from NU_NeoplasmLastFr  where headersearch like '%Primitives%' 

-- COLUMN Malignant_Secondary
INSERT INTO tmp_NeoplasmFr (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Malignant_Secondary )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, codelink 
from NU_NeoplasmLastFr  where headersearch like '%Secondaires%'

-- COLUMN In situ
INSERT INTO tmp_NeoplasmFr (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, In_Situ )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3,SubHeaderId4,  HeaderDesc, HeaderSearch, codelink 
from NU_NeoplasmLastFr  where headersearch like '%In situ%'

-- COLUMN Benign
INSERT INTO tmp_NeoplasmFr (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Benign )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, codelink 
from NU_NeoplasmLastFr  where headersearch like '%Benignes%'

-- COLUMN Uncertain or unknown behaviour
INSERT INTO tmp_NeoplasmFr (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Uncertain_or_Unknown_Behaviour )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, codelink 
from NU_NeoplasmLastFr  where headersearch like '%evolution imprevisible ou inconnue%'

------------------------------------- LEAVING JUST ONE ROW FOR HEADER IN tmp_NeoplasmFrlast 
-- COLUMN Malignant_Primary
INSERT INTO tmp_NeoplasmFrlast  (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Malignant_Primary )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Malignant_Primary from tmp_NeoplasmFr  where Malignant_Primary is not null 

-- OTHERS COLUMNS 

declare cursor_tmp_NeoplasmFrlast CURSOR FOR
select * from tmp_NeoplasmFrlast  
open cursor_tmp_NeoplasmFrlast

FETCH NEXT FROM cursor_tmp_NeoplasmFrlast 
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @SubHeaderId4, @HeaderDesc, @HeaderSearch, @Malignant_Primary, @Malignant_Secondary, @In_Situ, @Benign, @Uncertain_or_Unknown_Behaviour


-- LEAVING JUST ONE ROW FOR HEADER
WHILE @@FETCH_STATUS = 0
BEGIN
	set @tmplink1 = null
	set @tmplink2 = null
	set @tmplink3 = null
	set @tmplink4 = null

       	select @tmplink1= Malignant_Secondary from tmp_NeoplasmFr 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and subheaderid4 = @subheaderid4
				and Malignant_Secondary is not null
	select @tmplink2= In_Situ from tmp_NeoplasmFr 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and subheaderid4 = @subheaderid4 
				and In_Situ is not null
	select @tmplink3= Benign from tmp_NeoplasmFr 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and subheaderid4 = @subheaderid4 
				and Benign is not null
	select @tmplink4= Uncertain_or_Unknown_Behaviour from tmp_NeoplasmFr 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3  and subheaderid4 = @subheaderid4
				and Uncertain_or_Unknown_Behaviour is not null


	UPDATE tmp_NeoplasmFrLast
		SET Malignant_Secondary = @tmplink1,
		In_Situ = @tmplink2,
		Benign = @tmplink3,
		Uncertain_or_Unknown_Behaviour = @tmplink4
		WHERE   headerid     = @headerid and 
			subheaderid  = @subheaderid and
			subheaderid1 = @Subheaderid1 and
			subheaderid2 = @Subheaderid2 and
			subheaderid3 = @Subheaderid3 and
			subheaderid4 = @subheaderid4
	
FETCH NEXT FROM cursor_tmp_NeoplasmFrlast
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @SubHeaderId4, @HeaderDesc, @HeaderSearch, @Malignant_Primary, @Malignant_Secondary, @In_Situ, @Benign, @Uncertain_or_Unknown_Behaviour

END

CLOSE      cursor_tmp_NeoplasmFrlast
DEALLOCATE cursor_tmp_NeoplasmFrlast




-- Remove words "Malignes Primitives codelinks" at the end --


UPDATE tmp_NeoplasmFrlast
		SET headerdesc = rtrim(substring(Headerdesc,1,CHARINDEX('Malignes Primitives', headerdesc, 1)-1 )),
		    headersearch = rtrim(substring(headerSearch,1,CHARINDEX('Malignes Primitives', headerSearch, 1)-1 ))		WHERE  headerdesc like '%Malignes Primitives%' 


-- Do not execute this part.  It's not necesary after latest Simon parse 
-- CODELINK = ''  leave at the end
--INSERT INTO tmp_NeoplasmFrLAST (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4,
--HeaderDesc, HeaderSearch)
--select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch 
--from NU_NeoplasmLastFr  where codelink = ''


UPDATE tmp_NeoplasmFrlast SET  Malignant_Primary = null  WHERE Malignant_Primary = ''  


-- Replace character "|" for "-" resolve problem in VB
UPDATE tmp_neoplasmfrlast SET headerdesc=replace(headerdesc,char(150),char(45)) 


-- Drop tables
drop table tmp_NeoplasmFr



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO














CREATE    PROCEDURE [NU_DeleteSecurity]
	@Coder as varchar(50) --Internal coder number
AS	
DELETE  M_NCoder WHERE 	stdalnuser = @Coder














GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create Procedure [NU_DelUserGuideline]
		@GuideID as int,
		@GuideRelID as int
AS
-- Delete User Coding Guideline
delete from NU_UserGuidelines where GuidelineId=@GuideID
delete from NU_UserGuidelineCodeLinkRel where GuidelineId=@GuideID and GuidelineLinkId = @GuideRelID
delete from NU_UserGuidelineLink where GuidelineLinkId = @GuideRelID



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [NU_ExtraValues]
	@NCoderType as int,
	@Code as VarChar(50),
	@UseDate as datetime
AS 
	DECLARE @ID AS INT
	IF @NCoderType = 1 
	BEGIN
		SELECT  [Code] AS [ ], 
			[DisplayCode] AS [Code Value],
			[DefaultDescription] AS [Default Description],
			[UserDescription] AS [Hospital Description],			
			[Code] AS [System Code],	 				
			[CIHIValue] AS [CIHI Value],	 
			Convert(VarChar(10), [ValidFrom], 111) as [Valid From],
			Convert(VarChar(10), [ValidTo], 111) as [Valid To] 
		FROM LU_DiagnosisType 
		WHERE ([ValidFrom] <= @UseDate) AND (@UseDate <= [ValidTo]) 
		ORDER BY [DisplayCode]
        --ED - 01711
--		SELECT  [Code] AS [ ], 
--			[DisplayCode] AS [Code Value],
--			[DefaultDescription] AS [Default Description],
--			[UserDescription] AS [Hospital Description],			
--			[Code] AS [System Code],	 				
--			[CIHIValue] AS [CIHI Value],	 
--			Convert(VarChar(10), [ValidFrom], 111) as [Valid From],
--			Convert(VarChar(10), [ValidTo], 111) as [Valid To] 
--		FROM LU_DiagnosisPrefix 
--		WHERE ([ValidFrom] <= @UseDate) AND (@UseDate <= [ValidTo]) 
--		ORDER BY [DisplayCode]
	END
	ELSE IF @NCoderType = 2
	BEGIN
		SELECT @ID = Code FROM ICD_ProcFile10 WHERE DisplayCode = @Code
		
		SELECT  [Code] AS [ ], 
			[DisplayCode] AS [Code Value],
			[DefaultDescription] AS [Default Description],
			[UserDescription] AS [Hospital Description],	
			[Code] AS [System Code],	 				
			[CIHIValue] AS [CIHI Value],	 
			Convert(VarChar(10), [ValidFrom], 111) as [Valid From],
			Convert(VarChar(10), [ValidTo], 111) as [Valid To] 
		FROM LU_IntervAttStatus 
		WHERE ([ValidFrom] <= @UseDate) AND (@UseDate <= [ValidTo]) AND [AssociationID] = @ID
		ORDER BY [DisplayCode]
		SELECT  [Code] AS [ ], 
			[DisplayCode] AS [Code Value],
			[DefaultDescription] AS [Default Description],
			[UserDescription] AS [Hospital Description],	
			[Code] AS [System Code],	 				
			[CIHIValue] AS [CIHI Value],	 
			Convert(VarChar(10), [ValidFrom], 111) as [Valid From],
			Convert(VarChar(10), [ValidTo], 111) as [Valid To] 
		FROM LU_IntervAttLocation 
		WHERE ([ValidFrom] <= @UseDate) AND (@UseDate <= [ValidTo]) AND [AssociationID] = @ID
		ORDER BY [DisplayCode]
		SELECT  [Code] AS [ ], 
			[DisplayCode] AS [Code Value],
			[DefaultDescription] AS [Default Description],
			[UserDescription] AS [Hospital Description],	
			[Code] AS [System Code],	 				
			[CIHIValue] AS [CIHI Value],	 
			Convert(VarChar(10), [ValidFrom], 111) as [Valid From],
			Convert(VarChar(10), [ValidTo], 111) as [Valid To] 
		FROM LU_IntervAttExtent 
		WHERE ([ValidFrom] <= @UseDate) AND (@UseDate <= [ValidTo]) AND [AssociationID] = @ID
		ORDER BY [DisplayCode]
	END
















GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [NU_ExtraValuesFr]
	@NCoderType as int,
	@Code as VarChar(50),
	@UseDate as datetime
AS 
	DECLARE @ID AS INT
	IF @NCoderType = 1 
	BEGIN
		SELECT  [Code] AS [ ], 
			[DisplayCode] AS   [Code Valeur],
			[DefaultDescription] AS [Default Description],
			[UserDescription] AS [Description],			
			[Code] AS [System Code],	 				
			[CIHIValue] AS [CIHI Value],	 
			Convert(VarChar(10), [ValidFrom], 111) as [Valid From],
			Convert(VarChar(10), [ValidTo], 111) as [Valid To] 
		FROM LU_DiagnosisTypeFr 
		WHERE ([ValidFrom] <= @UseDate) AND (@UseDate <= [ValidTo]) 
		ORDER BY [DisplayCode]
        --ED - 01711
--		SELECT  [Code] AS [ ], 
--			[DisplayCode] AS [Code Value],
--			[DefaultDescription] AS [Default Description],
--			[UserDescription] AS [Hospital Description],			
--			[Code] AS [System Code],	 				
--			[CIHIValue] AS [CIHI Value],	 
--			Convert(VarChar(10), [ValidFrom], 111) as [Valid From],
--			Convert(VarChar(10), [ValidTo], 111) as [Valid To] 
--		FROM LU_DiagnosisPrefix 
--		WHERE ([ValidFrom] <= @UseDate) AND (@UseDate <= [ValidTo]) 
--		ORDER BY [DisplayCode]
	END
	ELSE IF @NCoderType = 2
	BEGIN

SELECT DISTINCT  0, dbo.CCI_Status_Fra.CIHIVALUE as [ICIS Valeur]  , dbo.CCI_Status_Fra.Description,
				 dbo.CCI_Status_Fra.Description,0, dbo.CCI_Status_Fra.CIHIVALUE  as [ICIS Valeur] , 
				 dbo.CCI_Status_Fra.CIHIVALUE  as [ICIS Valeur] ,'2003-01-01','2008-01-01' 
		FROM   dbo.CCI_Status_Fra INNER JOIN
		 dbo.CCI_Status_Val_Fra ON dbo.CCI_Status_Fra.LinkId = dbo.CCI_Status_Val_Fra.LinkId
		WHERE   CCI_Status_Val_Fra.DISPLAYCODE = replace(replace(@Code,'.',''),'-','')

-- 		SELECT @ID = Code FROM ICD_ProcFile10 WHERE DisplayCode = @Code
		
-- 		SELECT  [Code] AS [ ], 
-- 			[DisplayCode] AS  [Code Valeur],
-- 			[DefaultDescription] AS [Default Description],
-- 			[UserDescription] AS [Description],	
-- 			[Code] AS [System Code],	 				
-- 			[CIHIValue] AS [CIHI Value],	 
-- 			Convert(VarChar(10), [ValidFrom], 111) as [Valid From],
-- 			Convert(VarChar(10), [ValidTo], 111) as [Valid To] 
-- 		FROM LU_IntervAttStatusFr 
-- 		WHERE ([ValidFrom] <= @UseDate) AND (@UseDate <= [ValidTo]) AND [AssociationID] = @ID
-- 		ORDER BY [DisplayCode]


SELECT DISTINCT  0, dbo.CCI_Location_Fra.CIHIVALUE as [ICIS Valeur]  , dbo.CCI_Location_Fra.Description,
				 dbo.CCI_Location_Fra.Description,0, dbo.CCI_Location_Fra.CIHIVALUE  as [ICIS Valeur] , 
				 dbo.CCI_Location_Fra.CIHIVALUE as [ICIS Valeur] ,'2003-01-01','2008-01-01' 
		FROM   dbo.CCI_Location_Fra INNER JOIN
		 dbo.CCI_Location_Val_Fra ON dbo.CCI_Location_Fra.LinkId = dbo.CCI_Location_Val_Fra.LinkId
		WHERE   CCI_Location_Val_Fra.DISPLAYCODE = replace(replace(@Code,'.',''),'-','')

-- 		SELECT  [Code] AS [ ], 

-- 			[DisplayCode] AS [Code Valeur],
-- 			[DefaultDescription] AS [Default Description],
-- 			[UserDescription] AS [Description],	
-- 			[Code] AS [System Code],	 				
-- 			[CIHIValue] AS [CIHI Value],	 
-- 			Convert(VarChar(10), [ValidFrom], 111) as [Valid From],
-- 			Convert(VarChar(10), [ValidTo], 111) as [Valid To] 
-- 		FROM LU_IntervAttLocationFr 
-- 		WHERE ([ValidFrom] <= @UseDate) AND (@UseDate <= [ValidTo]) AND [AssociationID] = @ID
-- 		ORDER BY [DisplayCode]



		SELECT DISTINCT  0, dbo.CCI_Extent_Fra.CIHIVALUE as [ICIS Valeur] , dbo.CCI_Extent_Fra.Description,
				 dbo.CCI_Extent_Fra.Description,0, dbo.CCI_Extent_Fra.CIHIVALUE  as [ICIS Valeur] , 
				 dbo.CCI_Extent_Fra.CIHIVALUE  as [ICIS Valeur] ,'2003-01-01','2008-01-01' 
		FROM   dbo.CCI_Extent_Fra INNER JOIN
		 dbo.CCI_Extent_Val_Fra ON dbo.CCI_Extent_Fra.LinkId = dbo.CCI_Extent_Val_Fra.LinkId
		WHERE   CCI_Extent_Val_Fra.DISPLAYCODE = replace(replace(@Code,'.',''),'-','')

-- 		SELECT  [Code] AS [ ], 
-- 			[DisplayCode]AS [Code Valeur],
-- 			[DefaultDescription] AS [Default Description],
-- 			[UserDescription] AS [Description],	
-- 			[Code] AS [System Code],	 				
-- 			[CIHIValue] AS [CIHI Value],	 
-- 			Convert(VarChar(10), [ValidFrom], 111) as [Valid From],
-- 			Convert(VarChar(10), [ValidTo], 111) as [Valid To] 
-- 		FROM LU_IntervAttExtentFr 
-- 		WHERE ([ValidFrom] <= @UseDate) AND (@UseDate <= [ValidTo]) AND [AssociationID] = @ID
-- 		ORDER BY [DisplayCode]
	END
	



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO









Create      Procedure [NU_GetDProfile]
@ProfileID as int,
@LangID as int
AS


if @LangID=0
Begin

--Select userdescription,displaycode,cihivalue from icd_diagfile10Fr 

-- Select CodeNum
-- ,(select top 1 CodeDesc  from Nu_Codes as D where D.Codenum = codenum  COLLATE Latin1_General_CI_AS or D.cihivalue=NU_DProfile.cihivalue COLLATE Latin1_General_CI_AS) as U_Desc
-- ,Type,Typecode,TypeCIHI,AST
-- from NU_DProfile where ProfileID=@ProfileID
SELECT dbo.NU_Codes.Codenum, dbo.NU_Codes.CodeDesc as U_Desc ,NU_DProfile.Type,NU_DProfile.Typecode,NU_DProfile.TypeCIHI,NU_DProfile.AST
FROM    dbo.NU_DProfile INNER JOIN
dbo.NU_Codes ON dbo.NU_DProfile.CIHIVALUE = dbo.NU_Codes.CIHIVALUE
where ProfileID=@ProfileID
order by NU_DProfile.autoid

End

if @LangID=10000 
Begin

--Select userdescription,displaycode,cihivalue from icd_diagfile10Fr 

SELECT dbo.NU_CodesFr.Codenum, dbo.NU_CodesFr.CodeDesc as U_Desc ,NU_DProfile.Type,NU_DProfile.Typecode,NU_DProfile.TypeCIHI,NU_DProfile.AST
FROM    dbo.NU_DProfile INNER JOIN
dbo.NU_CodesFr ON dbo.NU_DProfile.CIHIVALUE = dbo.NU_CodesFr.CIHIVALUE
where ProfileID=@ProfileID
order by NU_DProfile.autoid
-- Select CodeNum
-- ,(select top 1 CodeDesc from Nu_CodesFR as D where D.Codenum = codenum COLLATE Latin1_General_CI_AS or D.cihivalue=NU_DProfile.cihivalue COLLATE Latin1_General_CI_AS) as U_Desc
-- ,Type,Typecode,TypeCIHI,AST
-- from NU_DProfile where ProfileID=@ProfileID
 
End




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO















CREATE            PROCEDURE [NU_GetExclude] 
		@ChapterId as int,
		@HeaderId as int,
		@SubHeaderid as int,
		@CodeId as int,
		@CodeHeader as int ,
		@SubCodeHeader as int,
		@SwitchStmt as int,
		@OptionalStmt as varchar (10)
		 
AS


IF @OptionalStmt = '0' BEGIN	
	if @SwitchStmt = 1
	begin 
	SELECT  IncludeDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader ,CodeHeader, CodeLink1,CodeLink2
	      From dbo.NU_Include  
	       WHERE 	ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY INCLUDEID
	 SELECT  ExcludeDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader , CodeLink1,CodeLink2
	      From dbo.NU_Exclude  
	     WHERE 	ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY EXCLUDEID
	 SELECT   DISTINCT DAG.OptStmtsDesc   ,  DAG.SubHeaderId, 
	         DAG.HeaderId,  DAG.ChapterId, dbo.NU_Codes.Asteriks, 
	         DAG.DaggerId,DAG.CodeId,DAG.CodeLink1,  DAG.CodeLink2 
	        From dbo.NU_Dagger as DAG INNER JOIN dbo.NU_Codes ON  DAG.CodeId = dbo.NU_Codes.Codeid
	             WHERE   DAG.ChapterID = @ChapterID 
		and DAG.HeaderID in (0, @HeaderID)
		and DAG.SubHeaderID in (0, @SubHeaderID)
		and DAG.CodeHeader in (0, @CodeHeader) 
		and DAG.SubCodeHeader in (0, @SubCodeHeader)
		and DAG.CodeId in (0, @CodeId)
		AND dbo.NU_Codes.Asteriks = 1
		  ORDER BY DAGGERID
	  SELECT  DISTINCT   OptStmtsDesc   , DAGG.SubHeaderId, 
	        DAGG.HeaderId, DAGG.ChapterId, dbo.NU_Codes.Asteriks, 
	        dbo.NU_Codes.Dagger, DAGG.CodeId    , DAGG.CodeLink1, DAGG.CodeLink2,DaggerID
	        From NU_Dagger as DAGG INNER JOIN dbo.NU_Codes ON DAGG.Codeid = dbo.NU_Codes.CodeId
		WHERE 
		DAGG.ChapterID = @ChapterID 
		and DAGG.HeaderID in (0, @HeaderID)
		and DAGG.SubHeaderID in (0, @SubHeaderID)
		and DAGG.CodeHeader in (0, @CodeHeader)
		and DAGG.SubCodeHeader in (0, @SubCodeHeader)
		and DAGG.CodeID in (0, @CodeID) AND    dbo.NU_Codes.Dagger = 1  ORDER BY DaggerId
	SELECT    NoteDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader ,NoteId ,CodeLink1
	      From   NU_Notes
	         WHERE 	ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		--and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY NOTEID
	end
	if   @SwitchStmt = 2
	begin
	SELECT --DISTINCT 
	                       IncludeDesc,  CodeId,  ChapterId,  HeaderId, 
	                       SubHeaderId,  CodeHeader,  SubCodeHeader,  CodeLink1, 
	                       CodeLink2  --, dbo.ICD_ProcFile10.Code
	FROM         dbo.NU_IntInclude
	WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID)  ORDER BY IncludeID
	SELECT --DISTINCT 
	                      dbo.NU_IntExclude.ExcludeDesc, dbo.NU_IntExclude.CodeId, dbo.NU_IntExclude.ChapterId, dbo.NU_IntExclude.HeaderId, 
	                      dbo.NU_IntExclude.SubHeaderId, dbo.NU_IntExclude.CodeHeader, dbo.NU_IntExclude.SubCodeHeader, dbo.NU_IntExclude.CodeLink1, 
	                      dbo.NU_IntExclude.CodeLink2--, dbo.ICD_ProcFile10.Code
	FROM         dbo.NU_IntExclude
	WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID)  ORDER BY ExcludeID
	  SELECT   DISTINCT   DAGG.OmitDesc  ,  DAGG.SubHeaderId, 
	         DAGG.HeaderId,  DAGG.ChapterId,  
	         DAGG.Omitid,  DAGG.CodeId    ,  DAGG.CodeLink1,  DAGG.CodeLink2
	        From dbo.NU_IntOmitCode AS DAGG INNER JOIN dbo.NU_IntCodes ON  DAGG.CodeId = dbo.NU_IntCodes.Codeid
	             WHERE    DAGG.ChapterID = @ChapterID 
		and DAGG.HeaderID in (0, @HeaderID)
		and DAGG.SubHeaderID in (0, @SubHeaderID)
		and DAGG.CodeHeader in (0, @CodeHeader)
		and DAGG.SubCodeHeader in (0, @SubCodeHeader)
		and DAGG.CodeId in (0, @CodeId)
		ORDER BY OmitID
	SELECT DISTINCT 
	                       dbo.NU_IntCodeAlso.AlsoDesc   , dbo.NU_IntCodeAlso.CodeId, dbo.NU_IntCodeAlso.ChapterId, dbo.NU_IntCodeAlso.HeaderId, 
	                      dbo.NU_IntCodeAlso.SubHeaderId, dbo.NU_IntCodeAlso.CodeHeader, dbo.NU_IntCodeAlso.SubCodeHeader, dbo.NU_IntCodeAlso.CodeLink1, 
	                      dbo.NU_IntCodeAlso.CodeLink2 ,AlsoID --, dbo.ICD_ProcFile10.Code
	FROM         dbo.NU_IntCodeAlso
	     WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY AlsoID
	SELECT   
	                      dbo.NU_IntNotes.NoteDesc, dbo.NU_IntNotes.CodeId, dbo.NU_IntNotes.ChapterId, dbo.NU_IntNotes.HeaderId, 
	                      dbo.NU_IntNotes.SubHeaderId, dbo.NU_IntNotes.CodeHeader, dbo.NU_IntNotes.SubCodeHeader ,dbo.NU_IntNotes.NoteId  ,CodeLink1
	               
	FROM         dbo.NU_IntNotes
	      WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY NOTEID
	 
	end
END

IF @OptionalStmt = '10000' BEGIN
	if @SwitchStmt = 1
	begin 
-- 	CLSELECT  IncludeDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader ,CodeHeader, CodeLink1,CodeLink2
-- 	      From dbo.NU_IncludeFr  
-- 	       WHERE 	ChapterID = @ChapterID 
-- 		and HeaderID in (0, @HeaderID)
-- 		and SubHeaderID in (0, @SubHeaderID)
-- 		and CodeHeader in (0, @CodeHeader)
-- 		and SubCodeHeader in (0, @SubCodeHeader)
-- 		and CodeID in (0, @CodeID) ORDER BY INUDEID
	 
	SELECT  ExcludeDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader , CodeLink1,CodeLink2
	      From dbo.NU_ExcludeFr  
	     WHERE 	ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY EXCLUDEID
	 
-- 	SELECT   DISTINCT DAG.OptStmtsDesc   ,  DAG.SubHeaderId, 
-- 	         DAG.HeaderId,  DAG.ChapterId, dbo.NU_CodesFr.Asteriks, 
-- 	         DAG.DaggerId,DAG.CodeId,DAG.CodeLink1,  DAG.CodeLink2 
-- 	        From dbo.NU_DaggerFr as DAG INNER JOIN dbo.NU_CodesFr ON  DAG.CodeId = dbo.NU_CodesFr.Codeid
-- 	             WHERE   DAG.ChapterID = @ChapterID 
-- 		and DAG.HeaderID in (0, @HeaderID)
-- 		and DAG.SubHeaderID in (0, @SubHeaderID)
-- 		and DAG.CodeHeader in (0, @CodeHeader) 
-- 		and DAG.SubCodeHeader in (0, @SubCodeHeader)
-- 		and DAG.CodeId in (0, @CodeId)
-- 		AND dbo.NU_CodesFr.Asteriks = 1
-- 		  ORDER BY DAGGERID
-- 	  SELECT  DISTINCT   OptStmtsDesc   , DAGG.SubHeaderId, 
-- 	        DAGG.HeaderId, DAGG.ChapterId, dbo.NU_CodesFr.Asteriks, 
-- 	        dbo.NU_CodesFr.Dagger, DAGG.CodeId    , DAGG.CodeLink1, DAGG.CodeLink2,DaggerID
-- 	        From NU_DaggerFr as DAGG INNER JOIN dbo.NU_CodesFr ON DAGG.Codeid = dbo.NU_CodesFr.CodeId
-- 		WHERE 
-- 		DAGG.ChapterID = @ChapterID 
-- 		and DAGG.HeaderID in (0, @HeaderID)
-- 		and DAGG.SubHeaderID in (0, @SubHeaderID)
-- 		and DAGG.CodeHeader in (0, @CodeHeader)
-- 		and DAGG.SubCodeHeader in (0, @SubCodeHeader)
-- 		and DAGG.CodeID in (0, @CodeID) AND    dbo.NU_CodesFr.Dagger = 1  ORDER BY DaggerId
-- 	SELECT    NoteDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader ,NoteId ,CodeLink1
-- 	      From   NU_NotesFr
-- 	         WHERE 	ChapterID = @ChapterID 
-- 		and HeaderID in (0, @HeaderID)
-- 		and SubHeaderID in (0, @SubHeaderID)
-- 		and CodeHeader in (0, @CodeHeader)
-- 
-- 		and SubCodeHeader in (0, @SubCodeHeader)
-- 		and CodeID in (0, @CodeID) ORDER BY NOTEID
	end
	if   @SwitchStmt = 2
	begin
-- 	SELECT --DISTINCT 
-- 	                       IncludeDesc,  CodeId,  ChapterId,  HeaderId, 
-- 	                       SubHeaderId,  CodeHeader,  SubCodeHeader,  CodeLink1, 
-- 	                       CodeLink2  --, dbo.ICD_ProcFile10.Code
-- 	FROM         dbo.NU_IntIncludeFr
-- 	WHERE  ChapterID = @ChapterID 
-- 		and HeaderID in (0, @HeaderID)
-- 		and SubHeaderID in (0, @SubHeaderID)
-- 		and CodeHeader in (0, @CodeHeader)
-- 		and SubCodeHeader in (0, @SubCodeHeader)
-- 		and CodeID in (0, @CodeID)  ORDER BY IncludeID
	SELECT --DISTINCT 
	                      dbo.NU_IntExcludeFr.ExcludeDesc, dbo.NU_IntExcludeFr.CodeId, dbo.NU_IntExcludeFr.ChapterId, dbo.NU_IntExcludeFr.HeaderId, 
	                      dbo.NU_IntExcludeFr.SubHeaderId, dbo.NU_IntExcludeFr.CodeHeader, dbo.NU_IntExcludeFr.SubCodeHeader, dbo.NU_IntExcludeFr.CodeLink1, 
	                      dbo.NU_IntExcludeFr.CodeLink2--, dbo.ICD_ProcFile10.Code
	FROM         dbo.NU_IntExcludeFr
	WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID)  ORDER BY ExcludeID
-- 	  SELECT   DISTINCT   DAGG.OmitDesc  ,  DAGG.SubHeaderId, 
-- 	         DAGG.HeaderId,  DAGG.ChapterId,  
-- 	         DAGG.Omitid,  DAGG.CodeId    ,  DAGG.CodeLink1,  DAGG.CodeLink2
-- 	        From dbo.NU_IntOmitCodeFr AS DAGG INNER JOIN dbo.NU_IntCodesFr ON  DAGG.CodeId = dbo.NU_IntCodesFr.Codeid
-- 	             WHERE    DAGG.ChapterID = @ChapterID 
-- 		and DAGG.HeaderID in (0, @HeaderID)
-- 		and DAGG.SubHeaderID in (0, @SubHeaderID)
-- 		and DAGG.CodeHeader in (0, @CodeHeader)
-- 		and DAGG.SubCodeHeader in (0, @SubCodeHeader)
-- 		and DAGG.CodeId in (0, @CodeId)
-- 		ORDER BY OmitID
-- 	SELECT DISTINCT 
-- 	                       dbo.NU_IntCodeAlsoFr.AlsoDesc   , dbo.NU_IntCodeAlsoFr.CodeId, dbo.NU_IntCodeAlsoFr.ChapterId, dbo.NU_IntCodeAlsoFr.HeaderId, 
-- 	                      dbo.NU_IntCodeAlsoFr.SubHeaderId, dbo.NU_IntCodeAlsoFr.CodeHeader, dbo.NU_IntCodeAlsoFr.SubCodeHeader, dbo.NU_IntCodeAlsoFr.CodeLink1, 
-- 	                      dbo.NU_IntCodeAlsoFr.CodeLink2 ,AlsoID --, dbo.ICD_ProcFile10.Code
-- 	FROM         dbo.NU_IntCodeAlsoFr
-- 	     WHERE  ChapterID = @ChapterID 
-- 		and HeaderID in (0, @HeaderID)
-- 		and SubHeaderID in (0, @SubHeaderID)
-- 		and CodeHeader in (0, @CodeHeader)
-- 		and SubCodeHeader in (0, @SubCodeHeader)
-- 		and CodeID in (0, @CodeID) ORDER BY AlsoID
-- 	SELECT   
-- 	                      dbo.NU_IntNotesFr.NoteDesc, dbo.NU_IntNotesFr.CodeId, dbo.NU_IntNotesFr.ChapterId, dbo.NU_IntNotesFr.HeaderId, 
-- 	                      dbo.NU_IntNotesFr.SubHeaderId, dbo.NU_IntNotesFr.CodeHeader, dbo.NU_IntNotesFr.SubCodeHeader ,dbo.NU_IntNotesFr.NoteId  ,CodeLink1
-- 	               
-- 	FROM         dbo.NU_IntNotesFr
-- 	      WHERE  ChapterID = @ChapterID 
-- 		and HeaderID in (0, @HeaderID)
-- 		and SubHeaderID in (0, @SubHeaderID)
-- 		and CodeHeader in (0, @CodeHeader)
-- 		and SubCodeHeader in (0, @SubCodeHeader)
-- 		and CodeID in (0, @CodeID) ORDER BY NOTEID
-- 	 
	end

END















GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
















CREATE               PROCEDURE [NU_GetExcludes] 
		@ChapterId as int,
		@HeaderId as int,
		@SubHeaderid as int,
		@CodeId as int,
		@CodeHeader as int ,
		@SubCodeHeader as int,
		@SwitchStmt as int,
		@OptionalStmt as varchar (10)
		 
AS


IF @OptionalStmt = '0' BEGIN	
	if @SwitchStmt = 1
	begin 
	SELECT  IncludeDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader ,CodeHeader, CodeLink1,CodeLink2
	      From dbo.NU_Include  
	       WHERE 	ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY INCLUDEID
	 SELECT  ExcludeDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader , CodeLink1,CodeLink2
	      From dbo.NU_Exclude  
	     WHERE 	ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY EXCLUDEID
	 SELECT   DISTINCT DAG.OptStmtsDesc   ,  DAG.SubHeaderId, 
	         DAG.HeaderId,  DAG.ChapterId, dbo.NU_Codes.Asteriks, 
	         DAG.DaggerId,DAG.CodeId,DAG.CodeLink1,  DAG.CodeLink2 
	        From dbo.NU_Dagger as DAG INNER JOIN dbo.NU_Codes ON  DAG.CodeId = dbo.NU_Codes.Codeid
		-- ED-01662 ADDED 20080710 commented for WiNrecs release
		AND dbo.NU_Codes.CodeHeader = DAG.CodeHeader 
		AND dbo.NU_Codes.ChapterId = DAG.ChapterId 
		AND dbo.NU_Codes.HeaderId = DAG.HeaderId 
		AND dbo.NU_Codes.SubHeaderId = DAG.SubHeaderId
		AND dbo.NU_Codes.SubCodeHeader = DAG.SubCodeHeader 
		-- END ED-01662	
	             WHERE   DAG.ChapterID = @ChapterID 
		and DAG.HeaderID in (0, @HeaderID)
		and DAG.SubHeaderID in (0, @SubHeaderID)
		and DAG.CodeHeader in (0, @CodeHeader) 
		and DAG.SubCodeHeader in (0, @SubCodeHeader)
		and DAG.CodeId in (0, @CodeId)
		AND dbo.NU_Codes.Asteriks = 1
		  ORDER BY DAGGERID
	  SELECT  DISTINCT   OptStmtsDesc   , DAGG.SubHeaderId, 
	        DAGG.HeaderId, DAGG.ChapterId, dbo.NU_Codes.Asteriks, 
	        dbo.NU_Codes.Dagger, DAGG.CodeId    , DAGG.CodeLink1, DAGG.CodeLink2,DaggerID
	        From NU_Dagger as DAGG INNER JOIN dbo.NU_Codes ON DAGG.Codeid = dbo.NU_Codes.CodeId
		-- ED-01662 ADDED 20080710 commented for WiNrecs release
		AND dbo.NU_Codes.CodeHeader = DAGG.CodeHeader 
		AND dbo.NU_Codes.ChapterId = DAGG.ChapterId 
		AND dbo.NU_Codes.HeaderId = DAGG.HeaderId 
		AND dbo.NU_Codes.SubHeaderId = DAGG.SubHeaderId
		AND dbo.NU_Codes.SubCodeHeader = DAGG.SubCodeHeader
		-- END ED-01662	
		WHERE 
		DAGG.ChapterID = @ChapterID 
		and DAGG.HeaderID in (0, @HeaderID)
		and DAGG.SubHeaderID in (0, @SubHeaderID)
		and DAGG.CodeHeader in (0, @CodeHeader)
		and DAGG.SubCodeHeader in (0, @SubCodeHeader)
		and DAGG.CodeID in (0, @CodeID) AND    dbo.NU_Codes.Dagger = 1  ORDER BY DaggerId
	SELECT    NoteDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader ,NoteId ,CodeLink1
	      From   NU_Notes
	         WHERE 	ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		--and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY NOTEID
	end
	if   @SwitchStmt = 2
	begin
	SELECT --DISTINCT 
	                       IncludeDesc,  CodeId,  ChapterId,  HeaderId, 
	                       SubHeaderId,  CodeHeader,  SubCodeHeader,  CodeLink1, 
	                       CodeLink2  --, dbo.ICD_ProcFile10.Code
	FROM         dbo.NU_IntInclude
	WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID)  ORDER BY IncludeID
	SELECT --DISTINCT 
	                      dbo.NU_IntExclude.ExcludeDesc, dbo.NU_IntExclude.CodeId, dbo.NU_IntExclude.ChapterId, dbo.NU_IntExclude.HeaderId, 
	                      dbo.NU_IntExclude.SubHeaderId, dbo.NU_IntExclude.CodeHeader, dbo.NU_IntExclude.SubCodeHeader, dbo.NU_IntExclude.CodeLink1, 
	                      dbo.NU_IntExclude.CodeLink2--, dbo.ICD_ProcFile10.Code
	FROM         dbo.NU_IntExclude
	WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID)  ORDER BY ExcludeID
	  SELECT   DISTINCT   DAGG.OmitDesc  ,  DAGG.SubHeaderId, 
	         DAGG.HeaderId,  DAGG.ChapterId,  
	         DAGG.Omitid,  DAGG.CodeId    ,  DAGG.CodeLink1,  DAGG.CodeLink2
	        From dbo.NU_IntOmitCode AS DAGG INNER JOIN dbo.NU_IntCodes ON  DAGG.CodeId = dbo.NU_IntCodes.Codeid
	             WHERE    DAGG.ChapterID = @ChapterID 
		and DAGG.HeaderID in (0, @HeaderID)
		and DAGG.SubHeaderID in (0, @SubHeaderID)
		and DAGG.CodeHeader in (0, @CodeHeader)
		and DAGG.SubCodeHeader in (0, @SubCodeHeader)
		and DAGG.CodeId in (0, @CodeId)
		ORDER BY OmitID
	SELECT DISTINCT 
	                       dbo.NU_IntCodeAlso.AlsoDesc   , dbo.NU_IntCodeAlso.CodeId, dbo.NU_IntCodeAlso.ChapterId, dbo.NU_IntCodeAlso.HeaderId, 
	                      dbo.NU_IntCodeAlso.SubHeaderId, dbo.NU_IntCodeAlso.CodeHeader, dbo.NU_IntCodeAlso.SubCodeHeader, dbo.NU_IntCodeAlso.CodeLink1, 
	                      dbo.NU_IntCodeAlso.CodeLink2 ,AlsoID --, dbo.ICD_ProcFile10.Code
	FROM         dbo.NU_IntCodeAlso
	     WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY AlsoID
	SELECT   
	                      dbo.NU_IntNotes.NoteDesc, dbo.NU_IntNotes.CodeId, dbo.NU_IntNotes.ChapterId, dbo.NU_IntNotes.HeaderId, 
	                      dbo.NU_IntNotes.SubHeaderId, dbo.NU_IntNotes.CodeHeader, dbo.NU_IntNotes.SubCodeHeader ,dbo.NU_IntNotes.NoteId  ,CodeLink1
	               
	FROM         dbo.NU_IntNotes
	      WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY NOTEID
	 
	end
END

IF @OptionalStmt = '10000' BEGIN
	if @SwitchStmt = 1
	begin 
	SELECT  IncludeDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader ,CodeHeader, CodeLink1,CodeLink2
	      From dbo.NU_IncludeFr  
	       WHERE 	ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY INCLUDEID
	 
	SELECT  ExcludeDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader , CodeLink1,CodeLink2
	      From dbo.NU_ExcludeFr  
	     WHERE 	ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY EXCLUDEID
	 
	SELECT   DISTINCT DAG.OptStmtsDesc   ,  DAG.SubHeaderId, 
	         DAG.HeaderId,  DAG.ChapterId, dbo.NU_CodesFr.Asteriks, 
	         DAG.DaggerId,DAG.CodeId,DAG.CodeLink1,  DAG.CodeLink2 
	        From dbo.NU_DaggerFr as DAG INNER JOIN dbo.NU_CodesFr ON  DAG.CodeId = dbo.NU_CodesFr.Codeid
	             WHERE   DAG.ChapterID = @ChapterID 
		and DAG.HeaderID in (0, @HeaderID)
		and DAG.SubHeaderID in (0, @SubHeaderID)
		and DAG.CodeHeader in (0, @CodeHeader) 
		and DAG.SubCodeHeader in (0, @SubCodeHeader)
		and DAG.CodeId in (0, @CodeId)
		AND dbo.NU_CodesFr.Asteriks = 1
		  ORDER BY DAGGERID
	  SELECT  DISTINCT   OptStmtsDesc   , DAGG.SubHeaderId, 
	        DAGG.HeaderId, DAGG.ChapterId, dbo.NU_CodesFr.Asteriks, 
	        dbo.NU_CodesFr.Dagger, DAGG.CodeId    , DAGG.CodeLink1, DAGG.CodeLink2,DaggerID
	        From NU_DaggerFr as DAGG INNER JOIN dbo.NU_CodesFr ON DAGG.Codeid = dbo.NU_CodesFr.CodeId
		WHERE 
		DAGG.ChapterID = @ChapterID 
		and DAGG.HeaderID in (0, @HeaderID)
		and DAGG.SubHeaderID in (0, @SubHeaderID)
		and DAGG.CodeHeader in (0, @CodeHeader)
		and DAGG.SubCodeHeader in (0, @SubCodeHeader)
		and DAGG.CodeID in (0, @CodeID) AND    dbo.NU_CodesFr.Dagger = 1  ORDER BY DaggerId
	SELECT    NoteDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader ,NoteId ,CodeLink1
	      From   NU_NotesFr
	         WHERE 	ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)

		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY NOTEID
	end
	if   @SwitchStmt = 2
	begin
	SELECT --DISTINCT 
	                       IncludeDesc,  CodeId,  ChapterId,  HeaderId, 
	                       SubHeaderId,  CodeHeader,  SubCodeHeader,  CodeLink1, 
	                       CodeLink2  --, dbo.ICD_ProcFile10.Code
	FROM         dbo.NU_IntIncludeFr
	WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID)  ORDER BY IncludeID
	SELECT --DISTINCT 
	                      dbo.NU_IntExcludeFr.ExcludeDesc, dbo.NU_IntExcludeFr.CodeId, dbo.NU_IntExcludeFr.ChapterId, dbo.NU_IntExcludeFr.HeaderId, 
	                      dbo.NU_IntExcludeFr.SubHeaderId, dbo.NU_IntExcludeFr.CodeHeader, dbo.NU_IntExcludeFr.SubCodeHeader, dbo.NU_IntExcludeFr.CodeLink1, 
	                      dbo.NU_IntExcludeFr.CodeLink2--, dbo.ICD_ProcFile10.Code
	FROM         dbo.NU_IntExcludeFr
	WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID)  ORDER BY ExcludeID
	  SELECT   DISTINCT   DAGG.OmitDesc  ,  DAGG.SubHeaderId, 
	         DAGG.HeaderId,  DAGG.ChapterId,  
	         DAGG.Omitid,  DAGG.CodeId    ,  DAGG.CodeLink1,  DAGG.CodeLink2
	        From dbo.NU_IntOmitCodeFr AS DAGG INNER JOIN dbo.NU_IntCodesFr ON  DAGG.CodeId = dbo.NU_IntCodesFr.Codeid
	             WHERE    DAGG.ChapterID = @ChapterID 
		and DAGG.HeaderID in (0, @HeaderID)
		and DAGG.SubHeaderID in (0, @SubHeaderID)
		and DAGG.CodeHeader in (0, @CodeHeader)
		and DAGG.SubCodeHeader in (0, @SubCodeHeader)
		and DAGG.CodeId in (0, @CodeId)
		ORDER BY OmitID
	SELECT DISTINCT 
	                       dbo.NU_IntCodeAlsoFr.AlsoDesc   , dbo.NU_IntCodeAlsoFr.CodeId, dbo.NU_IntCodeAlsoFr.ChapterId, dbo.NU_IntCodeAlsoFr.HeaderId, 
	                      dbo.NU_IntCodeAlsoFr.SubHeaderId, dbo.NU_IntCodeAlsoFr.CodeHeader, dbo.NU_IntCodeAlsoFr.SubCodeHeader, dbo.NU_IntCodeAlsoFr.CodeLink1, 
	                      dbo.NU_IntCodeAlsoFr.CodeLink2 ,AlsoID --, dbo.ICD_ProcFile10.Code
	FROM         dbo.NU_IntCodeAlsoFr
	     WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY AlsoID
	SELECT   
	                      dbo.NU_IntNotesFr.NoteDesc, dbo.NU_IntNotesFr.CodeId, dbo.NU_IntNotesFr.ChapterId, dbo.NU_IntNotesFr.HeaderId, 
	                      dbo.NU_IntNotesFr.SubHeaderId, dbo.NU_IntNotesFr.CodeHeader, dbo.NU_IntNotesFr.SubCodeHeader ,dbo.NU_IntNotesFr.NoteId  ,CodeLink1
	               
	FROM         dbo.NU_IntNotesFr
	      WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY NOTEID
	 
	end

END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO







CREATE               PROCEDURE [NU_GetExcludesUP] 
		@ChapterId as int,
		@HeaderId as int,
		@SubHeaderid as int,
		@CodeId as int,
		@CodeHeader as int ,
		@SubCodeHeader as int,
		@SwitchStmt as int,
		@OptionalStmt as varchar (10)
		 
AS


IF @OptionalStmt = '0' BEGIN	
	if @SwitchStmt = 1
	begin 
	SELECT  IncludeDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader ,CodeHeader, CodeLink1,CodeLink2,includeid as TblID
	      From dbo.NU_Include  
	       WHERE 	ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY INCLUDEID
	 SELECT  ExcludeDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader , CodeLink1,CodeLink2,excludeid as TblID
	      From dbo.NU_Exclude  
	     WHERE 	ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY EXCLUDEID
	 SELECT   DISTINCT DAG.OptStmtsDesc   ,  DAG.SubHeaderId, 
	         DAG.HeaderId,  DAG.ChapterId, dbo.NU_Codes.Asteriks, 
	         DAG.DaggerId,DAG.CodeId,DAG.CodeLink1,  DAG.CodeLink2,DAG.DaggerId as TblID
	        From dbo.NU_Dagger as DAG INNER JOIN dbo.NU_Codes ON  DAG.CodeId = dbo.NU_Codes.Codeid
	             WHERE   DAG.ChapterID = @ChapterID 
		and DAG.HeaderID in (0, @HeaderID)
		and DAG.SubHeaderID in (0, @SubHeaderID)
		and DAG.CodeHeader in (0, @CodeHeader) 
		and DAG.SubCodeHeader in (0, @SubCodeHeader)
		and DAG.CodeId in (0, @CodeId)
		AND dbo.NU_Codes.Asteriks = 1
		  ORDER BY DAGGERID
	  SELECT  DISTINCT   OptStmtsDesc   , DAGG.SubHeaderId, 
	        DAGG.HeaderId, DAGG.ChapterId, dbo.NU_Codes.Asteriks, 
	        dbo.NU_Codes.Dagger, DAGG.CodeId    , DAGG.CodeLink1, DAGG.CodeLink2,DaggerID as TblID
	        From NU_Dagger as DAGG INNER JOIN dbo.NU_Codes ON DAGG.Codeid = dbo.NU_Codes.CodeId
		WHERE 
		DAGG.ChapterID = @ChapterID 
		and DAGG.HeaderID in (0, @HeaderID)
		and DAGG.SubHeaderID in (0, @SubHeaderID)
		and DAGG.CodeHeader in (0, @CodeHeader)
		and DAGG.SubCodeHeader in (0, @SubCodeHeader)
		and DAGG.CodeID in (0, @CodeID) AND    dbo.NU_Codes.Dagger = 1  ORDER BY DaggerId
	SELECT    NoteDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader ,NoteId ,CodeLink1,NoteId as TblID
	      From   NU_Notes
	         WHERE 	ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		--and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY NOTEID
	end
	if   @SwitchStmt = 2
	begin
	SELECT --DISTINCT 
	                       IncludeDesc,  CodeId,  ChapterId,  HeaderId, 
	                       SubHeaderId,  CodeHeader,  SubCodeHeader,  CodeLink1, 
	                       CodeLink2 ,includeid as TblID --, dbo.ICD_ProcFile10.Code
	FROM         dbo.NU_IntInclude
	WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID)  ORDER BY IncludeID
	SELECT --DISTINCT 
	                      dbo.NU_IntExclude.ExcludeDesc, dbo.NU_IntExclude.CodeId, dbo.NU_IntExclude.ChapterId, dbo.NU_IntExclude.HeaderId, 
	                      dbo.NU_IntExclude.SubHeaderId, dbo.NU_IntExclude.CodeHeader, dbo.NU_IntExclude.SubCodeHeader, dbo.NU_IntExclude.CodeLink1, 
	                      dbo.NU_IntExclude.CodeLink2 ,excludeid as TblID--, dbo.ICD_ProcFile10.Code
	FROM         dbo.NU_IntExclude
	WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID)  ORDER BY ExcludeID
	  SELECT   DISTINCT   DAGG.OmitDesc  ,  DAGG.SubHeaderId, 
	         DAGG.HeaderId,  DAGG.ChapterId,  
	         DAGG.Omitid,  DAGG.CodeId    ,  DAGG.CodeLink1,  DAGG.CodeLink2,DAGG.Omitid as TblID
	        From dbo.NU_IntOmitCode AS DAGG INNER JOIN dbo.NU_IntCodes ON  DAGG.CodeId = dbo.NU_IntCodes.Codeid
	             WHERE    DAGG.ChapterID = @ChapterID 
		and DAGG.HeaderID in (0, @HeaderID)
		and DAGG.SubHeaderID in (0, @SubHeaderID)
		and DAGG.CodeHeader in (0, @CodeHeader)
		and DAGG.SubCodeHeader in (0, @SubCodeHeader)
		and DAGG.CodeId in (0, @CodeId)
		ORDER BY OmitID
	SELECT DISTINCT 
	                       dbo.NU_IntCodeAlso.AlsoDesc   , dbo.NU_IntCodeAlso.CodeId, dbo.NU_IntCodeAlso.ChapterId, dbo.NU_IntCodeAlso.HeaderId, 
	                      dbo.NU_IntCodeAlso.SubHeaderId, dbo.NU_IntCodeAlso.CodeHeader, dbo.NU_IntCodeAlso.SubCodeHeader, dbo.NU_IntCodeAlso.CodeLink1, 
	                      dbo.NU_IntCodeAlso.CodeLink2 ,AlsoID as TblID --, dbo.ICD_ProcFile10.Code
	FROM         dbo.NU_IntCodeAlso
	     WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY AlsoID
	SELECT   
	                      dbo.NU_IntNotes.NoteDesc, dbo.NU_IntNotes.CodeId, dbo.NU_IntNotes.ChapterId, dbo.NU_IntNotes.HeaderId, 
	                      dbo.NU_IntNotes.SubHeaderId, dbo.NU_IntNotes.CodeHeader, dbo.NU_IntNotes.SubCodeHeader ,dbo.NU_IntNotes.NoteId as TblID ,CodeLink1
	               
	FROM         dbo.NU_IntNotes
	      WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY NOTEID
	 
	end
END

IF @OptionalStmt = '10000' BEGIN
	if @SwitchStmt = 1
	begin 
	SELECT  IncludeDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader ,CodeHeader, CodeLink1,CodeLink2,includeid as TblID
	      From dbo.NU_IncludeFr  
	       WHERE 	ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY INCLUDEID
	 
	SELECT  ExcludeDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader , CodeLink1,CodeLink2,excludeid as TblID
	      From dbo.NU_ExcludeFr  
	     WHERE 	ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY EXCLUDEID
	 
	SELECT   DISTINCT DAG.OptStmtsDesc   ,  DAG.SubHeaderId, 
	         DAG.HeaderId,  DAG.ChapterId, dbo.NU_CodesFr.Asteriks, 
	         DAG.DaggerId,DAG.CodeId,DAG.CodeLink1,  DAG.CodeLink2 ,Daggerid as TblID
	        From dbo.NU_DaggerFr as DAG INNER JOIN dbo.NU_CodesFr ON  DAG.CodeId = dbo.NU_CodesFr.Codeid
	             WHERE   DAG.ChapterID = @ChapterID 
		and DAG.HeaderID in (0, @HeaderID)
		and DAG.SubHeaderID in (0, @SubHeaderID)
		and DAG.CodeHeader in (0, @CodeHeader) 
		and DAG.SubCodeHeader in (0, @SubCodeHeader)
		and DAG.CodeId in (0, @CodeId)
		AND dbo.NU_CodesFr.Asteriks = 1
		  ORDER BY DAGGERID
	  SELECT  DISTINCT   OptStmtsDesc   , DAGG.SubHeaderId, 
	        DAGG.HeaderId, DAGG.ChapterId, dbo.NU_CodesFr.Asteriks, 
	        dbo.NU_CodesFr.Dagger, DAGG.CodeId    , DAGG.CodeLink1, DAGG.CodeLink2,DaggerID,Daggerid as TblID
	        From NU_DaggerFr as DAGG INNER JOIN dbo.NU_CodesFr ON DAGG.Codeid = dbo.NU_CodesFr.CodeId
		WHERE 
		DAGG.ChapterID = @ChapterID 
		and DAGG.HeaderID in (0, @HeaderID)
		and DAGG.SubHeaderID in (0, @SubHeaderID)
		and DAGG.CodeHeader in (0, @CodeHeader)
		and DAGG.SubCodeHeader in (0, @SubCodeHeader)
		and DAGG.CodeID in (0, @CodeID) AND    dbo.NU_CodesFr.Dagger = 1  ORDER BY DaggerId
	SELECT    NoteDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader ,NoteId ,CodeLink1,NoteId as TblID
	      From   NU_NotesFr
	         WHERE 	ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)

		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY NOTEID
	end
	if   @SwitchStmt = 2
	begin
	SELECT --DISTINCT 
	                       IncludeDesc,  CodeId,  ChapterId,  HeaderId, 
	                       SubHeaderId,  CodeHeader,  SubCodeHeader,  CodeLink1, 
	                       CodeLink2  ,includeid as TblID--, dbo.ICD_ProcFile10.Code
	FROM         dbo.NU_IntIncludeFr
	WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID)  ORDER BY IncludeID
	SELECT --DISTINCT 
	                      dbo.NU_IntExcludeFr.ExcludeDesc, dbo.NU_IntExcludeFr.CodeId, dbo.NU_IntExcludeFr.ChapterId, dbo.NU_IntExcludeFr.HeaderId, 
	                      dbo.NU_IntExcludeFr.SubHeaderId, dbo.NU_IntExcludeFr.CodeHeader, dbo.NU_IntExcludeFr.SubCodeHeader, dbo.NU_IntExcludeFr.CodeLink1, 
	                      dbo.NU_IntExcludeFr.CodeLink2 ,excludeid as TblID--, dbo.ICD_ProcFile10.Code
	FROM         dbo.NU_IntExcludeFr
	WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID)  ORDER BY ExcludeID
	  SELECT   DISTINCT   DAGG.OmitDesc  ,  DAGG.SubHeaderId, 
	         DAGG.HeaderId,  DAGG.ChapterId,  
	         DAGG.Omitid,  DAGG.CodeId    ,  DAGG.CodeLink1,  DAGG.CodeLink2,DAGG.Omitid as TblID
	        From dbo.NU_IntOmitCodeFr AS DAGG INNER JOIN dbo.NU_IntCodesFr ON  DAGG.CodeId = dbo.NU_IntCodesFr.Codeid
	             WHERE    DAGG.ChapterID = @ChapterID 
		and DAGG.HeaderID in (0, @HeaderID)
		and DAGG.SubHeaderID in (0, @SubHeaderID)
		and DAGG.CodeHeader in (0, @CodeHeader)
		and DAGG.SubCodeHeader in (0, @SubCodeHeader)
		and DAGG.CodeId in (0, @CodeId)
		ORDER BY OmitID
	SELECT DISTINCT 
	                       dbo.NU_IntCodeAlsoFr.AlsoDesc   , dbo.NU_IntCodeAlsoFr.CodeId, dbo.NU_IntCodeAlsoFr.ChapterId, dbo.NU_IntCodeAlsoFr.HeaderId, 
	                      dbo.NU_IntCodeAlsoFr.SubHeaderId, dbo.NU_IntCodeAlsoFr.CodeHeader, dbo.NU_IntCodeAlsoFr.SubCodeHeader, dbo.NU_IntCodeAlsoFr.CodeLink1, 
	                      dbo.NU_IntCodeAlsoFr.CodeLink2 ,AlsoID,Alsoid as TblID --, dbo.ICD_ProcFile10.Code
	FROM         dbo.NU_IntCodeAlsoFr
	     WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY AlsoID
	SELECT   
	                      dbo.NU_IntNotesFr.NoteDesc, dbo.NU_IntNotesFr.CodeId, dbo.NU_IntNotesFr.ChapterId, dbo.NU_IntNotesFr.HeaderId, 
	                      dbo.NU_IntNotesFr.SubHeaderId, dbo.NU_IntNotesFr.CodeHeader, dbo.NU_IntNotesFr.SubCodeHeader ,dbo.NU_IntNotesFr.NoteId  ,CodeLink1,dbo.NU_IntNotesFr.NoteId as TblID
	               
	FROM         dbo.NU_IntNotesFr
	      WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY NOTEID
	 
	end

END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO







CREATE                     PROCEDURE [NU_GetGuidelinesCodes] 
		@CodeId as varchar(20),
		@ValidDate as datetime, 
		@SwitchStmt as int = 1, 
		@OptionalStmt as varchar (10) = 0 
		 
AS

IF @OptionalStmt = '0' BEGIN	-- English 
	if @SwitchStmt = 1 -- Diagnosis
	begin 
		-----        CIHI Coding Guidelines               ------------
-- 		IF (SELECT count(*)
-- 			FROM NU_GuideLines WHERE (@CodeId BETWEEN StartCode and EndCode Or StartCode Like @CodeId + '%')
-- 			AND ValidFrom <= cast( @ValidDate as varchar(20)) 
-- 			AND ValidTo >= cast( @ValidDate as varchar(20)) ) > 0 
-- 	
-- 		BEGIN 
			SELECT GuideLineId, MessageText, ErrorLevel, StartCode , EndCode, MultipleOcc, ReplaceRuleID
			FROM NU_GuideLines WHERE (@CodeId BETWEEN StartCode and EndCode Or StartCode Like @CodeId + '%')
			AND ValidFrom <= cast( @ValidDate as varchar(20)) 
			AND ValidTo >= cast( @ValidDate as varchar(20))
			ORDER BY MultipleOcc, ReplaceRuleID

			-- Only Includes
			SELECT a.GuideLineId as [GuidelineIDInc],  '.' + c.StartCode as [StartCode], c.EndCode as [EndCode], c.DiagTypeID as [DiagType] 
			FROM NU_GuideLines a, dbo.NU_GuidelineCodeLinkRel b, dbo.NU_GuidelineLink c
		         Where a.GuideLineId = b.GuideLineId And b.GuidelineLinkId = c.GuidelineLinkId 
		        	AND (@CodeId BETWEEN a.StartCode and a.EndCode Or a.StartCode Like @CodeId + '%')
				AND ValidFrom <= cast( @ValidDate as varchar(20)) 
				AND ValidTo >= cast( @ValidDate as varchar(20))  
				AND IsInclude = 1
				AND MultipleOcc = 0 ORDER BY [StartCode]

			-- Only Excludes
			SELECT a.GuideLineId as [GuidelineIDExc],'.' + c.StartCode as [StartCode], + c.EndCode as [EndCode], c.DiagTypeID as [DiagType]  
			FROM NU_GuideLines a, dbo.NU_GuidelineCodeLinkRel b, dbo.NU_GuidelineLink c
		         Where a.GuideLineId = b.GuideLineId And b.GuidelineLinkId = c.GuidelineLinkId 
		        	AND (@CodeId BETWEEN a.StartCode and a.EndCode Or a.StartCode Like @CodeId + '%')
				AND ValidFrom <= cast( @ValidDate as varchar(20)) 
				AND ValidTo >= cast( @ValidDate as varchar(20))  
				AND IsInclude = 0
				AND MultipleOcc = 0 ORDER BY [StartCode]

			-- Only MultipleOcc and NOT Replace rules
			SELECT a.GuideLineId as [GuidelineIDMult],'.' + c.StartCode as [StartCode], + c.EndCode as [EndCode], c.DiagTypeID as [DiagType]  
			FROM NU_GuideLines a, dbo.NU_GuidelineCodeLinkRel b, dbo.NU_GuidelineLink c
		         Where a.GuideLineId = b.GuideLineId And b.GuidelineLinkId = c.GuidelineLinkId 
		        	AND (@CodeId BETWEEN a.StartCode and a.EndCode Or a.StartCode Like @CodeId + '%')
				AND ValidFrom <= cast( @ValidDate as varchar(20)) 
				AND ValidTo >= cast( @ValidDate as varchar(20))  
				AND IsInclude = 1
				AND MultipleOcc = 1
				AND ReplaceRuleID is NULL 
				ORDER BY [StartCode]

			-- Only MultipleOcc and Replace rules
			SELECT a.GuideLineId as [GuidelineIDRep],'.' + c.StartCode as [StartCode], + c.EndCode as [EndCode], c.DiagTypeID as [DiagType] , ReplaceRuleID 
			FROM NU_GuideLines a, dbo.NU_GuidelineCodeLinkRel b, dbo.NU_GuidelineLink c
		         Where a.GuideLineId = b.GuideLineId And b.GuidelineLinkId = c.GuidelineLinkId 
		        	AND (@CodeId BETWEEN a.StartCode and a.EndCode Or a.StartCode Like @CodeId + '%')
				AND ValidFrom <= cast( @ValidDate as varchar(20)) 
				AND ValidTo >= cast( @ValidDate as varchar(20))  
				AND IsInclude = 1
				AND MultipleOcc = 1
				AND ReplaceRuleID is not NULL ORDER BY ReplaceRuleID


-- 		END
		-----        USER Coding Guidelines               ------------ 
-- 		IF (SELECT count(*)
-- 			FROM NU_UserGuideLines WHERE (@CodeId BETWEEN StartCode and EndCode Or StartCode Like @CodeId + '%')
-- 			AND ValidFrom <= cast( @ValidDate as varchar(20)) 
-- 			AND ValidTo >= cast( @ValidDate as varchar(20))  ) > 0 
-- 	
-- 		BEGIN 
			SELECT GuideLineId, MessageText, ErrorLevel, StartCode , EndCode, MultipleOcc, ReplaceRuleID
			FROM NU_UserGuideLines WHERE (@CodeId BETWEEN StartCode and EndCode Or StartCode Like @CodeId + '%')
			AND ValidFrom <= cast( @ValidDate as varchar(20)) 
			AND ValidTo >= cast( @ValidDate as varchar(20))
			ORDER BY MultipleOcc, ReplaceRuleID

			-- Only Includes
			SELECT a.GuideLineId as [GuidelineIDInc],  '.' + c.StartCode as [StartCode], c.EndCode as [EndCode], c.DiagTypeID as [DiagType] 
			FROM NU_UserGuideLines a, dbo.NU_UserGuidelineCodeLinkRel b, dbo.NU_UserGuidelineLink c
		         Where a.GuideLineId = b.GuideLineId And b.GuidelineLinkId = c.GuidelineLinkId 
		        	AND (@CodeId BETWEEN a.StartCode and a.EndCode Or a.StartCode Like @CodeId + '%')
				AND ValidFrom <= cast( @ValidDate as varchar(20)) 
				AND ValidTo >= cast( @ValidDate as varchar(20))  
				AND IsInclude = 1
				AND MultipleOcc = 0 ORDER BY [StartCode]

			-- Only Excludes
			SELECT a.GuideLineId as [GuidelineIDExc],'.' + c.StartCode as [StartCode], + c.EndCode as [EndCode], c.DiagTypeID as [DiagType]  
			FROM NU_UserGuideLines a, dbo.NU_UserGuidelineCodeLinkRel b, dbo.NU_UserGuidelineLink c
		         Where a.GuideLineId = b.GuideLineId And b.GuidelineLinkId = c.GuidelineLinkId 
		        	AND (@CodeId BETWEEN a.StartCode and a.EndCode Or a.StartCode Like @CodeId + '%')
				AND ValidFrom <= cast( @ValidDate as varchar(20)) 
				AND ValidTo >= cast( @ValidDate as varchar(20))  
				AND IsInclude = 0
				AND MultipleOcc = 0 ORDER BY [StartCode]

			-- Only MultipleOcc and NOT Replace rules
			SELECT a.GuideLineId as [GuidelineIDMult],'.' + c.StartCode as [StartCode], + c.EndCode as [EndCode], c.DiagTypeID as [DiagType]  
			FROM NU_UserGuideLines a, dbo.NU_UserGuidelineCodeLinkRel b, dbo.NU_UserGuidelineLink c
		         Where a.GuideLineId = b.GuideLineId And b.GuidelineLinkId = c.GuidelineLinkId 
		        	AND (@CodeId BETWEEN a.StartCode and a.EndCode Or a.StartCode Like @CodeId + '%')
				AND ValidFrom <= cast( @ValidDate as varchar(20)) 
				AND ValidTo >= cast( @ValidDate as varchar(20))  
				AND IsInclude = 1
				AND MultipleOcc = 1
				AND ReplaceRuleID is NULL 
				ORDER BY [StartCode]
			

-- 		END 


	end 

-- 	if @SwitchStmt = 2  -- Interventions not apply 
-- 	begin
-- 	end
 END

-- IF @OptionalStmt = '10000' BEGIN  --French future
-- 	if @SwitchStmt = 1
-- 	begin 
-- 	end
-- 	if @SwitchStmt = 2
-- 	begin
-- 	end
-- 
-- END


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO















CREATE            PROCEDURE [NU_GetInclude] 
		@ChapterId as int,
		@HeaderId as int,
		@SubHeaderid as int,
		@CodeId as int,
		@CodeHeader as int ,
		@SubCodeHeader as int,
		@SwitchStmt as int,
		@OptionalStmt as varchar (10)
		 
AS


IF @OptionalStmt = '0' BEGIN	
	if @SwitchStmt = 1
	begin 
	SELECT  IncludeDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader ,CodeHeader, CodeLink1,CodeLink2
	      From dbo.NU_Include  
	       WHERE 	ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY INCLUDEID
	 SELECT  ExcludeDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader , CodeLink1,CodeLink2
	      From dbo.NU_Exclude  
	     WHERE 	ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY EXCLUDEID
	 SELECT   DISTINCT DAG.OptStmtsDesc   ,  DAG.SubHeaderId, 
	         DAG.HeaderId,  DAG.ChapterId, dbo.NU_Codes.Asteriks, 
	         DAG.DaggerId,DAG.CodeId,DAG.CodeLink1,  DAG.CodeLink2 
	        From dbo.NU_Dagger as DAG INNER JOIN dbo.NU_Codes ON  DAG.CodeId = dbo.NU_Codes.Codeid
	             WHERE   DAG.ChapterID = @ChapterID 
		and DAG.HeaderID in (0, @HeaderID)
		and DAG.SubHeaderID in (0, @SubHeaderID)
		and DAG.CodeHeader in (0, @CodeHeader) 
		and DAG.SubCodeHeader in (0, @SubCodeHeader)
		and DAG.CodeId in (0, @CodeId)
		AND dbo.NU_Codes.Asteriks = 1
		  ORDER BY DAGGERID
	  SELECT  DISTINCT   OptStmtsDesc   , DAGG.SubHeaderId, 
	        DAGG.HeaderId, DAGG.ChapterId, dbo.NU_Codes.Asteriks, 
	        dbo.NU_Codes.Dagger, DAGG.CodeId    , DAGG.CodeLink1, DAGG.CodeLink2,DaggerID
	        From NU_Dagger as DAGG INNER JOIN dbo.NU_Codes ON DAGG.Codeid = dbo.NU_Codes.CodeId
		WHERE 
		DAGG.ChapterID = @ChapterID 
		and DAGG.HeaderID in (0, @HeaderID)
		and DAGG.SubHeaderID in (0, @SubHeaderID)
		and DAGG.CodeHeader in (0, @CodeHeader)
		and DAGG.SubCodeHeader in (0, @SubCodeHeader)
		and DAGG.CodeID in (0, @CodeID) AND    dbo.NU_Codes.Dagger = 1  ORDER BY DaggerId
	SELECT    NoteDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader ,NoteId ,CodeLink1
	      From   NU_Notes
	         WHERE 	ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		--and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY NOTEID
	end
	if   @SwitchStmt = 2
	begin
	SELECT --DISTINCT 
	                       IncludeDesc,  CodeId,  ChapterId,  HeaderId, 
	                       SubHeaderId,  CodeHeader,  SubCodeHeader,  CodeLink1, 
	                       CodeLink2  --, dbo.ICD_ProcFile10.Code
	FROM         dbo.NU_IntInclude
	WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID)  ORDER BY IncludeID
	SELECT --DISTINCT 
	                      dbo.NU_IntExclude.ExcludeDesc, dbo.NU_IntExclude.CodeId, dbo.NU_IntExclude.ChapterId, dbo.NU_IntExclude.HeaderId, 
	                      dbo.NU_IntExclude.SubHeaderId, dbo.NU_IntExclude.CodeHeader, dbo.NU_IntExclude.SubCodeHeader, dbo.NU_IntExclude.CodeLink1, 
	                      dbo.NU_IntExclude.CodeLink2--, dbo.ICD_ProcFile10.Code
	FROM         dbo.NU_IntExclude
	WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID)  ORDER BY ExcludeID
	  SELECT   DISTINCT   DAGG.OmitDesc  ,  DAGG.SubHeaderId, 
	         DAGG.HeaderId,  DAGG.ChapterId,  
	         DAGG.Omitid,  DAGG.CodeId    ,  DAGG.CodeLink1,  DAGG.CodeLink2
	        From dbo.NU_IntOmitCode AS DAGG INNER JOIN dbo.NU_IntCodes ON  DAGG.CodeId = dbo.NU_IntCodes.Codeid
	             WHERE    DAGG.ChapterID = @ChapterID 
		and DAGG.HeaderID in (0, @HeaderID)
		and DAGG.SubHeaderID in (0, @SubHeaderID)
		and DAGG.CodeHeader in (0, @CodeHeader)
		and DAGG.SubCodeHeader in (0, @SubCodeHeader)
		and DAGG.CodeId in (0, @CodeId)
		ORDER BY OmitID
	SELECT DISTINCT 
	                       dbo.NU_IntCodeAlso.AlsoDesc   , dbo.NU_IntCodeAlso.CodeId, dbo.NU_IntCodeAlso.ChapterId, dbo.NU_IntCodeAlso.HeaderId, 
	                      dbo.NU_IntCodeAlso.SubHeaderId, dbo.NU_IntCodeAlso.CodeHeader, dbo.NU_IntCodeAlso.SubCodeHeader, dbo.NU_IntCodeAlso.CodeLink1, 
	                      dbo.NU_IntCodeAlso.CodeLink2 ,AlsoID --, dbo.ICD_ProcFile10.Code
	FROM         dbo.NU_IntCodeAlso
	     WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY AlsoID
	SELECT   
	                      dbo.NU_IntNotes.NoteDesc, dbo.NU_IntNotes.CodeId, dbo.NU_IntNotes.ChapterId, dbo.NU_IntNotes.HeaderId, 
	                      dbo.NU_IntNotes.SubHeaderId, dbo.NU_IntNotes.CodeHeader, dbo.NU_IntNotes.SubCodeHeader ,dbo.NU_IntNotes.NoteId  ,CodeLink1
	               
	FROM         dbo.NU_IntNotes
	      WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY NOTEID
	 
	end
END

IF @OptionalStmt = '10000' BEGIN
	if @SwitchStmt = 1
	begin 
	SELECT  IncludeDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader ,CodeHeader, CodeLink1,CodeLink2
	      From dbo.NU_IncludeFr  
	       WHERE 	ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID) ORDER BY INCLUDEID
	 
-- 	SELECT  ExcludeDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader , CodeLink1,CodeLink2
-- 	      From dbo.NU_ExcludeFr  
-- 	     WHERE 	ChapterID = @ChapterID 
-- 		and HeaderID in (0, @HeaderID)
-- 		and SubHeaderID in (0, @SubHeaderID)
-- 		and CodeHeader in (0, @CodeHeader)
-- 		and SubCodeHeader in (0, @SubCodeHeader)
-- 		and CodeID in (0, @CodeID) ORDER BY EXCLUDEID
-- 	 
-- 	SELECT   DISTINCT DAG.OptStmtsDesc   ,  DAG.SubHeaderId, 
-- 	         DAG.HeaderId,  DAG.ChapterId, dbo.NU_CodesFr.Asteriks, 
-- 	         DAG.DaggerId,DAG.CodeId,DAG.CodeLink1,  DAG.CodeLink2 
-- 	        From dbo.NU_DaggerFr as DAG INNER JOIN dbo.NU_CodesFr ON  DAG.CodeId = dbo.NU_CodesFr.Codeid
-- 	             WHERE   DAG.ChapterID = @ChapterID 
-- 		and DAG.HeaderID in (0, @HeaderID)
-- 		and DAG.SubHeaderID in (0, @SubHeaderID)
-- 		and DAG.CodeHeader in (0, @CodeHeader) 
-- 		and DAG.SubCodeHeader in (0, @SubCodeHeader)
-- 		and DAG.CodeId in (0, @CodeId)
-- 		AND dbo.NU_CodesFr.Asteriks = 1
-- 		  ORDER BY DAGGERID
-- 	  SELECT  DISTINCT   OptStmtsDesc   , DAGG.SubHeaderId, 
-- 	        DAGG.HeaderId, DAGG.ChapterId, dbo.NU_CodesFr.Asteriks, 
-- 	        dbo.NU_CodesFr.Dagger, DAGG.CodeId    , DAGG.CodeLink1, DAGG.CodeLink2,DaggerID
-- 	        From NU_DaggerFr as DAGG INNER JOIN dbo.NU_CodesFr ON DAGG.Codeid = dbo.NU_CodesFr.CodeId
-- 		WHERE 
-- 		DAGG.ChapterID = @ChapterID 
-- 		and DAGG.HeaderID in (0, @HeaderID)
-- 		and DAGG.SubHeaderID in (0, @SubHeaderID)
-- 		and DAGG.CodeHeader in (0, @CodeHeader)
-- 		and DAGG.SubCodeHeader in (0, @SubCodeHeader)
-- 		and DAGG.CodeID in (0, @CodeID) AND    dbo.NU_CodesFr.Dagger = 1  ORDER BY DaggerId
-- 	SELECT    NoteDesc , CodeId, ChapterID , HeaderID, SubHeaderID ,  CodeHeader ,NoteId ,CodeLink1
-- 	      From   NU_NotesFr
-- 	         WHERE 	ChapterID = @ChapterID 
-- 		and HeaderID in (0, @HeaderID)
-- 		and SubHeaderID in (0, @SubHeaderID)
-- 		and CodeHeader in (0, @CodeHeader)
-- 
-- 		and SubCodeHeader in (0, @SubCodeHeader)
-- 		and CodeID in (0, @CodeID) ORDER BY NOTEID
	end
	if   @SwitchStmt = 2
	begin
	SELECT --DISTINCT 
	                       IncludeDesc,  CodeId,  ChapterId,  HeaderId, 
	                       SubHeaderId,  CodeHeader,  SubCodeHeader,  CodeLink1, 
	                       CodeLink2  --, dbo.ICD_ProcFile10.Code
	FROM         dbo.NU_IntIncludeFr
	WHERE  ChapterID = @ChapterID 
		and HeaderID in (0, @HeaderID)
		and SubHeaderID in (0, @SubHeaderID)
		and CodeHeader in (0, @CodeHeader)
		and SubCodeHeader in (0, @SubCodeHeader)
		and CodeID in (0, @CodeID)  ORDER BY IncludeID
-- 	SELECT --DISTINCT 
-- 	                      dbo.NU_IntExcludeFr.ExcludeDesc, dbo.NU_IntExcludeFr.CodeId, dbo.NU_IntExcludeFr.ChapterId, dbo.NU_IntExcludeFr.HeaderId, 
-- 	                      dbo.NU_IntExcludeFr.SubHeaderId, dbo.NU_IntExcludeFr.CodeHeader, dbo.NU_IntExcludeFr.SubCodeHeader, dbo.NU_IntExcludeFr.CodeLink1, 
-- 	                      dbo.NU_IntExcludeFr.CodeLink2--, dbo.ICD_ProcFile10.Code
-- 	FROM         dbo.NU_IntExcludeFr
-- 	WHERE  ChapterID = @ChapterID 
-- 		and HeaderID in (0, @HeaderID)
-- 		and SubHeaderID in (0, @SubHeaderID)
-- 		and CodeHeader in (0, @CodeHeader)
-- 		and SubCodeHeader in (0, @SubCodeHeader)
-- 		and CodeID in (0, @CodeID)  ORDER BY ExcludeID
-- 	  SELECT   DISTINCT   DAGG.OmitDesc  ,  DAGG.SubHeaderId, 
-- 	         DAGG.HeaderId,  DAGG.ChapterId,  
-- 	         DAGG.Omitid,  DAGG.CodeId    ,  DAGG.CodeLink1,  DAGG.CodeLink2
-- 	        From dbo.NU_IntOmitCodeFr AS DAGG INNER JOIN dbo.NU_IntCodesFr ON  DAGG.CodeId = dbo.NU_IntCodesFr.Codeid
-- 	             WHERE    DAGG.ChapterID = @ChapterID 
-- 		and DAGG.HeaderID in (0, @HeaderID)
-- 		and DAGG.SubHeaderID in (0, @SubHeaderID)
-- 		and DAGG.CodeHeader in (0, @CodeHeader)
-- 		and DAGG.SubCodeHeader in (0, @SubCodeHeader)
-- 		and DAGG.CodeId in (0, @CodeId)
-- 		ORDER BY OmitID
-- 	SELECT DISTINCT 
-- 	                       dbo.NU_IntCodeAlsoFr.AlsoDesc   , dbo.NU_IntCodeAlsoFr.CodeId, dbo.NU_IntCodeAlsoFr.ChapterId, dbo.NU_IntCodeAlsoFr.HeaderId, 
-- 	                      dbo.NU_IntCodeAlsoFr.SubHeaderId, dbo.NU_IntCodeAlsoFr.CodeHeader, dbo.NU_IntCodeAlsoFr.SubCodeHeader, dbo.NU_IntCodeAlsoFr.CodeLink1, 
-- 	                      dbo.NU_IntCodeAlsoFr.CodeLink2 ,AlsoID --, dbo.ICD_ProcFile10.Code
-- 	FROM         dbo.NU_IntCodeAlsoFr
-- 	     WHERE  ChapterID = @ChapterID 
-- 		and HeaderID in (0, @HeaderID)
-- 		and SubHeaderID in (0, @SubHeaderID)
-- 		and CodeHeader in (0, @CodeHeader)
-- 		and SubCodeHeader in (0, @SubCodeHeader)
-- 		and CodeID in (0, @CodeID) ORDER BY AlsoID
-- 	SELECT   
-- 	                      dbo.NU_IntNotesFr.NoteDesc, dbo.NU_IntNotesFr.CodeId, dbo.NU_IntNotesFr.ChapterId, dbo.NU_IntNotesFr.HeaderId, 
-- 	                      dbo.NU_IntNotesFr.SubHeaderId, dbo.NU_IntNotesFr.CodeHeader, dbo.NU_IntNotesFr.SubCodeHeader ,dbo.NU_IntNotesFr.NoteId  ,CodeLink1
-- 	               
-- 	FROM         dbo.NU_IntNotesFr
-- 	      WHERE  ChapterID = @ChapterID 
-- 		and HeaderID in (0, @HeaderID)
-- 		and SubHeaderID in (0, @SubHeaderID)
-- 		and CodeHeader in (0, @CodeHeader)
-- 		and SubCodeHeader in (0, @SubCodeHeader)
-- 		and CodeID in (0, @CodeID) ORDER BY NOTEID
	 
	end

END















GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






CREATE   Procedure [NU_GetIProfile]
@ProfileID as int,
@LangID as int
AS


if @LangID=0
Begin

SELECT dbo.NU_IntCodes.Codenum, dbo.NU_IntCodes.CodeDesc as U_Desc,
TypeS,TypeL,TypeE,TypeSCode,TypeLCode,TypeECode
FROM    dbo.NU_IntProfile INNER JOIN
dbo.NU_IntCodes ON dbo.NU_IntProfile.CIHIVALUE = dbo.NU_IntCodes.CIHIVALUE
where ProfileID=@ProfileID
order by NU_IntProfile.Autoid
-- Select CodeNum
-- ,(select top 1 CodeDesc  from Nu_intCodes as I where I.Codenum = codenum or I.cihivalue=NU_IntProfile.cihivalue) as U_Desc
-- ,TypeS,TypeL,TypeE,TypeSCode,TypeLCode,TypeECode
-- from NU_IntProfile where ProfileID=@ProfileID

End


if @LangID=10000 
Begin

SELECT dbo.NU_IntCodesFr.Codenum, dbo.NU_IntCodesFr.CodeDesc as U_Desc,
TypeS,TypeL,TypeE,TypeSCode,TypeLCode,TypeECode
FROM    dbo.NU_IntProfile INNER JOIN
dbo.NU_IntCodesFr ON dbo.NU_IntProfile.CIHIVALUE = dbo.NU_IntCodesFr.CIHIVALUE
where ProfileID=@ProfileID
order by NU_IntProfile.Autoid
-- Select CodeNum
-- ,(select top 1 CodeDesc  from Nu_intCodesFr as I where I.Codenum = codenum or I.cihivalue=NU_IntProfile.cihivalue) as U_Desc
-- ,TypeS,TypeL,TypeE,TypeSCode,TypeLCode,TypeECode
-- from NU_IntProfile where ProfileID=@ProfileID

End





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO














CREATE PROCEDURE [NU_GetLUType] AS
Select DisplayCode ,UserDescription,CIHIValue From LU_DiagnosisType 














GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO







CREATE   PROCEDURE [NU_GetProfiles] 
@Gender as varchar(1),
@Age as int,
@VisitDate as datetime,
@OptionalStmt as varchar(10),
@UserId as int 
AS

--the param are ready for filtered List of Profile
Select * from NU_Profile order by ProfileName   -- modifiedDt   PR - 03915










GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


























CREATE                     PROCEDURE [NU_GetUserNotes] 
			@DisplayCode as varchar(15),
			@SwitchStmt as int,
			@OptionalStmt as varchar (10)
AS


set nocount on 
create table #Q ( 
ICDNotes varchar(2500),   -- Changed from 255 EN - 00401
codenum varchar(20)
)

IF @OptionalStmt = '0' BEGIN
	if @SwitchStmt  = 2
	
	begin
	-- exact match 
	INSERT INTO #Q
	SELECT    isnull(ICDNOTES,''),codenum 	      From   NU_IntCodes	WHERE CodeNum LIKE @DisplayCode AND ICDNOTES <> ''

	-- The Higher level 
	IF (SELECT  DISTINCT subCODEHEADER FROM NU_IntCodes WHERE CodeNum LIKE @DisplayCode  ) > 0
	begin 
		INSERT INTO #Q
		SELECT    isnull(ICDNOTES,''),codenum	      From   NU_IntCodes
		WHERE CODEHEADER = (SELECT  DISTINCT CODEHEADER FROM NU_IntCodes 	
		WHERE CodeNum LIKE @DisplayCode  )  	AND  CODEID = 0  and subcodeheader = 0 AND ICDNOTES <> ''  --PR-03820 delete contition CODEHEADER <> 0 ADDED and subcodeheader = 0
	end 

	-- Next high level 
	IF (SELECT  DISTINCT subCODEHEADER FROM NU_IntCodes WHERE CodeNum LIKE @DisplayCode  ) > 0
	begin 
		insert into #Q
		SELECT    isnull(ICDNOTES,''),codenum	      From   NU_IntCodes
	      --WHERE AutoID = (SELECT DISTINCT  AutoID FROM NU_IntCodes  WHERE CodeNum LIKE @DisplayCode AND subheaderid <> 0) -- REPLACE  PR - 03820
		WHERE AutoId in  (select Autoid from NU_IntCodes where  subCodeHeader = (SELECT DISTINCT  subCodeHeader FROM NU_IntCodes  WHERE CodeNum LIKE @DisplayCode))
		AND  CODEID = 0 AND ICDNOTES <> ''
	end 
	end
	
	if @SwitchStmt = 1 
	
	begin
	 
	-- exact match 
	INSERT INTO #Q
	SELECT    isnull(ICDNOTES,''),codenum 	      From   NU_Codes	WHERE CodeNum LIKE @DisplayCode AND ICDNOTES <> ''

	-- The Higher level 
	INSERT INTO #Q
	SELECT    isnull(ICDNOTES,''),codenum 	      From   NU_Codes
	WHERE subHeaderId = (SELECT DISTINCT  subHeaderId FROM NU_CODES 	
	WHERE CodeNum LIKE @DisplayCode )  	AND  CODEID = 0  and codeheader = 0  AND ICDNOTES <> ''  --PR-03820 delete contition CODEHEADER <> 0 ADDED and subcodeheader = 0


	-- Next high level 
	IF (SELECT  DISTINCT CODEHEADER FROM NU_Codes WHERE CodeNum LIKE @DisplayCode  ) > 0
	begin 
		insert into #Q
		SELECT    isnull(ICDNOTES,''),codenum 	      From   NU_Codes
	      --WHERE subheaderid = (SELECT DISTINCT  subheaderid FROM NU_CODES  WHERE CodeNum LIKE @DisplayCode AND subheaderid <> 0) -- REPLACE PR - 03820
		WHERE AutoId in  (select Autoid from nu_codes where  CodeHeader = (SELECT DISTINCT  CodeHeader FROM NU_CODES  WHERE CodeNum LIKE @DisplayCode))
		AND  CODEID = 0 AND ICDNOTES <> ''
	end 
	end

END

If @OptionalStmt = '10000' BEGIN
if @SwitchStmt  = 2
	
	begin
	INSERT INTO #Q
	SELECT    isnull(ICDNOTES,''),codenum
	      From   NU_IntCodesFr
	--WHERE CodeNum LIKE  @DisplayCode + '%'  AND ICDNOTES <> ''
	WHERE CodeNum LIKE  @DisplayCode   AND ICDNOTES <> ''
	INSERT INTO #Q
	SELECT    isnull(ICDNOTES,''),codenum
	      From   NU_IntCodesFr
	WHERE CODEHEADER = (SELECT DISTINCT  CODEHEADER FROM NU_IntCodesFr
	WHERE CodeNum LIKE @DisplayCode ) -- AND  CODEHEADER <> 0 ) 
	AND  CODEID = 0 AND ICDNOTES <> ''
	insert into #Q
	SELECT    isnull(ICDNOTES,''),codenum
	      From   NU_IntCodesfr
	WHERE subheaderid = (SELECT DISTINCT  subheaderid FROM NU_IntCodesfr 
	WHERE CodeNum LIKE @DisplayCode AND subheaderid <> 0) 
	AND  CODEID = 0 AND ICDNOTES <> ''
	end
	
	if @SwitchStmt = 1 
	
	begin
	 
	
	INSERT INTO #Q
	SELECT    isnull(ICDNOTES,''),codenum
	      From   NU_CodesFr
	--WHERE CodeNum LIKE @DisplayCode + '%' AND ICDNOTES <> ''
	WHERE CodeNum LIKE @DisplayCode  AND ICDNOTES <> ''
	INSERT INTO #Q
	SELECT    isnull(ICDNOTES,''),codenum
	      From   NU_CodesFr
	WHERE subheaderid = (SELECT DISTINCT  subheaderid FROM NU_CODESFr
	 WHERE CodeNum LIKE  substring(@DisplayCode,1,4)  ) --AND CODEHEADER <> 0 ) 
	AND  CODEID = 0 AND ICDNOTES <> ''
	insert into #Q
	SELECT    isnull(ICDNOTES,''),codenum
	      From   NU_Codesfr
	WHERE subheaderid = (SELECT DISTINCT  subheaderid FROM NU_CODESfr 
	WHERE CodeNum LIKE @DisplayCode AND subheaderid <> 0) 
	AND  CODEID = 0 AND ICDNOTES <> ''
	end
END

SELECT DISTINCT ICDNOTES,codenum  FROM #Q WHERE ICDNOTES <> ''
























GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO












CREATE                    PROCEDURE [NU_GetUserPrvNotes] 
			@Code as varchar(20),
			@SwitchStmt as int,
			@OptionalStmt as varchar (10),
			@Type as int
AS
set nocount on 
create table #Q ( 
ICDNotes nvarchar(2500),  -- Changed from varchar(255) EN - 00401
codenum varchar(20),
PrvNoteId int
)


If  @OptionalStmt = '10000' 
begin
if @Type = 1 
begin
	-- exact match 
	insert into #Q
	SELECT     dbo.NU_PrvNotes.PrvNote AS ICDNOTES,dbo.NU_PrvNotes.codenum,PrvNoteId
	FROM         dbo.NU_PrvNotes INNER JOIN    dbo.NU_CodesFr ON  	dbo.NU_PrvNotes.Code = dbo.NU_CodesFr.Autoid 
	WHERE     (dbo.NU_CodesFr.CodeNum = @Code) AND (dbo.NU_PrvNotes.UserId = @SwitchStmt) AND dbo.NU_PrvNotes.LangId = @OptionalStmt

	-- Look for the higher level 
	insert into #Q
	select  PrvNote AS ICDNOTES,dbo.NU_PrvNotes.codenum,PrvNoteId from nu_prvnotes  where 	code IN (
		select Autoid from NU_CodesFr where  Chapterid = (SELECT DISTINCT  Chapterid FROM NU_CodesFr  WHERE CodeNum LIKE @Code) 
		AND  CODEID = 0 AND CODEHEADER = 0)
	AND 
	userid=@SwitchStmt AND dbo.NU_PrvNotes.LangId = @OptionalStmt

	-- look for the other headers when the code it's not a Big header
	
	if (SELECT DISTINCT  CODEHEADER FROM NU_CodesFr WHERE CodeNum LIKE @Code) > 0   
	Begin 
	insert into #Q	
	select  PrvNote AS ICDNOTES,dbo.NU_PrvNotes.codenum,PrvNoteId from nu_prvnotes 	where 	code IN  (
		select Autoid  from NU_CodesFr where CODEHEADER = (SELECT DISTINCT CODEHEADER FROM NU_CodesFr WHERE CodeNum LIKE @Code) 
		AND  CODEID = 0	)
	END
end

if @Type = 2 
begin
	-- exact match 
	insert into #Q
	SELECT     dbo.NU_PrvNotes.PrvNote AS ICDNOTES,dbo.NU_PrvNotes.codenum,PrvNoteId
	FROM         dbo.NU_PrvNotes INNER JOIN      dbo.NU_IntCodesFr ON	dbo.NU_PrvNotes.Code = dbo.NU_IntCodesFr.Autoid 
	WHERE     (dbo.NU_IntCodesFr.CodeNum = @Code)  	AND (dbo.NU_PrvNotes.UserId = @SwitchStmt) 	AND dbo.NU_PrvNotes.LangId = @OptionalStmt   


	-- Look for the higher level 
	insert into #Q
	select  PrvNote AS ICDNOTES,dbo.NU_PrvNotes.codenum,PrvNoteId from nu_prvnotes 	where 	code IN  (
	select Autoid  from NU_IntCodesFr where CodeHeader = (SELECT DISTINCT  CodeHeader FROM NU_IntCodesFr WHERE CodeNum LIKE @Code)  
		AND  CODEID = 0 AND SubCodeHeader = 0 
	)
	AND 
	userid=@SwitchStmt AND dbo.NU_PrvNotes.LangId = @OptionalStmt

	-- Added PR-03820  -- look for the other headers when the code it's not a Big header ( 1.AE.^^.^^) 
	if (SELECT DISTINCT  SubCodeHeader FROM NU_IntCodesFr WHERE CodeNum LIKE @Code) > 0   
	Begin 
		insert into #Q
		select  PrvNote AS ICDNOTES,dbo.NU_PrvNotes.codenum,PrvNoteId from nu_prvnotes 	where 	code IN  (
			select Autoid  from NU_IntCodesFr where SubCodeHeader = (SELECT DISTINCT  SubCodeHeader FROM NU_IntCodesFr WHERE CodeNum LIKE @Code) 
			AND  CODEID = 0 
		)
		AND 
		userid=@SwitchStmt AND dbo.NU_PrvNotes.LangId = @OptionalStmt

	end 
end
 

end

-- PR-03820: Total makeover 
If  @OptionalStmt = '0'
begin
if @Type = 1 
begin
	-- exact match 
	insert into #Q
	SELECT     dbo.NU_PrvNotes.PrvNote AS ICDNOTES,dbo.NU_PrvNotes.codenum,PrvNoteId
	FROM         dbo.NU_PrvNotes INNER JOIN    dbo.NU_Codes ON  	dbo.NU_PrvNotes.Code = dbo.NU_Codes.Autoid 
	WHERE     (dbo.NU_Codes.CodeNum = @Code) AND (dbo.NU_PrvNotes.UserId = @SwitchStmt) AND dbo.NU_PrvNotes.LangId = @OptionalStmt

	-- Look for the higher level 
	insert into #Q
	select  PrvNote AS ICDNOTES,dbo.NU_PrvNotes.codenum,PrvNoteId from nu_prvnotes  where 	code IN (
		select Autoid from nu_codes where  Chapterid = (SELECT DISTINCT  Chapterid FROM NU_CODES  WHERE CodeNum LIKE @Code) 
		AND  CODEID = 0 AND CODEHEADER = 0)
	AND 
	userid=@SwitchStmt AND dbo.NU_PrvNotes.LangId = @OptionalStmt

	-- look for the other headers when the code it's not a Big header
	
	if (SELECT DISTINCT  CODEHEADER FROM nu_codes WHERE CodeNum LIKE @Code) > 0   
	Begin 
	insert into #Q	
	select  PrvNote AS ICDNOTES,dbo.NU_PrvNotes.codenum,PrvNoteId from nu_prvnotes 	where 	code IN  (
		select Autoid  from nu_codes where CODEHEADER = (SELECT DISTINCT CODEHEADER FROM nu_codes WHERE CodeNum LIKE @Code) 
		AND  CODEID = 0	)
	END
end

if @Type = 2 
begin
	-- exact match 
	insert into #Q
	SELECT     dbo.NU_PrvNotes.PrvNote AS ICDNOTES,dbo.NU_PrvNotes.codenum,PrvNoteId
	FROM         dbo.NU_PrvNotes INNER JOIN      dbo.NU_IntCodes ON	dbo.NU_PrvNotes.Code = dbo.NU_IntCodes.Autoid 
	WHERE     (dbo.NU_IntCodes.CodeNum = @Code)  	AND (dbo.NU_PrvNotes.UserId = @SwitchStmt) 	AND dbo.NU_PrvNotes.LangId = @OptionalStmt   


	-- Look for the higher level 
	insert into #Q
	select  PrvNote AS ICDNOTES,dbo.NU_PrvNotes.codenum,PrvNoteId from nu_prvnotes 	where 	code IN  (
	select Autoid  from nu_Intcodes where CodeHeader = (SELECT DISTINCT  CodeHeader FROM NU_IntCODES WHERE CodeNum LIKE @Code)  
		AND  CODEID = 0 AND SubCodeHeader = 0 
	)
	AND 
	userid=@SwitchStmt AND dbo.NU_PrvNotes.LangId = @OptionalStmt

	-- Added PR-03820  -- look for the other headers when the code it's not a Big header ( 1.AE.^^.^^) 
	if (SELECT DISTINCT  SubCodeHeader FROM NU_IntCODES WHERE CodeNum LIKE @Code) > 0   
	Begin 
		insert into #Q
		select  PrvNote AS ICDNOTES,dbo.NU_PrvNotes.codenum,PrvNoteId from nu_prvnotes 	where 	code IN  (
			select Autoid  from nu_Intcodes where SubCodeHeader = (SELECT DISTINCT  SubCodeHeader FROM NU_IntCODES WHERE CodeNum LIKE @Code) 
			AND  CODEID = 0 
		)
		AND 
		userid=@SwitchStmt AND dbo.NU_PrvNotes.LangId = @OptionalStmt

	end 
end


end

set nocount off
Select distinct * from #Q










GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO







CREATE        PROCEDURE [NU_IN_Prv]
	
	@UserId as int,
	@LangID as int,
	@Code as int,	
	@CodeNum as varchar(15),
	@Note as varchar(2500)
	
	
AS 

Declare @RetrunId varchar(15)

-- EBV PR-01850     fix quotation problems 
DECLARE @NOTES VARCHAR(2500)   -- it was 500 EN - 00401
DECLARE @PT INT
DECLARE @STMP AS VARCHAR(2500)  -- it was varchar(50) EN - 00401

SET @NOTES = @Note
SET @PT=1
SET @STMP=''

WHILE @PT<=LEN(@NOTES)
BEGIN
	SET @STMP=@STMP+SUBSTRING(@NOTES,@PT,1)
	IF SUBSTRING(@NOTES,@PT,1)=CHAR(39)
	BEGIN
		WHILE SUBSTRING(@NOTES,@PT+1,1)=CHAR(39) AND @PT<LEN(@NOTES)
		BEGIN
			SET @PT=@PT+1
		END
	END
	SET @PT=@PT+1
END

--SET @STMP=REPLACE(@STMP,CHAR(39),CHAR(39)+CHAR(39))  this will cause to save 2 singles quotes
SET @NOTES=@STMP

SET @Note = @NOTES
--- ENDS EBV PR-01850


Set @RetrunId =  (SELECT count(PrvNoteId)  FROM NU_PrvNotes 
		WHERe UserId = @UserId AND Code = @Code  AND CodeNum = @CodeNum and LangID=@LangID ) 
 
if @RetrunId = 0 
begin
 INSERT INTO NU_PrvNotes (UserId , Code,PrvNote,CodeNum,LangID) 
			VALUES (@UserId,@Code,@Note,@CodeNum,@LangID )
end			 
if @RetrunId <> 0 
begin

UPDATE  NU_PrvNotes SET PrvNote =  @Note 
	 WHERE UserId = @UserId AND Code = @Code AND CodeNum = @CodeNum and LangID=@LangID
end





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [NU_InsertUserRule]
	(@StartCode as [varchar] (20),
	@EndCode as [varchar] (20),
	@MultipleOcc as [int],
	@MessageText as [nvarchar] (500) ,
	@ErrorLevel as [int],
	@ValidFrom as [smalldatetime],
	@ValidTo as [smalldatetime],
	@IsInclude as [int],
	@RuleStartCode as [varchar] (20),
	@RuleEndCode as [varchar] (20),
	@DiagTypeID as [nvarchar] (12))
AS 


Declare @MaxtGuidelineID as integer
Declare @MaxGuidelineLinkID as integer

-- What will be the next GuidelineID
SELECT @MaxtGuidelineID = MAX(GuidelineId) from NU_UserGuidelines 
SELECT @MaxGuidelineLinkID = MAX(GuidelineLinkID) from NU_UserGuidelineLink
--
 
INSERT INTO [NU_UserGuidelines] 
	 ([StartCode],
	[EndCode],
	[MultipleOcc],
	[MessageText],
	[ErrorLevel],
	[ValidFrom],
	[ValidTo],
	[ReplaceRuleID])  -- This field doesn't apply for User Guidelines
VALUES 
	(@StartCode,
	@EndCode,
	@MultipleOcc,
	@MessageText,
	@ErrorLevel,
	@ValidFrom,
	@ValidTo,
	NULL)

SELECT @MaxtGuidelineID = MAX(GuidelineId) from NU_UserGuidelines 

INSERT INTO [NU_UserGuidelineLink] 
	 ([IsInclude],
	[StartCode],
	[EndCode],
	[IsMandatory],
	[DiagTypeID])
VALUES 
	(@IsInclude,
	@RuleStartCode,
	@RuleEndCode,
	0,		-- This field doesn't apply for User Guidelines
	@DiagTypeID)

SELECT @MaxGuidelineLinkID = MAX(GuidelineLinkID) from NU_UserGuidelineLink

INSERT INTO [NU_UserGuidelineCodeLinkRel] 
	 ([GuidelineId],
	[GuidelineLinkId])
VALUES 
	(@MaxtGuidelineID,
	@MaxGuidelineLinkID)
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO












CREATE PROCEDURE [NU_LinkCode]
 @SearchString  as varchar(15),
 @SwitchFlag as int
 AS
if  @SwitchFlag = 2 
begin
SELECT dbo.NU_IntCodes.Codeid,dbo.NU_IntCodes.ChapterId,  dbo.NU_IntCodes.HeaderId,  dbo.NU_IntCodes.SubHeaderId,  
     	 DisplayCode,  UserDescription,  
    	 Dagger,  Asteriks,  dbo.NU_IntCodes.CodeHeader, 
	 dbo.NU_IntCodes.SubCodeHeader FROM  dbo.NU_IntCodes INNER JOIN 
         dbo.ICD_ProcFile10 ON dbo.NU_IntCodes.Code  = dbo.ICD_ProcFile10.Code   WHERE    [displaycode]  + ICD_ProcFile10.cihivalue   LIKE  @SearchString +'%'
 
 
end
else 
 if   @SwitchFlag = 1 
begin 
 
SELECT dbo.NU_Codes.Codeid, dbo.NU_Codes.ChapterId,  dbo.NU_Codes.HeaderId,  dbo.NU_Codes.SubHeaderId,  
  DisplayCode,  UserDescription, 
  Dagger,  Asteriks, dbo.NU_Codes.CodeHeader,  
  dbo.NU_Codes.SubCodeHeader  FROM NU_Codes INNER JOIN  
  dbo.ICD_DiagFile10 ON dbo.NU_Codes.Code = dbo.ICD_DiagFile10.Code   WHERE  [displaycode] + ICD_DiagFile10.cihivalue  LIKE @SearchString  +'%'
  	
 
end












GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO











CREATE                                              PROCEDURE 
[NU_LookUpAlpha_B]
@SearchString  as varchar(800),
@OptionalStmt as varchar(10)
AS
create table #T (
--AutoId int  IDENTITY (1, 1) NOT NULL ,
autoid int ,
HeaderDesc VARCHAR(255),
CodeLink VARCHAR(15),
HeaderId int,
SubHeaderId int,
)

Declare @TempString as varchar(1000)
Declare @FirstWord as varchar(100)
Declare @LeadWord as varchar(100)
Declare @LeadWord1 as varchar(100)
Declare @LeadWord2 as varchar(100)
Declare @LeadWord3 as varchar(100)
Declare @SQL as varchar(5000)
Declare @Index as int

IF @OptionalStmt = '10000' BEGIN
		set @TempString = @SearchString
		set nocount on
		set @LeadWord = ''
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @SearchString = replace(@SearchString,@FirstWord,'')
		if      @FirstWord  <> '' begin
		set @FirstWord = replace(@FirstWord, '  ', ' ')
		set @FirstWord = replace(@FirstWord, ' ', '%'' and [HeaderSearch]   like 
''%')

			set @FirstWord = '[HeaderSearch]    like ''%' + @FirstWord + '%'''
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid, HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaFr WHERE '
			+ @FirstWord + ' order by autoid'
			exec( @SQL)

		end

		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord1 = @FirstWord
		if      @LeadWord1 <> '' begin
		set @LeadWord1 = replace(@LeadWord1, '  ', ' ')
		set @LeadWord1 = replace(@LeadWord1, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord1 = '[HeaderSearch]    like ''%' + @LeadWord1 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT  autoid, HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaFr WHERE '
			+ @LeadWord1 + ' order by autoid'
			exec( @SQL)

		end
		--print 'Second Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord2 = @FirstWord
		if  @LeadWord2 <> '' begin
		set @LeadWord2 = replace(@LeadWord2, '  ', ' ')
		set @LeadWord2 = replace(@LeadWord2, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord2 = '[HeaderSearch]    like ''%' + @LeadWord2 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid,HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaFr WHERE '
			+ @LeadWord2 + ' order by autoid'
			exec( @SQL)

		end
		--print 'Third Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end
		set @LeadWord3 = @FirstWord
		if  @LeadWord3 <> '' begin
		set @LeadWord3 = replace(@LeadWord3, '  ', ' ')
		set @LeadWord3 = replace(@LeadWord3, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord3 = '[HeaderSearch]    like ''%' + @LeadWord3 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid,HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaFr WHERE '
			+ @LeadWord3 + ' order by autoid'
			exec( @SQL)

		--print 'Fourth Word ' + @FirstWord
		end
		SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId  FROM #T order by 
autoid
END

IF @OptionalStmt = '0' BEGIN
		set @TempString = @SearchString
		set nocount on
		set @LeadWord = ''
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @SearchString = replace(@SearchString,@FirstWord,'')
		if      @FirstWord  <> '' begin
		set @FirstWord = replace(@FirstWord, '  ', ' ')
		set @FirstWord = replace(@FirstWord, ' ', '%'' and [HeaderSearch]   like ''%')

			set @FirstWord = '[HeaderSearch]    like ''%' + @FirstWord + '%'''
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid, HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM NU_Alpha  WHERE '
			+ @FirstWord + ' order by autoid'
			exec( @SQL)

		end

		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord1 = @FirstWord
		if      @LeadWord1 <> '' begin
		set @LeadWord1 = replace(@LeadWord1, '  ', ' ')
		set @LeadWord1 = replace(@LeadWord1, ' ', '%'' and [HeaderSearch]   like ''%')
		set @LeadWord1 = '[HeaderSearch]    like ''%' + @LeadWord1 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT  autoid, HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM NU_Alpha WHERE '
			+ @LeadWord1 + ' order by autoid'
			exec( @SQL)

		end
		--print 'Second Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord2 = @FirstWord
		if  @LeadWord2 <> '' begin
		set @LeadWord2 = replace(@LeadWord2, '  ', ' ')
		set @LeadWord2 = replace(@LeadWord2, ' ', '%'' and [HeaderSearch]   like ''%')
		set @LeadWord2 = '[HeaderSearch]    like ''%' + @LeadWord2 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid,HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM NU_Alpha WHERE '
			+ @LeadWord2 + ' order by autoid'
			exec( @SQL)

		end
		--print 'Third Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end
		set @LeadWord3 = @FirstWord
		if  @LeadWord3 <> '' begin
		set @LeadWord3 = replace(@LeadWord3, '  ', ' ')
		set @LeadWord3 = replace(@LeadWord3, ' ', '%'' and [HeaderSearch]   like ''%')
		set @LeadWord3 = '[HeaderSearch]    like ''%' + @LeadWord3 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid,HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM NU_AlphaFr WHERE '
			+ @LeadWord3 + ' order by autoid'
			exec( @SQL)

		--print 'Fourth Word ' + @FirstWord
		end
		SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId  FROM #T order by 
autoid
END

-- 		SELECT  HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId   FROM #T
-- 		GROUP BY  HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId
-- 		ORDER BY min(autoid)















GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO


























CREATE                                                   PROCEDURE 
[NU_LookUpAlpha_C]
@SearchString  as varchar(800),
@OptionalStmt as varchar(10)
AS

create table #T (
--AutoId int  IDENTITY (1, 1) NOT NULL ,
autoid int ,
HeaderDesc VARCHAR(255),
CodeLink VARCHAR(15),
HeaderId int,
SubHeaderId int,
)

Declare @TempString as varchar(1000)
Declare @FirstWord as varchar(100)
Declare @LeadWord as varchar(100)
Declare @LeadWord1 as varchar(100)
Declare @LeadWord2 as varchar(100)
Declare @LeadWord3 as varchar(100)
Declare @SQL as varchar(5000)
Declare @Index as int

IF @OptionalStmt = '10000' BEGIN
		set @TempString = @SearchString
		set nocount on
		set @LeadWord = ''
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @SearchString = replace(@SearchString,@FirstWord,'')
		if      @FirstWord  <> '' begin
		set @FirstWord = replace(@FirstWord, '  ', ' ')
		set @FirstWord = replace(@FirstWord, ' ', '%'' and [HeaderSearch]   like 
''%')

			set @FirstWord = '[HeaderSearch]    like ''%' + @FirstWord + '%'''
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaFr WHERE '
			+ @FirstWord + ' AND SUBHEADERID1 = 0 order by autoid'
			--print @SQL
			exec( @SQL)

		end

		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord1 = @FirstWord
		if      @LeadWord1 <> '' begin
		set @LeadWord1 = replace(@LeadWord1, '  ', ' ')
		set @LeadWord1 = replace(@LeadWord1, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord1 = '[HeaderSearch]    like ''%' + @LeadWord1 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaFr WHERE '
			+ @LeadWord1 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			--print @SQL
			exec( @SQL)

		end
		--print 'Second Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord2 = @FirstWord
		if  @LeadWord2 <> '' begin
		set @LeadWord2 = replace(@LeadWord2, '  ', ' ')
		set @LeadWord2 = replace(@LeadWord2, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord2 = '[HeaderSearch]    like ''%' + @LeadWord2 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaFr WHERE '
			+ @LeadWord2 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			 --print @SQL
			exec( @SQL)

		end
		--print 'Third Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end
		set @LeadWord3 = @FirstWord
		if  @LeadWord3 <> '' begin
		set @LeadWord3 = replace(@LeadWord3, '  ', ' ')
		set @LeadWord3 = replace(@LeadWord3, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord3 = '[HeaderSearch]    like ''%' + @LeadWord3 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaFr WHERE '
			+ @LeadWord3 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			--print @SQL
			exec( @SQL)

		--print 'Fourth Word ' + @FirstWord
		end
		SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId  FROM #T order by 
autoid
END

IF @OptionalStmt = '0' BEGIN
		set @TempString = @SearchString
		set nocount on
		set @LeadWord = ''
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @SearchString = replace(@SearchString,@FirstWord,'')
		if      @FirstWord  <> '' begin
		set @FirstWord = replace(@FirstWord, '  ', ' ')
		set @FirstWord = replace(@FirstWord, ' ', '%'' and [HeaderSearch]   like 
''%')

			set @FirstWord = '[HeaderSearch]    like ''%' + @FirstWord + '%'''
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM NU_Alpha WHERE '
			+ @FirstWord + ' AND SUBHEADERID1 = 0 order by autoid'
			--print @SQL
			exec( @SQL)

		end

		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord1 = @FirstWord
		if      @LeadWord1 <> '' begin
		set @LeadWord1 = replace(@LeadWord1, '  ', ' ')
		set @LeadWord1 = replace(@LeadWord1, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord1 = '[HeaderSearch]    like ''%' + @LeadWord1 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM NU_Alpha WHERE '
			+ @LeadWord1 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			--print @SQL
			exec( @SQL)

		end
		--print 'Second Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord2 = @FirstWord
		if  @LeadWord2 <> '' begin
		set @LeadWord2 = replace(@LeadWord2, '  ', ' ')
		set @LeadWord2 = replace(@LeadWord2, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord2 = '[HeaderSearch]    like ''%' + @LeadWord2 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_Alpha WHERE '
			+ @LeadWord2 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			 --print @SQL
			exec( @SQL)

		end
		--print 'Third Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end
		set @LeadWord3 = @FirstWord
		if  @LeadWord3 <> '' begin
		set @LeadWord3 = replace(@LeadWord3, '  ', ' ')
		set @LeadWord3 = replace(@LeadWord3, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord3 = '[HeaderSearch]    like ''%' + @LeadWord3 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_Alpha WHERE '
			+ @LeadWord3 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			--print @SQL
			exec( @SQL)

		--print 'Fourth Word ' + @FirstWord
		end
		SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId  FROM #T order by 
autoid
END





































GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO






















CREATE                                         PROCEDURE [NU_LookUpAlpha_F]
@SearchString  as varchar(800),
@OptionalStmt as varchar(10)
AS
DECLARE @SQL varchar(2000)
set nocount on
set @SearchString = replace(@SearchString, '  ', ' ')
set @SearchString = replace(@SearchString, ' ', '%'' and [HeaderSearch]   
like ''%')
set @SearchString = '[HeaderSearch]    like ''%' + @SearchString + '%'''
--print @SearchString
IF @OptionalStmt = '0' BEGIN

set @SQL =
'SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM NU_Alpha WHERE '
+ @SearchString + ' order by autoid'
--print @SQL
exec( @SQL)
END
IF @OptionalStmt = '10000' BEGIN


set @SQL =
'SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM NU_AlphaFr WHERE '
+ @SearchString + ' order by autoid'
--print @SQL
set nocount off
exec( @SQL)




END











GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO












CREATE                                               PROCEDURE 
[NU_LookUpAlphaECI_B]
@SearchString  as varchar(800),
@OptionalStmt as varchar(10)
AS
create table #T (
--AutoId int  IDENTITY (1, 1) NOT NULL ,
autoid int ,
HeaderDesc VARCHAR(255),
CodeLink VARCHAR(15),
HeaderId int,
SubHeaderId int,
)

Declare @TempString as varchar(1000)
Declare @FirstWord as varchar(100)
Declare @LeadWord as varchar(100)
Declare @LeadWord1 as varchar(100)
Declare @LeadWord2 as varchar(100)
Declare @LeadWord3 as varchar(100)
Declare @SQL as varchar(5000)
Declare @Index as int

IF @OptionalStmt = '10000' BEGIN
		set @TempString = @SearchString
		set nocount on
		set @LeadWord = ''
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @SearchString = replace(@SearchString,@FirstWord,'')
		if      @FirstWord  <> '' begin
		set @FirstWord = replace(@FirstWord, '  ', ' ')
		set @FirstWord = replace(@FirstWord, ' ', '%'' and [HeaderSearch]   like 
''%')

			set @FirstWord = '[HeaderSearch]    like ''%' + @FirstWord + '%'''
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid, HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaECIFr WHERE '
			+ @FirstWord + ' order by autoid'
			exec( @SQL)

		end

		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord1 = @FirstWord
		if      @LeadWord1 <> '' begin
		set @LeadWord1 = replace(@LeadWord1, '  ', ' ')
		set @LeadWord1 = replace(@LeadWord1, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord1 = '[HeaderSearch]    like ''%' + @LeadWord1 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT  autoid, HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaECIFr WHERE '
			+ @LeadWord1 + ' order by autoid'
			exec( @SQL)

		end
		--print 'Second Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord2 = @FirstWord
		if  @LeadWord2 <> '' begin
		set @LeadWord2 = replace(@LeadWord2, '  ', ' ')
		set @LeadWord2 = replace(@LeadWord2, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord2 = '[HeaderSearch]    like ''%' + @LeadWord2 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid,HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaECIFr WHERE '
			+ @LeadWord2 + ' order by autoid'
			exec( @SQL)

		end
		--print 'Third Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end
		set @LeadWord3 = @FirstWord
		if  @LeadWord3 <> '' begin
		set @LeadWord3 = replace(@LeadWord3, '  ', ' ')
		set @LeadWord3 = replace(@LeadWord3, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord3 = '[HeaderSearch]    like ''%' + @LeadWord3 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid,HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaECIFr WHERE '
			+ @LeadWord3 + ' order by autoid'
			exec( @SQL)

		--print 'Fourth Word ' + @FirstWord
		end
		SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId  FROM #T order by 
autoid
END
IF @OptionalStmt = '0' BEGIN
		set @TempString = @SearchString
		set nocount on
		set @LeadWord = ''
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @SearchString = replace(@SearchString,@FirstWord,'')
		if      @FirstWord  <> '' begin
		set @FirstWord = replace(@FirstWord, '  ', ' ')
		set @FirstWord = replace(@FirstWord, ' ', '%'' and [HeaderSearch]   like 
''%')

			set @FirstWord = '[HeaderSearch]    like ''%' + @FirstWord + '%'''
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid, HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaECI WHERE '
			+ @FirstWord + ' order by autoid'
			exec( @SQL)

		end

		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord1 = @FirstWord
		if      @LeadWord1 <> '' begin
		set @LeadWord1 = replace(@LeadWord1, '  ', ' ')
		set @LeadWord1 = replace(@LeadWord1, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord1 = '[HeaderSearch]    like ''%' + @LeadWord1 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT  autoid, HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaECI WHERE '
			+ @LeadWord1 + ' order by autoid'
			exec( @SQL)

		end
		--print 'Second Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord2 = @FirstWord
		if  @LeadWord2 <> '' begin
		set @LeadWord2 = replace(@LeadWord2, '  ', ' ')
		set @LeadWord2 = replace(@LeadWord2, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord2 = '[HeaderSearch]    like ''%' + @LeadWord2 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid,HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaECI WHERE '
			+ @LeadWord2 + ' order by autoid'
			exec( @SQL)

		end
		--print 'Third Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end
		set @LeadWord3 = @FirstWord
		if  @LeadWord3 <> '' begin
		set @LeadWord3 = replace(@LeadWord3, '  ', ' ')
		set @LeadWord3 = replace(@LeadWord3, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord3 = '[HeaderSearch]    like ''%' + @LeadWord3 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid,HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaECI WHERE '
			+ @LeadWord3 + ' order by autoid'
			exec( @SQL)

		--print 'Fourth Word ' + @FirstWord
		end
		SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId  FROM #T order by 
autoid
END


-- 		SELECT  HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId   FROM #T
-- 		GROUP BY  HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId
-- 		ORDER BY min(autoid)
















GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO



























CREATE                                                    PROCEDURE 
[NU_LookUpAlphaECI_C]
@SearchString  as varchar(800),
@OptionalStmt as varchar(10)
AS

create table #T (
--AutoId int  IDENTITY (1, 1) NOT NULL ,
autoid int ,
HeaderDesc VARCHAR(255),
CodeLink VARCHAR(15),
HeaderId int,
SubHeaderId int,
)

Declare @TempString as varchar(1000)
Declare @FirstWord as varchar(100)
Declare @LeadWord as varchar(100)
Declare @LeadWord1 as varchar(100)
Declare @LeadWord2 as varchar(100)
Declare @LeadWord3 as varchar(100)
Declare @SQL as varchar(5000)
Declare @Index as int

IF @OptionalStmt = '10000' BEGIN
		set @TempString = @SearchString
		set nocount on
		set @LeadWord = ''
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @SearchString = replace(@SearchString,@FirstWord,'')
		if      @FirstWord  <> '' begin
		set @FirstWord = replace(@FirstWord, '  ', ' ')
		set @FirstWord = replace(@FirstWord, ' ', '%'' and [HeaderSearch]   like 
''%')

			set @FirstWord = '[HeaderSearch]    like ''%' + @FirstWord + '%'''
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaECIFr WHERE '
			+ @FirstWord + ' AND SUBHEADERID1 = 0 order by autoid'
			--print @SQL
			exec( @SQL)

		end

		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord1 = @FirstWord
		if      @LeadWord1 <> '' begin
		set @LeadWord1 = replace(@LeadWord1, '  ', ' ')
		set @LeadWord1 = replace(@LeadWord1, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord1 = '[HeaderSearch]    like ''%' + @LeadWord1 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaECIFr WHERE '
			+ @LeadWord1 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			--print @SQL
			exec( @SQL)

		end
		--print 'Second Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord2 = @FirstWord
		if  @LeadWord2 <> '' begin
		set @LeadWord2 = replace(@LeadWord2, '  ', ' ')
		set @LeadWord2 = replace(@LeadWord2, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord2 = '[HeaderSearch]    like ''%' + @LeadWord2 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaECIFr WHERE '
			+ @LeadWord2 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			 --print @SQL
			exec( @SQL)

		end
		--print 'Third Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end
		set @LeadWord3 = @FirstWord
		if  @LeadWord3 <> '' begin
		set @LeadWord3 = replace(@LeadWord3, '  ', ' ')
		set @LeadWord3 = replace(@LeadWord3, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord3 = '[HeaderSearch]    like ''%' + @LeadWord3 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaECIFr WHERE '
			+ @LeadWord3 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			--print @SQL
			exec( @SQL)

		--print 'Fourth Word ' + @FirstWord
		end
		SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId  FROM #T order by 
autoid
END





IF @OptionalStmt = '0' BEGIN
		set @TempString = @SearchString
		set nocount on
		set @LeadWord = ''
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @SearchString = replace(@SearchString,@FirstWord,'')
		if      @FirstWord  <> '' begin
		set @FirstWord = replace(@FirstWord, '  ', ' ')
		set @FirstWord = replace(@FirstWord, ' ', '%'' and [HeaderSearch]   like 
''%')

			set @FirstWord = '[HeaderSearch]    like ''%' + @FirstWord + '%'''
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaECI WHERE '
			+ @FirstWord + ' AND SUBHEADERID1 = 0 order by autoid'
			--print @SQL
			exec( @SQL)

		end

		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord1 = @FirstWord
		if      @LeadWord1 <> '' begin
		set @LeadWord1 = replace(@LeadWord1, '  ', ' ')
		set @LeadWord1 = replace(@LeadWord1, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord1 = '[HeaderSearch]    like ''%' + @LeadWord1 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaECI WHERE '
			+ @LeadWord1 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			--print @SQL
			exec( @SQL)

		end
		--print 'Second Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord2 = @FirstWord
		if  @LeadWord2 <> '' begin
		set @LeadWord2 = replace(@LeadWord2, '  ', ' ')
		set @LeadWord2 = replace(@LeadWord2, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord2 = '[HeaderSearch]    like ''%' + @LeadWord2 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaECI WHERE '
			+ @LeadWord2 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			 --print @SQL
			exec( @SQL)

		end
		--print 'Third Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end
		set @LeadWord3 = @FirstWord
		if  @LeadWord3 <> '' begin
		set @LeadWord3 = replace(@LeadWord3, '  ', ' ')
		set @LeadWord3 = replace(@LeadWord3, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord3 = '[HeaderSearch]    like ''%' + @LeadWord3 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaECI WHERE '
			+ @LeadWord3 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			--print @SQL
			exec( @SQL)

		--print 'Fourth Word ' + @FirstWord
		end
		SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId  FROM #T order by 
autoid
END





































GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO























CREATE                                          PROCEDURE 
[NU_LookUpAlphaECI_F]
@SearchString  as varchar(800),
@OptionalStmt as varchar(10)
AS
DECLARE @SQL varchar(2000)
set nocount on
set @SearchString = replace(@SearchString, '  ', ' ')
set @SearchString = replace(@SearchString, ' ', '%'' and [HeaderSearch]   
like ''%')
set @SearchString = '[HeaderSearch]    like ''%' + @SearchString + '%'''
--print @SearchString
IF @OptionalStmt = '0' BEGIN

set @SQL =
'SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM NU_AlphaECI WHERE 
'
+ @SearchString + ' order by autoid'
--print @SQL
exec( @SQL)
END
IF @OptionalStmt = '10000' BEGIN


set @SQL =
'SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM NU_AlphaECIFr 
WHERE '
+ @SearchString + ' order by autoid'
--print @SQL
set nocount off
exec( @SQL)




END












GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE                                             PROCEDURE 
[NU_LookUpAlphaInt_B]
@SearchString  as varchar(800),
@OptionalStmt as varchar(10)
AS
create table #T (
--AutoId int  IDENTITY (1, 1) NOT NULL ,
autoid int ,
HeaderDesc VARCHAR(255),
CodeLink VARCHAR(15),
HeaderId int,
SubHeaderId int,
)

Declare @TempString as varchar(1000)
Declare @FirstWord as varchar(100)
Declare @LeadWord as varchar(100)
Declare @LeadWord1 as varchar(100)
Declare @LeadWord2 as varchar(100)
Declare @LeadWord3 as varchar(100)
Declare @SQL as varchar(5000)
Declare @Index as int

IF @OptionalStmt = '10000' BEGIN
		set @TempString = @SearchString
		set nocount on
		set @LeadWord = ''
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @SearchString = replace(@SearchString,@FirstWord,'')
		if      @FirstWord  <> '' begin
		set @FirstWord = replace(@FirstWord, '  ', ' ')
		set @FirstWord = replace(@FirstWord, ' ', '%'' and [HeaderSearch]   like 
''%')

			set @FirstWord = '[HeaderSearch]    like ''%' + @FirstWord + '%'''
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid, HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaIntFr WHERE '
			+ @FirstWord + ' order by autoid'
			exec( @SQL)

		end

		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord1 = @FirstWord
		if      @LeadWord1 <> '' begin
		set @LeadWord1 = replace(@LeadWord1, '  ', ' ')
		set @LeadWord1 = replace(@LeadWord1, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord1 = '[HeaderSearch]    like ''%' + @LeadWord1 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT  autoid, HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaIntFr WHERE '
			+ @LeadWord1 + ' order by autoid'
			exec( @SQL)

		end
		--print 'Second Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord2 = @FirstWord
		if  @LeadWord2 <> '' begin
		set @LeadWord2 = replace(@LeadWord2, '  ', ' ')
		set @LeadWord2 = replace(@LeadWord2, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord2 = '[HeaderSearch]    like ''%' + @LeadWord2 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid,HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaIntFr WHERE '
			+ @LeadWord2 + ' order by autoid'
			exec( @SQL)

		end
		--print 'Third Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end
		set @LeadWord3 = @FirstWord
		if  @LeadWord3 <> '' begin
		set @LeadWord3 = replace(@LeadWord3, '  ', ' ')
		set @LeadWord3 = replace(@LeadWord3, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord3 = '[HeaderSearch]    like ''%' + @LeadWord3 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid,HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaIntFr WHERE '
			+ @LeadWord3 + ' order by autoid'
			exec( @SQL)

		--print 'Fourth Word ' + @FirstWord
		end
		SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId  FROM #T order by 
autoid
END

IF @OptionalStmt = '0' BEGIN
		set @TempString = @SearchString
		set nocount on
		set @LeadWord = ''
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @SearchString = replace(@SearchString,@FirstWord,'')
		if      @FirstWord  <> '' begin
		set @FirstWord = replace(@FirstWord, '  ', ' ')
		set @FirstWord = replace(@FirstWord, ' ', '%'' and [HeaderSearch]   like 
''%')

			set @FirstWord = '[HeaderSearch]    like ''%' + @FirstWord + '%'''
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid, HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaInt WHERE '
			+ @FirstWord + ' order by autoid'
			exec( @SQL)

		end

		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord1 = @FirstWord
		if      @LeadWord1 <> '' begin
		set @LeadWord1 = replace(@LeadWord1, '  ', ' ')
		set @LeadWord1 = replace(@LeadWord1, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord1 = '[HeaderSearch]    like ''%' + @LeadWord1 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT  autoid, HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaInt WHERE '
			+ @LeadWord1 + ' order by autoid'
			exec( @SQL)

		end
		--print 'Second Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord2 = @FirstWord
		if  @LeadWord2 <> '' begin
		set @LeadWord2 = replace(@LeadWord2, '  ', ' ')
		set @LeadWord2 = replace(@LeadWord2, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord2 = '[HeaderSearch]    like ''%' + @LeadWord2 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid,HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaInt WHERE '
			+ @LeadWord2 + ' order by autoid'
			exec( @SQL)

		end
		--print 'Third Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end
		set @LeadWord3 = @FirstWord
		if  @LeadWord3 <> '' begin
		set @LeadWord3 = replace(@LeadWord3, '  ', ' ')
		set @LeadWord3 = replace(@LeadWord3, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord3 = '[HeaderSearch]    like ''%' + @LeadWord3 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid,HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaInt WHERE '
			+ @LeadWord3 + ' order by autoid'
			exec( @SQL)

		--print 'Fourth Word ' + @FirstWord
		end
		SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId  FROM #T order by 
autoid
END

-- 		SELECT  HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId   FROM #T
-- 		GROUP BY  HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId
-- 		ORDER BY min(autoid)




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO







































CREATE                                               PROCEDURE 
[NU_LookUpAlphaInt_C]
@SearchString  as varchar(800),
@OptionalStmt as varchar(10)
AS

create table #T (
--AutoId int  IDENTITY (1, 1) NOT NULL ,
autoid int ,
HeaderDesc VARCHAR(255),
CodeLink VARCHAR(15),
HeaderId int,
SubHeaderId int,
)

Declare @TempString as varchar(1000)
Declare @FirstWord as varchar(100)
Declare @LeadWord as varchar(100)
Declare @LeadWord1 as varchar(100)
Declare @LeadWord2 as varchar(100)
Declare @LeadWord3 as varchar(100)
Declare @SQL as varchar(5000)
Declare @Index as int

IF @OptionalStmt = '10000' BEGIN
		set @TempString = @SearchString
		set nocount on
		set @LeadWord = ''
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @SearchString = replace(@SearchString,@FirstWord,'')
		if      @FirstWord  <> '' begin
		set @FirstWord = replace(@FirstWord, '  ', ' ')
		set @FirstWord = replace(@FirstWord, ' ', '%'' and [HeaderSearch]   like 
''%')

			set @FirstWord = '[HeaderSearch]    like ''%' + @FirstWord + '%'''
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaIntFr WHERE '
			+ @FirstWord + ' AND SUBHEADERID1 = 0 order by autoid'
			--print @SQL
			exec( @SQL)
			 
		end
		 
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord1 = @FirstWord
		if      @LeadWord1 <> '' begin
		set @LeadWord1 = replace(@LeadWord1, '  ', ' ')
		set @LeadWord1 = replace(@LeadWord1, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord1 = '[HeaderSearch]    like ''%' + @LeadWord1 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaIntFr WHERE '
			+ @LeadWord1 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			--print @SQL
			exec( @SQL)
 
		end
		--print 'Second Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord2 = @FirstWord
		if  @LeadWord2 <> '' begin
		set @LeadWord2 = replace(@LeadWord2, '  ', ' ')
		set @LeadWord2 = replace(@LeadWord2, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord2 = '[HeaderSearch]    like ''%' + @LeadWord2 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaIntFr WHERE '
			+ @LeadWord2 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			 --print @SQL
			exec( @SQL)
 
		end
		--print 'Third Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end
		set @LeadWord3 = @FirstWord
		if  @LeadWord3 <> '' begin
		set @LeadWord3 = replace(@LeadWord3, '  ', ' ')
		set @LeadWord3 = replace(@LeadWord3, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord3 = '[HeaderSearch]    like ''%' + @LeadWord3 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaIntFr WHERE '
			+ @LeadWord3 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			--print @SQL
			exec( @SQL)
 
		--print 'Fourth Word ' + @FirstWord
		end
		SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId  FROM #T order by 
autoid
END



IF @OptionalStmt = '0' BEGIN
		set @TempString = @SearchString
		set nocount on
		set @LeadWord = ''
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @SearchString = replace(@SearchString,@FirstWord,'')
		if      @FirstWord  <> '' begin
		set @FirstWord = replace(@FirstWord, '  ', ' ')
		set @FirstWord = replace(@FirstWord, ' ', '%'' and [HeaderSearch]   like 
''%')

			set @FirstWord = '[HeaderSearch]    like ''%' + @FirstWord + '%'''
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaInt WHERE '
			+ @FirstWord + ' AND SUBHEADERID1 = 0 order by autoid'
			--print @SQL
			exec( @SQL)
			 
		end
		 
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord1 = @FirstWord
		if      @LeadWord1 <> '' begin
		set @LeadWord1 = replace(@LeadWord1, '  ', ' ')
		set @LeadWord1 = replace(@LeadWord1, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord1 = '[HeaderSearch]    like ''%' + @LeadWord1 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaInt WHERE '
			+ @LeadWord1 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			--print @SQL
			exec( @SQL)
 
		end
		--print 'Second Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord2 = @FirstWord
		if  @LeadWord2 <> '' begin
		set @LeadWord2 = replace(@LeadWord2, '  ', ' ')
		set @LeadWord2 = replace(@LeadWord2, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord2 = '[HeaderSearch]    like ''%' + @LeadWord2 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaInt WHERE '
			+ @LeadWord2 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			 --print @SQL
			exec( @SQL)
 
		end
		--print 'Third Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end
		set @LeadWord3 = @FirstWord
		if  @LeadWord3 <> '' begin
		set @LeadWord3 = replace(@LeadWord3, '  ', ' ')
		set @LeadWord3 = replace(@LeadWord3, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord3 = '[HeaderSearch]    like ''%' + @LeadWord3 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_AlphaInt WHERE '
			+ @LeadWord3 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			--print @SQL
			exec( @SQL)
 
		--print 'Fourth Word ' + @FirstWord
		end
		SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId  FROM #T order by 
autoid
END








































GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO






















CREATE                                           PROCEDURE 
[NU_LookUpAlphaInt_F]
@SearchString  as varchar(800),
@OptionalStmt as varchar(10)
AS
DECLARE @SQL varchar(2000)
set nocount on
set @SearchString = replace(@SearchString, '  ', ' ')
set @SearchString = replace(@SearchString, ' ', '%'' and [HeaderSearch]   
like ''%')
set @SearchString = '[HeaderSearch]    like ''%' + @SearchString + '%'''
--print @SearchString
IF @OptionalStmt = '0' BEGIN

set @SQL =
'SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM NU_ALPHAINT WHERE 
'
+ @SearchString + ' order by autoid'
--print @SQL
exec( @SQL)
END
IF @OptionalStmt = '10000' BEGIN


set @SQL =
'SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM NU_ALPHAINTFR 
WHERE '
+ @SearchString + ' order by autoid'
--print @SQL
set nocount off
exec( @SQL)




END











GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [NU_LookUpCDCode]
		@SearchString  as varchar(2000),    --PR - 03745
		@SwitchFlag as int,
		@Gender as varchar(1),
		@Age as int,
		@VisitDate as datetime,
		@OptionalStmt as varchar(10),
		@UserId as int = 1  -- BV: PR-02974 USERID DEFAULT 
		 
 AS	
Declare @SQL as VarChar(8000)
Declare @SQL1 as VarChar(8000)
Declare @EntryValue as VarChar(50)
Declare @SearchValue as VarChar(50)
Declare @SearchString1 as varchar(8000) 
Declare @SearchString2 as varchar(8000) 
Declare @SearchString3 as varchar(8000) --EBV PR-01850
Declare @TempString as varchar(8000) 
declare @GenderS as varchar(50) -- Gender 'O' issue

---- 	EN-00411 add nuc.Flagged for intervention english 

--Declare @DashPosition as int
--NEW STUFF FOR FEB 19 
set nocount on 
--set @DashPosition =  0
--TEST IF THERE IS A "-" int the string if so use a between statment
--set @DashPosition = charindex('-', @SearchString ,1)  
--if @DashPosition <> 0
 
--begin 
	--EXECUTE BETWEEN STATMENT
	--print  @SearchString  
	--exec  NU_BetweenCode @SearchString, 1
	--return 0 
--end 

set @GenderS = '(''A'', ''N'', ''G'')' -- Gender 'O' issue
if @Gender = 'F' set @GenderS = '(''A'', ''F'', ''G'')' -- Gender 'O' issue
if @Gender = 'M' set @GenderS = '(''A'', ''M'', ''N'')' -- Gender 'O' issue
if @Gender = 'O' set @GenderS = '(''A'', ''G'', ''N'')' -- Gender 'O' issue

	
IF @OptionalStmt = '0' BEGIN
		
		set @TempString =   replace(@SearchString , ' ',''',''') 
		set @TempString =    '''' + @TempString  +''''
		set @SearchString2 = ''
		--Have to search multiple entries ie two chest's have to do search 
		--On both chest pector 
		--And chest stetho
			
			
			set @SQL = N'' + 'declare  Cur_XReference cursor   fast_forward for ' +
		 	'select EntryValue, SearchValue ' + 
			'from NU_CrossReference ' + 
			'where EntryValue in (  ' +  @TempString  + '   ) '  +
			 
				'Open Cur_XReference ' --Create Dynamic Cursur 
				exec(@SQL)
				fetch next from Cur_XReference
					into @EntryValue, @SearchValue
			while @@fetch_status = 0
			begin
				if @EntryValue  <> '' 
				begin
					--If the word is in the list
					set @SearchString1 =  replace(@SearchString, @EntryValue, @SearchValue)  
		-- 			If isnull(@Searchstring1,'')  <>''
		-- 			begin 
		-- 				set @SearchString2 = 	isnull(@SearchString2,'') + ' or isnull ([UserDescription],'''') + '' '' +  isnull ([cihivalue],'''') + '' '' + isnull ([displaycode],'''')   like ''%' + @SearchString1 + '%'''
		-- 				--This is in case there are many entries for one cross refference  
		-- 			end
				end
			fetch next from Cur_XReference
			into @EntryValue, @SearchValue
			end
			
			Close Cur_XReference
		deallocate Cur_XReference
		 
		 
		--"""""""""""""""""""""""""""""""""""""""""""
		-- 
		-- 	set @SearchString = replace(@SearchString, '  ', ' ')
		-- 	set @SearchString = replace(@SearchString, ' ', '%'' and [UserDescription]  + '' '' + [cihivalue] + '' '' + [displaycode]   + '' '' +  isnull ([ICDNotes],'''') like ''%')	
		-- 	set @SearchString = '[UserDescription] + '' '' +  [cihivalue]   + '' '' + [displaycode] + '' '' +  isnull ([ICDNotes],'''')  like ''%' + @SearchString + '%'''
		-- 	
		-- 	--the next lines are for searching user notes they have to be ored with original because and will
		-- 	--return no values
		-- 	 
		-- 	--ICDNotes
		-- 	If isnull(@Searchstring1, '') <>''
		-- 	Begin
		-- 		set @SearchString1 = replace(@SearchString1, '  ', ' ')
		-- 		set @SearchString1 = replace(@SearchString1, ' ', '%'' and isnull ([UserDescription],'''')   + '' '' + isnull ([cihivalue],'''') + '' '' + isnull ([displaycode],'''')  like ''%')	
		-- 		set @SearchString1 = ' or isnull ([UserDescription],'''')  + '' '' +  isnull ([cihivalue],'''') + '' '' + isnull ([displaycode],'''')   like ''%' + @SearchString1 + '%'''
		-- 	End
			-- EBV PR-01850


			set @SearchString3 =  @SearchString   
	
			set @SearchString3 = replace(@SearchString3, '  ', ' ')
			set @SearchString3 = replace(@SearchString3,  ' ', '%'' and isnull (PrvNote,'''') like ''%')	
	 		set @SearchString3 = ' isnull (PrvNote,'''') like ''%' + @SearchString3 + '%'''

			-- ENDS EBV PR-01850
		 
			set @SearchString = replace(@SearchString, '  ', ' ')
			set @SearchString = replace(@SearchString, ' ', '%'' and [CodeDesc]  + '' '' + nuc.[CodeNum] + '' '' +   CIHIValue + '' '' + isnull (ICDNotes,'''') like ''%')	
			set @SearchString = '[CodeDesc]  + '' '' + nuc.[CodeNum] + '' '' +  isnull ( CIHIValue,'''') + '' '' +  isnull (ICDNotes,'''')  like ''%' + @SearchString + '%'''
			
			--the next lines are for searching user notes they have to be ored with original because and will
			--return no values
			 
			--ICDNotes
			If isnull(@Searchstring1, '') <>''
			Begin
				set @SearchString1 = replace(@SearchString1, '  ', ' ')
				set @SearchString1 = replace(@SearchString1, ' ', '%'' and isnull ([CodeDesc],'''')   + '' '' + isnull (nuc.[CodeNum],'''')  + '' '' +  CIHIValue like ''%')	
				set @SearchString1 = ' or isnull ([CodeDesc],'''')  + '' '' +  isnull (nuc.[CodeNum],'''') + '' '' +  isnull ( CIHIValue,'''')   like ''%' + @SearchString1 + '%'''
			End

		 
		if  @SwitchFlag = 2 
			begin 

		set @SQL1 = N'' + 
		'SELECT DISTINCT 
		nuc.Codeid, 
		nuc.ChapterId,   
		nuc.HeaderId, 
		nuc.SubHeaderId, 
		nuc.CodeNum AS [Display Code],  nuc.CodeDesc AS [Description], 
		Dagger,  
		Asteriks, 
		nuc.CodeHeader,  
		nuc.SubCodeHeader ,  
		nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
		nuc.AgeHigh , 
		nuc.DiagnosisGender,
		nuc.Flagged 
		FROM   dbo.NU_IntCodes nuc ' +
		--'LEFT OUTER JOIN dbo.ICD_ProcFile10 ICD ON nuc.Code = ICD.Code ' +
		-- EBV PR-01850
		' FULL OUTER JOIN dbo.NU_PrvNotes ON nuc.Code = dbo.NU_PrvNotes.Code 
		 WHERE   '  
		set @SQL  = @SQL1 + @SearchString + isnull(@SearchString1, '') +
		' AND( nuc.AgeLow <= ' + cast(@Age as varchar)  + 
		' AND nuc.AgeHigh  >= ' + cast(@Age as varchar) + ' OR  nuc.agelow = 150 ) ' +
		' AND (nuc.DiagnosisGender  in ' + @GenderS +  
		')  AND nuc.ValidFrom <= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
		' AND nuc.ValidTo >= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
		--- EBV PR-01850
		' OR ( ' + @SearchString3 + ' AND UserId = ' + cast(@UserId as varchar) + '  )  AND nuc.CODENUM <> ''''  
		ORDER BY nuc.CodeNum  ASC '
		-- ' OR ' +  @SearchString1 +
		-- LINE BELOW WAS CHANGED NOVEMBER 15 BY SIMON   TO NOT LOOK "AND FOR NU_IntCodes.CodeId <> 0"
		-- 'AND NU_IntCodes.CodeId <> 0 ORDER BY DisplayCode  ASC ' ----they have chosen the cross reference function
			
		end
		else 
		 
		if   @SwitchFlag = 1 
			begin
		-- ED-01642 ADDED Canadian col
		set @SQL1 = N'' + 
		'SELECT  DISTINCT 
		nuc.Codeid, 
		nuc.ChapterId,   
		nuc.HeaderId, 
		nuc.SubHeaderId, 
		nuc.CodeNum AS [Display Code],  nuc.CodeDesc AS [Description], 
		Dagger,  
		Asteriks, 
		nuc.CodeHeader,  
		nuc.SubCodeHeader ,  
		nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
		nuc.AgeHigh ,
		nuc.DiagnosisGender,
		nuc.Canadian
		FROM  dbo.NU_Codes nuc ' + 
		--LEFT OUTER JOIN dbo.ICD_DiagFile10 ICD ON nuc.Code = ICD.Code ' +
		' FULL OUTER JOIN dbo.NU_PrvNotes ON nuc.Code = dbo.NU_PrvNotes.Code 
		 WHERE   '  
		 set @SQL  = @SQL1 + @SearchString + isnull(@SearchString1, '')  +
		' AND( nuc.AgeLow <= ' + cast(@Age as varchar)  + 
		' AND nuc.AgeHigh  >= ' + cast(@Age as varchar) + ' OR  nuc.agelow = 150 ) ' +
		' AND (nuc.DiagnosisGender  in ' + @GenderS +  
		')  AND nuc.ValidFrom <= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
		' AND nuc.ValidTo >= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
		--EBV PR-01850
		' OR ( ' + @SearchString3 + ' AND UserId = ' + cast(@UserId as varchar) + '  )  AND nuc.CODENUM <> ''''  
		ORDER BY nuc.CodeNum  ASC ' --' OR ' +  @SearchString1 +
		end
END

IF @OptionalStmt = '10000' BEGIN
		
		set @TempString =   replace(@SearchString , ' ',''',''') 
		set @TempString =    '''' + @TempString  +''''
		set @SearchString2 = ''
		--Have to search multiple entries ie two chest's have to do search 
		--On both chest pector 
		--And chest stetho
			
			
			set @SQL = N'' + 'declare  Cur_XReference cursor   fast_forward for ' +
		 	'select EntryValue, SearchValue ' + 
			'from NU_CrossReferenceFr ' + 
			'where EntryValue in (  ' +  @TempString  + '   ) '  +
			 
				'Open Cur_XReference ' --Create Dynamic Cursur 
				exec(@SQL)
				fetch next from Cur_XReference
					into @EntryValue, @SearchValue
			while @@fetch_status = 0
			begin
				if @EntryValue  <> '' 
				begin
					--If the word is in the list
					set @SearchString1 =  replace(@SearchString, @EntryValue, @SearchValue)  
		-- 			If isnull(@Searchstring1,'')  <>''
		-- 			begin 
		-- 				set @SearchString2 = 	isnull(@SearchString2,'') + ' or isnull ([UserDescription],'''') + '' '' +  isnull ([cihivalue],'''') + '' '' + isnull ([displaycode],'''')   like ''%' + @SearchString1 + '%'''
		-- 				--This is in case there are many entries for one cross refference  
		-- 			end
				end
			fetch next from Cur_XReference
			into @EntryValue, @SearchValue
			end
			
			Close Cur_XReference
		deallocate Cur_XReference
		 
		 
		--"""""""""""""""""""""""""""""""""""""""""""
		-- 
		-- 	set @SearchString = replace(@SearchString, '  ', ' ')
		-- 	set @SearchString = replace(@SearchString, ' ', '%'' and [UserDescription]  + '' '' + [cihivalue] + '' '' + [displaycode]   + '' '' +  isnull ([ICDNotes],'''') like ''%')	
		-- 	set @SearchString = '[UserDescription] + '' '' +  [cihivalue]   + '' '' + [displaycode] + '' '' +  isnull ([ICDNotes],'''')  like ''%' + @SearchString + '%'''
		-- 	
		-- 	--the next lines are for searching user notes they have to be ored with original because and will
		-- 	--return no values
		-- 	 
		-- 	--ICDNotes
		-- 	If isnull(@Searchstring1, '') <>''
		-- 	Begin
		-- 		set @SearchString1 = replace(@SearchString1, '  ', ' ')
		-- 		set @SearchString1 = replace(@SearchString1, ' ', '%'' and isnull ([UserDescription],'''')   + '' '' + isnull ([cihivalue],'''') + '' '' + isnull ([displaycode],'''')  like ''%')	
		-- 		set @SearchString1 = ' or isnull ([UserDescription],'''')  + '' '' +  isnull ([cihivalue],'''') + '' '' + isnull ([displaycode],'''')   like ''%' + @SearchString1 + '%'''
		-- 	End
			--- EBV PR-01850		 
			set @SearchString3 =  @SearchString   

			set @SearchString3 = replace(@SearchString3, '  ', ' ')
			set @SearchString3 = replace(@SearchString3,  ' ', '%'' and isnull (PrvNote,'''') like ''%')	
	 		set @SearchString3 = ' isnull (PrvNote,'''') like ''%' + @SearchString3 + '%'''
			--- ENDS EBV PR-01850
	
			set @SearchString = replace(@SearchString, '  ', ' ')
			set @SearchString = replace(@SearchString, ' ', '%'' and [HEADERSEARCH]  + '' '' + nuc.[CodeNum] + '' '' +   CIHIValue + '' '' + isnull (ICDNotes,'''') like ''%')	
			set @SearchString = '[HEADERSEARCH]  + '' '' + nuc.[CodeNum] + '' '' +  isnull ( CIHIValue,'''') + '' '' +  isnull (ICDNotes,'''')  like ''%' + @SearchString + '%'''
			
			--the next lines are for searching user notes they have to be ored with original because and will
			--return no values
			 
			--ICDNotes
			If isnull(@Searchstring1, '') <>''
			Begin
				set @SearchString1 = replace(@SearchString1, '  ', ' ')
				set @SearchString1 = replace(@SearchString1, ' ', '%'' and isnull ([HEADERSEARCH],'''')   + '' '' + isnull (nuc.[CodeNum],'''')  + '' '' +  CIHIValue like ''%')	
				set @SearchString1 = ' or isnull ([HEADERSEARCH],'''')  + '' '' +  isnull (nuc.[CodeNum],'''') + '' '' +  isnull ( CIHIValue,'''')   like ''%' + @SearchString1 + '%'''
			End
		 
		if  @SwitchFlag = 2 
			begin 
		set @SQL1 = N'' + 
		'SELECT DISTINCT 
		nuc.Codeid, 
		nuc.ChapterId,   
		nuc.HeaderId, 
		nuc.SubHeaderId, 
		nuc.CodeNum AS [Display Code],  nuc.CodeDesc AS [Description], 
		Dagger,  
		Asteriks, 
		nuc.CodeHeader,  
		nuc.SubCodeHeader ,  
		nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
		nuc.AgeHigh , 
		nuc.DiagnosisGender
		FROM   dbo.NU_IntCodesFr nuc ' +
		--'LEFT OUTER JOIN dbo.ICD_ProcFile10 ICD ON nuc.Code = ICD.Code ' +
		' FULL OUTER JOIN dbo.NU_PrvNotes ON nuc.Code = dbo.NU_PrvNotes.Code 
		 WHERE   '  		set @SQL  = @SQL1 + @SearchString + isnull(@SearchString1, '') +
		' AND( nuc.AgeLow <= ' + cast(@Age as varchar)  + 
		' AND nuc.AgeHigh  >= ' + cast(@Age as varchar) + ' OR  nuc.agelow = 150 ) ' +
		' AND (nuc.DiagnosisGender  in ' + @GenderS +  
		')  AND nuc.ValidFrom <= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
		' AND nuc.ValidTo >= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
		--- EBV PR-01850
		' OR ( ' + @SearchString3 + ' AND UserId = ' + cast(@UserId as varchar) + '  )  AND nuc.CODENUM <> ''''  
		ORDER BY nuc.CodeNum  ASC '
		-- ' OR ' +  @SearchString1 +
		-- LINE BELOW WAS CHANGED NOVEMBER 15 BY SIMON   TO NOT LOOK "AND FOR NU_IntCodes.CodeId <> 0"
		-- 'AND NU_IntCodes.CodeId <> 0 ORDER BY DisplayCode  ASC ' ----they have chosen the cross reference function
			
		end
		else 
		 
		if   @SwitchFlag = 1 
			begin
		set @SQL1 = N'' + 
		'SELECT  DISTINCT 
		nuc.Codeid, 
		nuc.ChapterId,   
		nuc.HeaderId, 
		nuc.SubHeaderId, 
		nuc.CodeNum AS [Display Code],  nuc.CodeDesc AS [Description], 
		Dagger,  
		Asteriks, 
		nuc.CodeHeader,  
		nuc.SubCodeHeader ,  
		nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
		nuc.AgeHigh ,
		nuc.DiagnosisGender
		FROM  dbo.NU_CodesFr nuc ' + 
		--LEFT OUTER JOIN dbo.ICD_DiagFile10 ICD ON nuc.Code = ICD.Code ' +
		' FULL OUTER JOIN dbo.NU_PrvNotes ON nuc.Code = dbo.NU_PrvNotes.Code 
		 WHERE   '  
		 set @SQL  = @SQL1 + @SearchString + isnull(@SearchString1, '')  +
		' AND( nuc.AgeLow <= ' + cast(@Age as varchar)  + 
		' AND nuc.AgeHigh  >= ' + cast(@Age as varchar) + ' OR  nuc.agelow = 150 ) ' +
		' AND (nuc.DiagnosisGender  in ' + @GenderS +  
		')  AND nuc.ValidFrom <= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
		' AND nuc.ValidTo >= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
		--- EBV PR-01850
		' OR ( ' + @SearchString3 + ' AND UserId = ' + cast(@UserId as varchar) + '  )  AND nuc.CODENUM <> ''''  
		ORDER BY nuc.CodeNum  ASC '
		end
END
 
set nocount off
--print  @SQL
exec(@SQL)






















GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO















CREATE               PROCEDURE [NU_LookUpCDCodeAdv]
		@SearchString  as varchar(2000),
		@SwitchFlag as int,
		@Gender as varchar(1),
		@Age as int,
		@VisitDate as datetime,
		@OptionalStmt as varchar(10),
		@UserId as int 
AS
	
Declare @SQL as VarChar(8000)
Declare @SQL1 as VarChar(8000)
Declare @EntryValue as VarChar(50)
Declare @SearchValue as VarChar(50)
Declare @SearchString1 as varchar(8000) 
Declare @SearchString2 as varchar(8000) 
Declare @SearchString3 as varchar(8000) 
Declare @TempString as varchar(8000) 
declare @GenderS as varchar(50) -- Gender 'O' issue
Declare @Codenum as varchar(50) -- PR - 03799

---- 	EN-00411 add nuc.Flagged for intervention english 
--Declare @DashPosition as int
--NEW STUFF FOR FEB 19 
set nocount on 

set @GenderS = '(''A'', ''N'', ''G'')' 
if @Gender = 'F' set @GenderS = '(''A'', ''F'', ''G'')' -- Gender 'O' issue
if @Gender = 'M' set @GenderS = '(''A'', ''M'', ''N'')' -- Gender 'O' issue
if @Gender = 'O' set @GenderS = '(''A'', ''G'', ''N'')' -- Gender 'O' issue

--   PR - 03799 Sep 4,2008
select @Codenum = CODENUM from NU_CODES where cihivalue like  @SearchString  
if @Codenum <> '' 
begin
	set @SearchString = @Codenum 
end 
--  

--set @SearchString = replace(@SearchString, '''', '''''')

IF @OptionalStmt = '0' 
BEGIN
    set @TempString =   replace(@SearchString, ' ',''',''') 
    set @TempString =    '''' + @TempString  +''''
    set @SearchString2 = ''
    --Have to search multiple entries ie two chest's have to do search 
    --On both chest pector 
    --And chest stetho
	
	
	set @SQL = N'' + 'declare  Cur_XReference cursor   fast_forward for ' +
 	'select EntryValue, SearchValue ' + 
	'from NU_CrossReference ' + 
	'where EntryValue in (  ' +  @TempString  + '   ) '  +
	 
		'Open Cur_XReference ' --Create Dynamic Cursur 
--print @sql
		exec(@SQL)
		fetch next from Cur_XReference
			into @EntryValue, @SearchValue
	while @@fetch_status = 0
	begin
		if @EntryValue  <> '' 
		begin
			--If the word is in the list of crossreference
			--Get the last on ... because @SearchString1 is being replaced
			set @SearchString1 =  replace(@SearchString, @EntryValue, @SearchValue)  
-- 			If isnull(@Searchstring1,'')  <>''
-- 			begin 
-- 				set @SearchString2 = 	isnull(@SearchString2,'') + ' or isnull ([UserDescription],'''') + '' '' +  isnull ([cihivalue],'''') + '' '' + isnull ([displaycode],'''')   like ''%' + @SearchString1 + '%'''
-- 				--This is in case there are many entries for one cross refference  
-- 			end
		end
	    fetch next from Cur_XReference
	    into @EntryValue, @SearchValue
	end
	
	Close Cur_XReference
    deallocate Cur_XReference
 
    set  @SearchString2 =  @SearchString
	 
--"""""""""""""""""""""""""""""""""""""""""""
-- 	set @SearchString = replace(@SearchString, '  ', ' ')
-- 	set @SearchString = replace(@SearchString, ' ', '%'' and  [IncludeDesc]   like ''%')	
-- 	set @SearchString = '[IncludeDesc]   like ''%' + @SearchString + '%'''
-- 	
-- 	--the next lines are for searching user notes they have to be ored with original because and will
-- 	--return no values
-- 	 
-- 	--ICDNotes
--*************************************************
--- ED - 00765
 -----BEGIN SQL -----------------------------------------------------------        
	set @SearchString3 =  @SearchString   

	set @SearchString3 = replace(@SearchString3, '  ', ' ')
	--set @SearchString3 = replace(@SearchString3,  ' ', '%'' and [HEADERSEARCH]   + '' '' + nuc.[CodeNum]  + '' '' + CIHIValue  + '' '' +  isnull (ICDNotes,'''') like ''%')	
       ---Ticket No PR - 01555
	 set @SearchString3 = replace(@SearchString3,  ' ', '%'' and isnull (PrvNote,'''') like ''%')	
	 set @SearchString3 = ' isnull (PrvNote,'''') like ''%' + @SearchString3 + '%'''
 
	--Ticket ED - 01483 to replace CodeDesc with Headersearch	
	set @SearchString = replace(@SearchString, '  ', ' ')
	set @SearchString = replace(@SearchString, ' ', '%'' and [HEADERSEARCH]   + '' '' + nuc.[CodeNum]  + '' '' + CIHIValue  + '' '' +  isnull (ICDNotes,'''') like ''% ')	
	set @SearchString = '[HEADERSEARCH]  + '' '' + nuc.[CodeNum] + '' '' +   isnull (CIHIValue,'''')  + '' '' +   isnull (ICDNotes,'''') + '' '' + replace(replace(nuc.codelink1,''.'',''''),''/'','''')  like ''% ' + @SearchString + '%'''
	--+ '' '' + [IncludeDesc]
	--+ '' '' + [IncludeDesc]
	--the next lines are for searching user notes they have to be ored with original because and will
	--return no values
	  
	--ICDNotes
	If isnull(@Searchstring1, '') <>''
	Begin
		set @SearchString1 = replace(@SearchString1, '  ', ' ')
		set @SearchString1 = replace(@SearchString1, ' ', '%'' and isnull ([HEADERSEARCH],'''')   + '' '' + isnull (nuc.[CodeNum],'''')  + '' '' + isnull (CIHIValue,'''') like ''%')	
		set @SearchString1 = ' or isnull ([HEADERSEARCH],'''')   + '' '' + isnull (nuc.[CodeNum],'''') + '' '' + isnull (CIHIValue,'''')   like ''%' + @SearchString1 + '%'''
	End
--+ '' '' + isnull ([IncludeDesc],'''') 
--+ '' '' + isnull ([IncludeDesc],'''')
	--the next lines are for searching user notes they have to be ored with original because and will
	--return no values

--NP-01707 Simon August 22 2008
--check for * and then replace with so % *AAAAA% becomes %AAAA%
if (CHARINDEX('*',@SearchString,0) <> 0)
	begin
		set	 @SearchString = replace(@SearchString,'% ','%')
		set	 @SearchString = replace(@SearchString,'*','')
	end
-----END SQL -----------------------------------------------------------
	 
    set @SearchString2 = replace( @SearchString + isnull(@SearchString1, '') , '[HEADERSEARCH]', '[IncludeDesc]')

    --select @SearchString, @SearchString1, @SearchString2, @SearchString3

    if  @SwitchFlag = 2 
	begin 
        set @SQL1 = N'' + 
        'SELECT DISTINCT 
        nuc.Codeid, 
        nuc.ChapterId,   
        nuc.HeaderId, 
        nuc.SubHeaderId, 
        nuc.CodeNum AS [Display Code],  nuc.CodeDesc AS [Description], 
        Dagger,  
        Asteriks, 
        nuc.CodeHeader,  
        nuc.SubCodeHeader ,  
        nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
        nuc.AgeHigh ,
        nuc.DiagnosisGender,
		nuc.Flagged
        FROM  dbo.NU_IntCodes nuc ' +
        --'LEFT OUTER JOIN dbo.ICD_ProcFile10 ICD ON nuc.Code = ICD.Code ' +
        ' FULL OUTER JOIN dbo.NU_PrvNotes ON nuc.Code = dbo.NU_PrvNotes.Code ' +
        --  FULL OUTER JOIN   
        --dbo.NU_IntInclude ON nuc.CodeId = dbo.NU_IntInclude.CodeId   ED - 01483
        --AND nuc.ChapterId = dbo.NU_IntInclude.ChapterId AND 
        --nuc.HeaderId = dbo.NU_IntInclude.HeaderId AND 
        --nuc.SubHeaderId = dbo.NU_IntInclude.SubHeaderId AND 
        --nuc.CodeHeader = dbo.NU_IntInclude.CodeHeader AND
        --nuc.SubCodeHeader = dbo.NU_IntInclude.SubCodeHeader
        ' WHERE   '    
 	        set @SQL  = @SQL1 + @SearchString + isnull(@SearchString1, '') + 
        -- ' OR ' +  @SearchString2 +
         ' AND( nuc.AgeLow <= ' + cast(@Age as varchar)  + 
        ' AND nuc.AgeHigh  >= ' + cast(@Age as varchar) + ' OR  nuc.agelow = 150 ) ' +
        ' AND (isnull(nuc.DiagnosisGender, '''') in ' + @GenderS +
        ')  AND nuc.ValidFrom <= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
        ' AND nuc.ValidTo >= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
        --ED - 00765
        ' OR ( ' + @SearchString3 + ' AND UserId = ' + cast(@UserId as varchar) + '  )  AND nuc.CODENUM <> ''''  
          ORDER BY nuc.CodeNum  ASC '
	end
    else 
     
    if   @SwitchFlag = 1 
	begin
    --ED-01642 ADD Canadian column
        set @SQL1 = N'' + 
        'SELECT DISTINCT 
        nuc.Codeid, 
        nuc.ChapterId,   
        nuc.HeaderId, 
        nuc.SubHeaderId, 
        nuc.CodeNum AS [Display Code],  nuc.CodeDesc AS [Description], 
        Dagger,  
        Asteriks, 
        nuc.CodeHeader,  
        nuc.SubCodeHeader ,  
        nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
        nuc.AgeHigh ,

        nuc.DiagnosisGender,
        nuc.Canadian
        FROM  dbo.NU_Codes nuc ' +
        -- 'dbo.NU_PrvNotes ON nuc.Code = dbo.NU_PrvNotes.Code FULL OUTER JOIN ' +
        --LEFT OUTER JOIN dbo.ICD_DiagFile10 ICD ON nuc.Code = ICD.Code ' +
        ' FULL OUTER JOIN dbo.NU_PrvNotes ON nuc.Code = dbo.NU_PrvNotes.Code ' + 
        --   FULL OUTER JOIN
        -- dbo.NU_Include ON nuc.CodeId = dbo.NU_Include.CodeId  ED - 01483
        -- AND nuc.ChapterId = dbo.NU_Include.ChapterId AND 
        -- nuc.HeaderId = dbo.NU_Include.HeaderId AND 
        -- nuc.SubHeaderId = dbo.NU_Include.SubHeaderId AND 
        -- nuc.CodeHeader = dbo.NU_Include.CodeHeader
        'WHERE  '
           set @SQL  = @SQL1 + @SearchString + isnull(@SearchString1, '')  +
        -- ' OR ' +  @SearchString2 +
        ' AND( nuc.AgeLow <= ' + cast(@Age as varchar)  + 
        ' AND nuc.AgeHigh  >= ' + cast(@Age as varchar) + ' OR  nuc.agelow = 150 ) ' +
        ' AND (isnull(nuc.DiagnosisGender, '''') in ' + @GenderS +
        ')  AND nuc.ValidFrom <= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
        ' AND nuc.ValidTo >= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
        --ED - 00765
        ' OR ( ' + @SearchString3 + ' AND UserId = ' + cast(@UserId as varchar) + '  )  AND nuc.CODENUM <> ''''  
          ORDER BY nuc.CodeNum  ASC '
--print  @SQL
    end

END

IF @OptionalStmt = '10000' 
BEGIN
    set @TempString =   replace(@SearchString , ' ',''',''') 
    set @TempString =    '''' + @TempString  +''''
    set @SearchString2 = ''
    --Have to search multiple entries ie two chest's have to do search --On both chest pector 
    --And chest stetho
	
	
	set @SQL = N'' + 'declare  Cur_XReference cursor   fast_forward for ' + 	'select EntryValue, SearchValue ' + 

	'from NU_CrossReferenceFr ' + 
	'where EntryValue in (  ' +  @TempString  + '   ) '  +
	 
		'Open Cur_XReference ' --Create Dynamic Cursur 
		exec(@SQL)
		fetch next from Cur_XReference
			into @EntryValue, @SearchValue
	while @@fetch_status = 0
	begin
		if @EntryValue  <> '' 
		begin
			--If the word is in the list
			set @SearchString1 =  replace(@SearchString, @EntryValue, @SearchValue)  
-- 			If isnull(@Searchstring1,'')  <>''
-- 			begin 
-- 				set @SearchString2 = 	isnull(@SearchString2,'') + ' or isnull ([UserDescription],'''') + '' '' +  isnull ([cihivalue],'''') + '' '' + isnull ([displaycode],'''')   like ''%' + @SearchString1 + '%'''
-- 				--This is in case there are many entries for one cross refference  
-- 			end
		end
	fetch next from Cur_XReference
	into @EntryValue, @SearchValue
	end
	
	Close Cur_XReference
    deallocate Cur_XReference
 
    set  @SearchString2 =  @SearchString
	 
--"""""""""""""""""""""""""""""""""""""""""""
-- 	set @SearchString = replace(@SearchString, '  ', ' ')
-- 	set @SearchString = replace(@SearchString, ' ', '%'' and  [IncludeDesc]   like ''%')	
-- 	set @SearchString = '[IncludeDesc]   like ''%' + @SearchString + '%'''
-- 	
-- 	--the next lines are for searching user notes they have to be ored with original because and will
-- 	--return no values
-- 	 
-- 	--ICDNotes
--*************************************************
        
	set @SearchString3 =  @SearchString   

	set @SearchString3 = replace(@SearchString3, '  ', ' ')
	--set @SearchString3 = replace(@SearchString3,  ' ', '%'' and [HEADERSEARCH]   + '' '' + nuc.[CodeNum]  + '' '' + CIHIValue  + '' '' +  isnull (ICDNotes,'''') like ''%')	
       ---Ticket No PR - 01555
	 set @SearchString3 = replace(@SearchString3,  ' ', '%'' and isnull (PrvNote,'''') like ''%')	
	 set @SearchString3 = ' isnull (PrvNote,'''') like ''%' + @SearchString3 + '%'''
	
	--print  @SearchString3

	set @SearchString = replace(@SearchString, '  ', ' ')
	set @SearchString = replace(@SearchString, ' ', '%'' and [HEADERSEARCH]   + '' '' + nuc.[CodeNum]  + '' '' + CIHIValue  + '' '' +  isnull (ICDNotes,'''') like ''%')	
	set @SearchString = '[HEADERSEARCH]  + '' '' + nuc.[CodeNum] + '' '' +   isnull (CIHIValue,'''')  + '' '' +   isnull (ICDNotes,'''') + '' '' + replace(replace(nuc.codelink1,''.'',''''),''/'','''')  like ''%' + @SearchString + '%'''
	
	--+ '' '' + [IncludeDesc]
	--+ '' '' + [IncludeDesc]
	--the next lines are for searching user notes they have to be ored with original because and will
	--return no values
	 
	--ICDNotes
	If isnull(@Searchstring1, '') <>''
	Begin
		set @SearchString1 = replace(@SearchString1, '  ', ' ')
		set @SearchString1 = replace(@SearchString1, ' ', '%'' and isnull ([HEADERSEARCH],'''')   + '' '' + isnull (nuc.[CodeNum],'''')  + '' '' + isnull (CIHIValue,'''') like ''%')	
		set @SearchString1 = ' or isnull ([HEADERSEARCH],'''')   + '' '' + isnull (nuc.[CodeNum],'''') + '' '' + isnull (CIHIValue,'''')   like ''%' + @SearchString1 + '%'''
	End

 
--+ '' '' + isnull ([IncludeDesc],'''') 
--+ '' '' + isnull ([IncludeDesc],'''')
	--the next lines are for searching user notes they have to be ored with original because and will
	--return no values
	 
    set @SearchString2 = replace( @SearchString + isnull(@SearchString1, '') , '[HEADERSEARCH]', '[IncludeSrch]')

    if  @SwitchFlag = 2 
	begin 
        set @SQL1 = N'' + 
        'SELECT DISTINCT 
        nuc.Codeid, 
        nuc.ChapterId,   
        nuc.HeaderId, 
        nuc.SubHeaderId, 
        nuc.CodeNum AS [Display Code],  nuc.CodeDesc AS [Description], 
        Dagger,  
        Asteriks, 
        nuc.CodeHeader,  
        nuc.SubCodeHeader ,  
        nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
        nuc.AgeHigh ,
        nuc.DiagnosisGender
        FROM  dbo.NU_IntCodesFr nuc ' +

        --'LEFT OUTER JOIN dbo.ICD_ProcFile10 ICD ON nuc.Code = ICD.Code ' +
        ' FULL OUTER JOIN dbo.NU_PrvNotes ON nuc.Code = dbo.NU_PrvNotes.Code 
         FULL OUTER JOIN
        dbo.NU_IntIncludefr ON nuc.CodeId = dbo.NU_IntIncludefr.CodeId 
        AND nuc.ChapterId = dbo.NU_IntIncludefr.ChapterId AND 
        nuc.HeaderId = dbo.NU_IntIncludefr.HeaderId AND 
        nuc.SubHeaderId = dbo.NU_IntIncludefr.SubHeaderId AND 
        nuc.CodeHeader = dbo.NU_IntIncludefr.CodeHeader AND
        nuc.SubCodeHeader = dbo.NU_IntIncludefr.SubCodeHeader
        WHERE   '    
 	        set @SQL  = @SQL1 + @SearchString + isnull(@SearchString1, '') +
         ' OR ' +  @SearchString2 +
         ' AND( nuc.AgeLow <= ' + cast(@Age as varchar)  + 
        ' AND nuc.AgeHigh  >= ' + cast(@Age as varchar) + ' OR  nuc.agelow = 150 ) ' +
        ' AND (isnull(nuc.DiagnosisGender, '''') in ' + @GenderS +
        ')  AND nuc.ValidFrom <= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
        ' AND nuc.ValidTo >= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
        ' OR ( ' + @SearchString3 + ' AND UserId = ' + cast(@UserId as varchar) + '  )  AND nuc.CODENUM <> ''''  
          ORDER BY nuc.CodeNum  ASC '

	end
    else 
     
    if   @SwitchFlag = 1 
	begin
        set @SQL1 = N'' + 'SELECT DISTINCT 
        nuc.Codeid, 
        nuc.ChapterId,   
        nuc.HeaderId, 
        nuc.SubHeaderId, 
        nuc.CodeNum AS [Display Code],  nuc.CodeDesc AS [Description], 
        Dagger,  
        Asteriks, 
        nuc.CodeHeader,  
        nuc.SubCodeHeader ,  nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
        nuc.AgeHigh ,
        nuc.DiagnosisGender
        FROM  dbo.NU_CodesFr nuc ' +
        ' FULL OUTER JOIN dbo.NU_PrvNotes ON nuc.Code = dbo.NU_PrvNotes.Code   
         FULL OUTER JOIN
        dbo.NU_Includefr ON nuc.CodeId = dbo.NU_Includefr.CodeId 
        AND nuc.ChapterId = dbo.NU_Includefr.ChapterId AND 
        nuc.HeaderId = dbo.NU_Includefr.HeaderId AND 
        nuc.SubHeaderId = dbo.NU_Includefr.SubHeaderId AND 
        nuc.CodeHeader = dbo.NU_Includefr.CodeHeader
        WHERE    '
           set @SQL  = @SQL1 + @SearchString + isnull(@SearchString1, '')  +
         ' OR ' +  @SearchString2 +  
        ' AND(  nuc.AgeLow <= ' + cast(@Age as varchar)  + 
        ' AND nuc.AgeHigh  >= ' + cast(@Age as varchar) + ' OR  nuc.agelow = 150 ) ' +
        ' AND (nuc.DiagnosisGender  LIKE ' + '''' + @GenderS + '''' + 
        ')  AND nuc.ValidFrom <= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
        ' AND nuc.ValidTo >= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
        ' OR ( ' + @SearchString3 + ' AND UserId = ' + cast(@UserId as varchar) + '  )  AND nuc.CODENUM <> ''''  
          ORDER BY nuc.CodeNum  ASC '
 
-- set @SQL1 = N'' + 
-- 'SELECT DISTINCT 
-- nuc.Codeid, 
-- nuc.ChapterId,   
-- nuc.HeaderId, 
-- nuc.SubHeaderId, 
-- nuc.CodeNum AS [Display Code],  nuc.CodeDesc AS [Description], 
-- Dagger,  
-- Asteriks, 
-- nuc.CodeHeader,  
-- nuc.SubCodeHeader ,  
-- nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
-- nuc.AgeHigh ,
-- nuc.DiagnosisGender
-- FROM  dbo.NU_CodesFr nuc ' +
-- ' FULL OUTER JOIN dbo.NU_PrvNotes ON nuc.Code = dbo.NU_PrvNotes.Code   
--  FULL OUTER JOIN
-- dbo.NU_Includefr ON nuc.CodeId = dbo.NU_Includefr.CodeId 
-- AND nuc.ChapterId = dbo.NU_Includefr.ChapterId AND 
-- nuc.HeaderId = dbo.NU_Includefr.HeaderId AND 
-- nuc.SubHeaderId = dbo.NU_Includefr.SubHeaderId AND 
-- nuc.CodeHeader = dbo.NU_Includefr.CodeHeader
-- WHERE UserId =  ' + cast(@UserId  as varchar) + ' AND '    
--    set @SQL  = @SQL1 + @SearchString + isnull(@SearchString1, '')  +
--  ' OR ' +  @SearchString2 + ' OR ' +  @SearchString3 +  
-- ' AND(  nuc.AgeLow <= ' + cast(@Age as varchar)  + 
-- ' AND nuc.AgeHigh  >= ' + cast(@Age as varchar) + ' OR  nuc.agelow = 150 ) ' +
-- ' AND (nuc.DiagnosisGender  LIKE ' + '''' + @GenderS + '''' +  ' OR  nuc.DiagnosisGender = ' + '''A''' +
-- ')  AND nuc.ValidFrom <= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
-- ' AND nuc.ValidTo >= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
-- ' AND CODENUM <> ''''  
--   ORDER BY CodeNum  ASC '

 --' OR ' +  @SearchString1 +
--OR NU_PrvNotes ' + @SearchString + ' WHERE NU_PrvNotes.UserId = ' + @UserId + '
  
    end
END

set nocount off
--Print @SQL


exec(@SQL)














GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO






















CREATE                                                                        PROCEDURE [NU_LookUpCDCodeAdvTest]
		
				
		@SearchString  as varchar(800),
		@SwitchFlag as int,
		@Gender as varchar(1),
		@Age as int,
		@VisitDate as datetime,
		@OptionalStmt as varchar(10),
		@UserId as int 
		
		 
AS
	
Declare @SQL as VarChar(8000)
Declare @SQL1 as VarChar(8000)
Declare @EntryValue as VarChar(50)
Declare @SearchValue as VarChar(50)
Declare @SearchString1 as varchar(8000) 
Declare @SearchString2 as varchar(8000) 
Declare @SearchString3 as varchar(8000) 
Declare @TempString as varchar(8000) 
--Declare @DashPosition as int
--NEW STUFF FOR FEB 19 
set nocount on 

IF @OptionalStmt = '0' BEGIN
set @TempString =   replace(@SearchString , ' ',''',''') 
set @TempString =    '''' + @TempString  +''''
set @SearchString2 = ''
--Have to search multiple entries ie two chest's have to do search 
--On both chest pector 
--And chest stetho
	
	
	set @SQL = N'' + 'declare  Cur_XReference cursor   fast_forward for ' +
 	'select EntryValue, SearchValue ' + 
	'from NU_CrossReference ' + 
	'where EntryValue in (  ' +  @TempString  + '   ) '  +
	 
		'Open Cur_XReference ' --Create Dynamic Cursur 
		exec(@SQL)
		fetch next from Cur_XReference
			into @EntryValue, @SearchValue
	while @@fetch_status = 0
	begin
		if @EntryValue  <> '' 
		begin
			--If the word is in the list of crossreference
			--Get the last on ... because @SearchString1 is being replaced
			set @SearchString1 =  replace(@SearchString, @EntryValue, @SearchValue)  
-- 			If isnull(@Searchstring1,'')  <>''
-- 			begin 
-- 				set @SearchString2 = 	isnull(@SearchString2,'') + ' or isnull ([UserDescription],'''') + '' '' +  isnull ([cihivalue],'''') + '' '' + isnull ([displaycode],'''')   like ''%' + @SearchString1 + '%'''
-- 				--This is in case there are many entries for one cross refference  
-- 			end
		end
	fetch next from Cur_XReference
	into @EntryValue, @SearchValue
	end
	
	Close Cur_XReference
deallocate Cur_XReference
 
set  @SearchString2 =  @SearchString
	 
--"""""""""""""""""""""""""""""""""""""""""""
-- 	set @SearchString = replace(@SearchString, '  ', ' ')
-- 	set @SearchString = replace(@SearchString, ' ', '%'' and  [IncludeDesc]   like ''%')	
-- 	set @SearchString = '[IncludeDesc]   like ''%' + @SearchString + '%'''
-- 	
-- 	--the next lines are for searching user notes they have to be ored with original because and will
-- 	--return no values
-- 	 
-- 	--ICDNotes
--*************************************************
--- ED - 00765
        
	set @SearchString3 =  @SearchString   

	set @SearchString3 = replace(@SearchString3, '  ', ' ')
	--set @SearchString3 = replace(@SearchString3,  ' ', '%'' and [HEADERSEARCH]   + '' '' + nuc.[CodeNum]  + '' '' + CIHIValue  + '' '' +  isnull (ICDNotes,'''') like ''%')	
       ---Ticket No PR - 01555
	 set @SearchString3 = replace(@SearchString3,  ' ', '%'' and isnull (PrvNote,'''') like ''%')	
	 set @SearchString3 = ' isnull (PrvNote,'''') like ''%' + @SearchString3 + '%'''
 
	--Ticket ED - 01483 to replace CodeDesc with Headersearch	
	set @SearchString = replace(@SearchString, '  ', ' ')
	set @SearchString = replace(@SearchString, ' ', '%'' and [HEADERSEARCH]   + '' '' + nuc.[CodeNum]  + '' '' + CIHIValue  + '' '' +  isnull (ICDNotes,'''') like ''%')	
	set @SearchString = '[HEADERSEARCH]  + '' '' + nuc.[CodeNum] + '' '' +   isnull (CIHIValue,'''')  + '' '' +   isnull (ICDNotes,'''') + '' '' + replace(replace(nuc.codelink1,''.'',''''),''/'','''')  like ''% ' + @SearchString + '% '''
	--+ '' '' + [IncludeDesc]
	--+ '' '' + [IncludeDesc]
	--the next lines are for searching user notes they have to be ored with original because and will
	--return no values
	  
	--ICDNotes
	If isnull(@Searchstring1, '') <>''
	Begin
		set @SearchString1 = replace(@SearchString1, '  ', ' ')
		set @SearchString1 = replace(@SearchString1, ' ', '%'' and isnull ([HEADERSEARCH],'''')   + '' '' + isnull (nuc.[CodeNum],'''')  + '' '' + isnull (CIHIValue,'''') like ''%')	
		set @SearchString1 = ' or isnull ([HEADERSEARCH],'''')   + '' '' + isnull (nuc.[CodeNum],'''') + '' '' + isnull (CIHIValue,'''')   like ''%' + @SearchString1 + '%'''
	End
--+ '' '' + isnull ([IncludeDesc],'''') 
--+ '' '' + isnull ([IncludeDesc],'''')
	--the next lines are for searching user notes they have to be ored with original because and will
	--return no values
	 
set @SearchString2 = replace( @SearchString + isnull(@SearchString1, '') , '[HEADERSEARCH]', '[IncludeDesc]')
if  @SwitchFlag = 2 
	begin 


set @SQL1 = N'' + 
'SELECT DISTINCT 
nuc.Codeid, 
nuc.ChapterId,   
nuc.HeaderId, 
nuc.SubHeaderId, 
nuc.CodeNum AS [Display Code],  nuc.CodeDesc AS [Description], 
Dagger,  
Asteriks, 
nuc.CodeHeader,  
nuc.SubCodeHeader ,  
nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
nuc.AgeHigh ,
nuc.DiagnosisGender
FROM  dbo.NU_IntCodes nuc ' +
--'LEFT OUTER JOIN dbo.ICD_ProcFile10 ICD ON nuc.Code = ICD.Code ' +
' FULL OUTER JOIN dbo.NU_PrvNotes ON nuc.Code = dbo.NU_PrvNotes.Code 
  FULL OUTER JOIN   
dbo.NU_IntInclude ON nuc.CodeId = dbo.NU_IntInclude.CodeId 
AND nuc.ChapterId = dbo.NU_IntInclude.ChapterId AND 
nuc.HeaderId = dbo.NU_IntInclude.HeaderId AND 
nuc.SubHeaderId = dbo.NU_IntInclude.SubHeaderId AND 
nuc.CodeHeader = dbo.NU_IntInclude.CodeHeader AND
nuc.SubCodeHeader = dbo.NU_IntInclude.SubCodeHeader
WHERE   '    
 	set @SQL  = @SQL1 + @SearchString + isnull(@SearchString1, '') + 

 ' ORDER BY nuc.CodeNum  ASC '
	end
else 
 
if   @SwitchFlag = 1 
	begin
--ED-01642 ADD Canadian column
set @SQL1 = N'' + 
'SELECT DISTINCT 
nuc.Codeid, 
nuc.ChapterId,   
nuc.HeaderId, 
nuc.SubHeaderId, 
nuc.CodeNum AS [Display Code],  nuc.CodeDesc AS [Description], 
Dagger,  
Asteriks, 
nuc.CodeHeader,  
nuc.SubCodeHeader ,  
nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
nuc.AgeHigh ,
nuc.DiagnosisGender,
nuc.Canadian
FROM  dbo.NU_Codes nuc ' +
-- 'dbo.NU_PrvNotes ON nuc.Code = dbo.NU_PrvNotes.Code FULL OUTER JOIN ' +
--LEFT OUTER JOIN dbo.ICD_DiagFile10 ICD ON nuc.Code = ICD.Code ' +
' FULL OUTER JOIN dbo.NU_PrvNotes ON nuc.Code = dbo.NU_PrvNotes.Code ' + 
--   FULL OUTER JOIN
-- dbo.NU_Include ON nuc.CodeId = dbo.NU_Include.CodeId 
-- AND nuc.ChapterId = dbo.NU_Include.ChapterId AND 
-- nuc.HeaderId = dbo.NU_Include.HeaderId AND 
-- nuc.SubHeaderId = dbo.NU_Include.SubHeaderId AND 
-- nuc.CodeHeader = dbo.NU_Include.CodeHeader
'WHERE  '
   set @SQL  = @SQL1 + @SearchString + isnull(@SearchString1, '')  +

 ' ORDER BY nuc.CodeNum  ASC '
 --print @SQL
end

END

IF @OptionalStmt = '10000' BEGIN
set @TempString =   replace(@SearchString , ' ',''',''') 
set @TempString =    '''' + @TempString  +''''
set @SearchString2 = ''
--Have to search multiple entries ie two chest's have to do search --On both chest pector 
--And chest stetho
	
	
	set @SQL = N'' + 'declare  Cur_XReference cursor   fast_forward for ' + 	'select EntryValue, SearchValue ' + 

	'from NU_CrossReferenceFr ' + 
	'where EntryValue in (  ' +  @TempString  + '   ) '  +
	 
		'Open Cur_XReference ' --Create Dynamic Cursur 
		exec(@SQL)
		fetch next from Cur_XReference
			into @EntryValue, @SearchValue
	while @@fetch_status = 0
	begin
		if @EntryValue  <> '' 
		begin
			--If the word is in the list
			set @SearchString1 =  replace(@SearchString, @EntryValue, @SearchValue)  
-- 			If isnull(@Searchstring1,'')  <>''
-- 			begin 
-- 				set @SearchString2 = 	isnull(@SearchString2,'') + ' or isnull ([UserDescription],'''') + '' '' +  isnull ([cihivalue],'''') + '' '' + isnull ([displaycode],'''')   like ''%' + @SearchString1 + '%'''
-- 				--This is in case there are many entries for one cross refference  
-- 			end
		end
	fetch next from Cur_XReference
	into @EntryValue, @SearchValue
	end
	
	Close Cur_XReference
deallocate Cur_XReference
 
set  @SearchString2 =  @SearchString
	 
--"""""""""""""""""""""""""""""""""""""""""""
-- 	set @SearchString = replace(@SearchString, '  ', ' ')
-- 	set @SearchString = replace(@SearchString, ' ', '%'' and  [IncludeDesc]   like ''%')	
-- 	set @SearchString = '[IncludeDesc]   like ''%' + @SearchString + '%'''
-- 	
-- 	--the next lines are for searching user notes they have to be ored with original because and will
-- 	--return no values
-- 	 
-- 	--ICDNotes
--*************************************************
        
	set @SearchString3 =  @SearchString   

	set @SearchString3 = replace(@SearchString3, '  ', ' ')
	--set @SearchString3 = replace(@SearchString3,  ' ', '%'' and [HEADERSEARCH]   + '' '' + nuc.[CodeNum]  + '' '' + CIHIValue  + '' '' +  isnull (ICDNotes,'''') like ''%')	
       ---Ticket No PR - 01555
	 set @SearchString3 = replace(@SearchString3,  ' ', '%'' and isnull (PrvNote,'''') like ''%')	
	 set @SearchString3 = ' isnull (PrvNote,'''') like ''%' + @SearchString3 + '%'''
	
	--print  @SearchString3

	set @SearchString = replace(@SearchString, '  ', ' ')
	set @SearchString = replace(@SearchString, ' ', '%'' and [HEADERSEARCH]   + '' '' + nuc.[CodeNum]  + '' '' + CIHIValue  + '' '' +  isnull (ICDNotes,'''') like ''%')	
	set @SearchString = '[HEADERSEARCH]  + '' '' + nuc.[CodeNum] + '' '' +   isnull (CIHIValue,'''')  + '' '' +   isnull (ICDNotes,'''') + '' '' + replace(replace(nuc.codelink1,''.'',''''),''/'','''')  like ''%' + @SearchString + '%'''
	
	--+ '' '' + [IncludeDesc]
	--+ '' '' + [IncludeDesc]
	--the next lines are for searching user notes they have to be ored with original because and will
	--return no values
	 
	--ICDNotes
	If isnull(@Searchstring1, '') <>''
	Begin
		set @SearchString1 = replace(@SearchString1, '  ', ' ')
		set @SearchString1 = replace(@SearchString1, ' ', '%'' and isnull ([HEADERSEARCH],'''')   + '' '' + isnull (nuc.[CodeNum],'''')  + '' '' + isnull (CIHIValue,'''') like ''%')	
		set @SearchString1 = ' or isnull ([HEADERSEARCH],'''')   + '' '' + isnull (nuc.[CodeNum],'''') + '' '' + isnull (CIHIValue,'''')   like ''%' + @SearchString1 + '%'''
	End

 
--+ '' '' + isnull ([IncludeDesc],'''') 
--+ '' '' + isnull ([IncludeDesc],'''')
	--the next lines are for searching user notes they have to be ored with original because and will
	--return no values
	 
set @SearchString2 = replace( @SearchString + isnull(@SearchString1, '') , '[HEADERSEARCH]', '[IncludeSrch]')

if  @SwitchFlag = 2 
	begin 
set @SQL1 = N'' + 
'SELECT DISTINCT 
nuc.Codeid, 
nuc.ChapterId,   
nuc.HeaderId, 
nuc.SubHeaderId, 
nuc.CodeNum AS [Display Code],  nuc.CodeDesc AS [Description], 
Dagger,  
Asteriks, 
nuc.CodeHeader,  
nuc.SubCodeHeader ,  
nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
nuc.AgeHigh ,
nuc.DiagnosisGender
FROM  dbo.NU_IntCodesFr nuc ' +

--'LEFT OUTER JOIN dbo.ICD_ProcFile10 ICD ON nuc.Code = ICD.Code ' +
' FULL OUTER JOIN dbo.NU_PrvNotes ON nuc.Code = dbo.NU_PrvNotes.Code 
 FULL OUTER JOIN
dbo.NU_IntIncludefr ON nuc.CodeId = dbo.NU_IntIncludefr.CodeId 
AND nuc.ChapterId = dbo.NU_IntIncludefr.ChapterId AND 
nuc.HeaderId = dbo.NU_IntIncludefr.HeaderId AND 
nuc.SubHeaderId = dbo.NU_IntIncludefr.SubHeaderId AND 
nuc.CodeHeader = dbo.NU_IntIncludefr.CodeHeader AND
nuc.SubCodeHeader = dbo.NU_IntIncludefr.SubCodeHeader
WHERE   '    
 	set @SQL  = @SQL1 + @SearchString + isnull(@SearchString1, '') +
 ' ORDER BY nuc.CodeNum  ASC '

	end
else 
 
if   @SwitchFlag = 1 
	begin
 set @SQL1 = N'' + 'SELECT DISTINCT 
nuc.Codeid, 
nuc.ChapterId,   
nuc.HeaderId, 
nuc.SubHeaderId, 
nuc.CodeNum AS [Display Code],  nuc.CodeDesc AS [Description], 
Dagger,  
Asteriks, 
nuc.CodeHeader,  
nuc.SubCodeHeader ,  nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
nuc.AgeHigh ,
nuc.DiagnosisGender
FROM  dbo.NU_CodesFr nuc ' +
' FULL OUTER JOIN dbo.NU_PrvNotes ON nuc.Code = dbo.NU_PrvNotes.Code   
 FULL OUTER JOIN
dbo.NU_Includefr ON nuc.CodeId = dbo.NU_Includefr.CodeId 
AND nuc.ChapterId = dbo.NU_Includefr.ChapterId AND 
nuc.HeaderId = dbo.NU_Includefr.HeaderId AND 
nuc.SubHeaderId = dbo.NU_Includefr.SubHeaderId AND 
nuc.CodeHeader = dbo.NU_Includefr.CodeHeader
WHERE    '
   set @SQL  = @SQL1 + @SearchString + isnull(@SearchString1, '')  +
' ORDER BY nuc.CodeNum  ASC '
 
-- set @SQL1 = N'' + 
-- 'SELECT DISTINCT 
-- nuc.Codeid, 
-- nuc.ChapterId,   
-- nuc.HeaderId, 
-- nuc.SubHeaderId, 
-- nuc.CodeNum AS [Display Code],  nuc.CodeDesc AS [Description], 
-- Dagger,  
-- Asteriks, 
-- nuc.CodeHeader,  
-- nuc.SubCodeHeader ,  
-- nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
-- nuc.AgeHigh ,
-- nuc.DiagnosisGender
-- FROM  dbo.NU_CodesFr nuc ' +
-- ' FULL OUTER JOIN dbo.NU_PrvNotes ON nuc.Code = dbo.NU_PrvNotes.Code   
--  FULL OUTER JOIN
-- dbo.NU_Includefr ON nuc.CodeId = dbo.NU_Includefr.CodeId 
-- AND nuc.ChapterId = dbo.NU_Includefr.ChapterId AND 
-- nuc.HeaderId = dbo.NU_Includefr.HeaderId AND 
-- nuc.SubHeaderId = dbo.NU_Includefr.SubHeaderId AND 
-- nuc.CodeHeader = dbo.NU_Includefr.CodeHeader
-- WHERE UserId =  ' + cast(@UserId  as varchar) + ' AND '    
--    set @SQL  = @SQL1 + @SearchString + isnull(@SearchString1, '')  +
--  ' OR ' +  @SearchString2 + ' OR ' +  @SearchString3 +  
-- ' AND(  nuc.AgeLow <= ' + cast(@Age as varchar)  + 
-- ' AND nuc.AgeHigh  >= ' + cast(@Age as varchar) + ' OR  nuc.agelow = 150 ) ' +
-- ' AND (nuc.DiagnosisGender  LIKE ' + '''' + @Gender + '''' +  ' OR  nuc.DiagnosisGender = ' + '''A''' +
-- ')  AND nuc.ValidFrom <= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
-- ' AND nuc.ValidTo >= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
-- ' AND CODENUM <> ''''  
--   ORDER BY CodeNum  ASC '

 --' OR ' +  @SearchString1 +
--OR NU_PrvNotes ' + @SearchString + ' WHERE NU_PrvNotes.UserId = ' + @UserId + '
  
end
END

set nocount off
--Print @SQL


exec(@SQL)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO








CREATE                                           PROCEDURE [NU_LookUpCDCodeSimpler]
		@SearchString  as varchar(800),
		@SwitchFlag as int,
--N		@Gender as varchar(1),
--N		@Age as int,
--N		@VisitDate as datetime,
		@OptionalStmt as varchar(10),
		@UserId as int 
		 
 AS	
Declare @SQL as VarChar(8000)
Declare @SQL1 as VarChar(8000)
Declare @EntryValue as VarChar(50)
Declare @SearchValue as VarChar(50)
Declare @SearchString1 as varchar(8000) 
Declare @SearchString2 as varchar(8000) 
Declare @TempString as varchar(8000) 
--Declare @DashPosition as int
--NEW STUFF FOR FEB 19 
set nocount on 
--set @DashPosition =  0
--TEST IF THERE IS A "-" int the string if so use a between statment
--set @DashPosition = charindex('-', @SearchString ,1)  
--if @DashPosition <> 0
 
--begin 
	--EXECUTE BETWEEN STATMENT
	--print  @SearchString  
	--exec  NU_BetweenCode @SearchString, 1
	--return 0 
--end 
	
IF @OptionalStmt = '0' BEGIN
		
		set @TempString =   replace(@SearchString , ' ',''',''') 
		set @TempString =    '''' + @TempString  +''''
		set @SearchString2 = ''
		--Have to search multiple entries ie two chest's have to do search 
		--On both chest pector 
		--And chest stetho
			
			
			set @SQL = N'' + 'declare  Cur_XReference cursor   fast_forward for ' +
		 	'select EntryValue, SearchValue ' + 
			'from NU_CrossReference ' + 
			'where EntryValue in (  ' +  @TempString  + '   ) '  +
			 
				'Open Cur_XReference ' --Create Dynamic Cursur 
				exec(@SQL)
				fetch next from Cur_XReference
					into @EntryValue, @SearchValue
			while @@fetch_status = 0
			begin
				if @EntryValue  <> '' 
				begin
					--If the word is in the list
					set @SearchString1 =  replace(@SearchString, @EntryValue, @SearchValue)  
		-- 			If isnull(@Searchstring1,'')  <>''
		-- 			begin 
		-- 				set @SearchString2 = 	isnull(@SearchString2,'') + ' or isnull ([UserDescription],'''') + '' '' +  isnull ([cihivalue],'''') + '' '' + isnull ([displaycode],'''')   like ''%' + @SearchString1 + '%'''
		-- 				--This is in case there are many entries for one cross refference  
		-- 			end
				end
			fetch next from Cur_XReference
			into @EntryValue, @SearchValue
			end
			
			Close Cur_XReference
		deallocate Cur_XReference
		 
		 
		--"""""""""""""""""""""""""""""""""""""""""""
		-- 
		-- 	set @SearchString = replace(@SearchString, '  ', ' ')
		-- 	set @SearchString = replace(@SearchString, ' ', '%'' and [UserDescription]  + '' '' + [cihivalue] + '' '' + [displaycode]   + '' '' +  isnull ([ICDNotes],'''') like ''%')	
		-- 	set @SearchString = '[UserDescription] + '' '' +  [cihivalue]   + '' '' + [displaycode] + '' '' +  isnull ([ICDNotes],'''')  like ''%' + @SearchString + '%'''
		-- 	
		-- 	--the next lines are for searching user notes they have to be ored with original because and will
		-- 	--return no values
		-- 	 
		-- 	--ICDNotes
		-- 	If isnull(@Searchstring1, '') <>''
		-- 	Begin
		-- 		set @SearchString1 = replace(@SearchString1, '  ', ' ')
		-- 		set @SearchString1 = replace(@SearchString1, ' ', '%'' and isnull ([UserDescription],'''')   + '' '' + isnull ([cihivalue],'''') + '' '' + isnull ([displaycode],'''')  like ''%')	
		-- 		set @SearchString1 = ' or isnull ([UserDescription],'''')  + '' '' +  isnull ([cihivalue],'''') + '' '' + isnull ([displaycode],'''')   like ''%' + @SearchString1 + '%'''
		-- 	End
		 
			set @SearchString = replace(@SearchString, '  ', ' ')
			set @SearchString = replace(@SearchString, ' ', '%'' and [CodeDesc]  + '' '' + [CodeNum] + '' '' +   CIHIValue + '' '' + isnull (ICDNotes,'''') like ''%')	
			set @SearchString = '[CodeDesc]  + '' '' + [CodeNum] + '' '' +  isnull ( CIHIValue,'''') + '' '' +  isnull (ICDNotes,'''')  like ''%' + @SearchString + '%'''
			
			--the next lines are for searching user notes they have to be ored with original because and will
			--return no values
			 
			--ICDNotes
			If isnull(@Searchstring1, '') <>''
			Begin
				set @SearchString1 = replace(@SearchString1, '  ', ' ')
				set @SearchString1 = replace(@SearchString1, ' ', '%'' and isnull ([CodeDesc],'''')   + '' '' + isnull ([CodeNum],'''')  + '' '' +  CIHIValue like ''%')	
				set @SearchString1 = ' or isnull ([CodeDesc],'''')  + '' '' +  isnull ([CodeNum],'''') + '' '' +  isnull ( CIHIValue,'''')   like ''%' + @SearchString1 + '%'''
			End
		 
		if  @SwitchFlag = 2 
			begin 
		set @SQL1 = N'' + 
		'SELECT DISTINCT 
		nuc.Codeid, 
		nuc.ChapterId,   
		nuc.HeaderId, 
		nuc.SubHeaderId, 
		nuc.CodeNum AS [Display Code],  nuc.CodeDesc AS [Description], 
		Dagger,  
		Asteriks, 
		nuc.CodeHeader,  
		nuc.SubCodeHeader ,  
		nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
		nuc.AgeHigh , 
		nuc.DiagnosisGender,AutoID
		FROM   dbo.NU_IntCodes nuc ' +
		--'LEFT OUTER JOIN dbo.ICD_ProcFile10 ICD ON nuc.Code = ICD.Code ' +
		' WHERE   '  
		set @SQL  = @SQL1 + @SearchString + isnull(@SearchString1, '') +
--N		' AND( nuc.AgeLow <= ' + cast(@Age as varchar)  + 
--N		' AND nuc.AgeHigh  >= ' + cast(@Age as varchar) + ' OR  nuc.agelow = 150 ) ' +
--N		' AND (nuc.DiagnosisGender  LIKE ' + '''' + @Gender + '''' +  
--N		' OR  nuc.DiagnosisGender = ' + '''A''' +
--N		')  AND nuc.ValidFrom <= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
--N		' AND nuc.ValidTo >= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
		' AND nuc.CodeNum <> '''' ORDER BY nuc.CodeNum  ASC '
		-- ' OR ' +  @SearchString1 +
		-- LINE BELOW WAS CHANGED NOVEMBER 15 BY SIMON   TO NOT LOOK "AND FOR NU_IntCodes.CodeId <> 0"
		-- 'AND NU_IntCodes.CodeId <> 0 ORDER BY DisplayCode  ASC ' ----they have chosen the cross reference function
			
		end
		else 
		 
		if   @SwitchFlag = 1 
			begin
		set @SQL1 = N'' + 
		'SELECT  DISTINCT 
		nuc.Codeid, 
		nuc.ChapterId,   
		nuc.HeaderId, 
		nuc.SubHeaderId, 
		nuc.CodeNum AS [Display Code],  nuc.CodeDesc AS [Description], 
		Dagger,  
		Asteriks, 
		nuc.CodeHeader,  
		nuc.SubCodeHeader ,  
		nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
		nuc.AgeHigh ,
		nuc.DiagnosisGender,AutoID
		FROM  dbo.NU_Codes nuc ' + 
		--LEFT OUTER JOIN dbo.ICD_DiagFile10 ICD ON nuc.Code = ICD.Code ' +
		'WHERE  '
		   set @SQL  = @SQL1 + @SearchString + isnull(@SearchString1, '')  +
--N		' AND( nuc.AgeLow <= ' + cast(@Age as varchar)  + 
--N		' AND nuc.AgeHigh  >= ' + cast(@Age as varchar) + ' OR  nuc.agelow = 150 ) ' +
--N		' AND (nuc.DiagnosisGender  LIKE ' + '''' + @Gender + '''' +  ' OR  nuc.DiagnosisGender = ' + '''A''' +
--N		')  AND nuc.ValidFrom <= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
--N		' AND nuc.ValidTo >= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
		' AND nuc.CodeNum <> '''' ORDER BY nuc.CodeNum  ASC ' --' OR ' +  @SearchString1 +
		end
END

IF @OptionalStmt = '10000' BEGIN
		
		set @TempString =   replace(@SearchString , ' ',''',''') 
		set @TempString =    '''' + @TempString  +''''
		set @SearchString2 = ''
		--Have to search multiple entries ie two chest's have to do search 
		--On both chest pector 
		--And chest stetho
			
			
			set @SQL = N'' + 'declare  Cur_XReference cursor   fast_forward for ' +
		 	'select EntryValue, SearchValue ' + 
			'from NU_CrossReferenceFr ' + 
			'where EntryValue in (  ' +  @TempString  + '   ) '  +
			 
				'Open Cur_XReference ' --Create Dynamic Cursur 
				exec(@SQL)
				fetch next from Cur_XReference
					into @EntryValue, @SearchValue
			while @@fetch_status = 0
			begin
				if @EntryValue  <> '' 
				begin
					--If the word is in the list
					set @SearchString1 =  replace(@SearchString, @EntryValue, @SearchValue)  
		-- 			If isnull(@Searchstring1,'')  <>''
		-- 			begin 
		-- 				set @SearchString2 = 	isnull(@SearchString2,'') + ' or isnull ([UserDescription],'''') + '' '' +  isnull ([cihivalue],'''') + '' '' + isnull ([displaycode],'''')   like ''%' + @SearchString1 + '%'''
		-- 				--This is in case there are many entries for one cross refference  
		-- 			end
				end
			fetch next from Cur_XReference
			into @EntryValue, @SearchValue
			end
			
			Close Cur_XReference
		deallocate Cur_XReference
		 
		 
		--"""""""""""""""""""""""""""""""""""""""""""
		-- 
		-- 	set @SearchString = replace(@SearchString, '  ', ' ')
		-- 	set @SearchString = replace(@SearchString, ' ', '%'' and [UserDescription]  + '' '' + [cihivalue] + '' '' + [displaycode]   + '' '' +  isnull ([ICDNotes],'''') like ''%')	
		-- 	set @SearchString = '[UserDescription] + '' '' +  [cihivalue]   + '' '' + [displaycode] + '' '' +  isnull ([ICDNotes],'''')  like ''%' + @SearchString + '%'''
		-- 	
		-- 	--the next lines are for searching user notes they have to be ored with original because and will
		-- 	--return no values
		-- 	 
		-- 	--ICDNotes
		-- 	If isnull(@Searchstring1, '') <>''
		-- 	Begin
		-- 		set @SearchString1 = replace(@SearchString1, '  ', ' ')
		-- 		set @SearchString1 = replace(@SearchString1, ' ', '%'' and isnull ([UserDescription],'''')   + '' '' + isnull ([cihivalue],'''') + '' '' + isnull ([displaycode],'''')  like ''%')	
		-- 		set @SearchString1 = ' or isnull ([UserDescription],'''')  + '' '' +  isnull ([cihivalue],'''') + '' '' + isnull ([displaycode],'''')   like ''%' + @SearchString1 + '%'''
		-- 	End
		 
			set @SearchString = replace(@SearchString, '  ', ' ')
			set @SearchString = replace(@SearchString, ' ', '%'' and [HEADERSEARCH]  + '' '' + [CodeNum] + '' '' +   CIHIValue + '' '' + isnull (ICDNotes,'''') like ''%')	
			set @SearchString = '[HEADERSEARCH]  + '' '' + [CodeNum] + '' '' +  isnull ( CIHIValue,'''') + '' '' +  isnull (ICDNotes,'''')  like ''%' + @SearchString + '%'''
			
			--the next lines are for searching user notes they have to be ored with original because and will
			--return no values
			 
			--ICDNotes
			If isnull(@Searchstring1, '') <>''
			Begin
				set @SearchString1 = replace(@SearchString1, '  ', ' ')
				set @SearchString1 = replace(@SearchString1, ' ', '%'' and isnull ([HEADERSEARCH],'''')   + '' '' + isnull ([CodeNum],'''')  + '' '' +  CIHIValue like ''%')	
				set @SearchString1 = ' or isnull ([HEADERSEARCH],'''')  + '' '' +  isnull ([CodeNum],'''') + '' '' +  isnull ( CIHIValue,'''')   like ''%' + @SearchString1 + '%'''
			End
		 
		if  @SwitchFlag = 2 
			begin 
		set @SQL1 = N'' + 
		'SELECT DISTINCT 
		nuc.Codeid, 
		nuc.ChapterId,   
		nuc.HeaderId, 
		nuc.SubHeaderId, 
		nuc.CodeNum AS [Display Code],  nuc.CodeDesc AS [Description], 
		Dagger,  
		Asteriks, 
		nuc.CodeHeader,  
		nuc.SubCodeHeader ,  
		nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
		nuc.AgeHigh , 
		nuc.DiagnosisGender,AutoID
		FROM   dbo.NU_IntCodesFr nuc ' +
		--'LEFT OUTER JOIN dbo.ICD_ProcFile10 ICD ON nuc.Code = ICD.Code ' +
		' WHERE   '  
		set @SQL  = @SQL1 + @SearchString + isnull(@SearchString1, '') +
--N		' AND( nuc.AgeLow <= ' + cast(@Age as varchar)  + 
--N		' AND nuc.AgeHigh  >= ' + cast(@Age as varchar) + ' OR  nuc.agelow = 150 ) ' +
--N		' AND (nuc.DiagnosisGender  LIKE ' + '''' + @Gender + '''' +  
--N		' OR  nuc.DiagnosisGender = ' + '''A''' +
--N		')  AND nuc.ValidFrom <= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
--N		' AND nuc.ValidTo >= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
		' AND nuc.CodeNum <> '''' ORDER BY nuc.CodeNum  ASC '
		-- ' OR ' +  @SearchString1 +
		-- LINE BELOW WAS CHANGED NOVEMBER 15 BY SIMON   TO NOT LOOK "AND FOR NU_IntCodes.CodeId <> 0"
		-- 'AND NU_IntCodes.CodeId <> 0 ORDER BY DisplayCode  ASC ' ----they have chosen the cross reference function
			
		end
		else 
		 
		if   @SwitchFlag = 1 
			begin
		set @SQL1 = N'' + 
		'SELECT  DISTINCT 
		nuc.Codeid, 
		nuc.ChapterId,   
		nuc.HeaderId, 
		nuc.SubHeaderId, 
		nuc.CodeNum AS [Display Code],  nuc.CodeDesc AS [Description], 
		Dagger,  
		Asteriks, 
		nuc.CodeHeader,  
		nuc.SubCodeHeader ,  
		nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
		nuc.AgeHigh ,
		nuc.DiagnosisGender,AutoID
		FROM  dbo.NU_CodesFr nuc ' + 
		--LEFT OUTER JOIN dbo.ICD_DiagFile10 ICD ON nuc.Code = ICD.Code ' +
		'WHERE  '
		   set @SQL  = @SQL1 + @SearchString + isnull(@SearchString1, '')  +
--N		' AND( nuc.AgeLow <= ' + cast(@Age as varchar)  + 
--N		' AND nuc.AgeHigh  >= ' + cast(@Age as varchar) + ' OR  nuc.agelow = 150 ) ' +
--N		' AND (nuc.DiagnosisGender  LIKE ' + '''' + @Gender + '''' +  ' OR  nuc.DiagnosisGender = ' + '''A''' +
--N		')  AND nuc.ValidFrom <= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
--n		' AND nuc.ValidTo >= ' + '''' +  cast( @VisitDate as varchar(20)) + '''' + 
		' AND nuc.CodeNum <> '''' ORDER BY nuc.CodeNum  ASC ' --' OR ' +  @SearchString1 +
		end
END
 
set nocount off
--print  @SQL
exec(@SQL)






GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO













CREATE                               PROCEDURE [NU_LookUpDrugs_B]
@SearchString  as varchar(800),
@OptionalStmt as varchar(10)
AS
create table #T (
--AutoId int  IDENTITY (1, 1) NOT NULL ,
autoid int ,
HeaderDesc VARCHAR(255),
CodeLink VARCHAR(15),
HeaderId int,
SubHeaderId int,
)

Declare @TempString as varchar(1000)
Declare @FirstWord as varchar(100)
Declare @LeadWord as varchar(100)
Declare @LeadWord1 as varchar(100)
Declare @LeadWord2 as varchar(100)
Declare @LeadWord3 as varchar(100)
Declare @SQL as varchar(5000)
Declare @Index as int

IF @OptionalStmt = '10000' BEGIN
		set @TempString = @SearchString
		set nocount on
		set @LeadWord = ''
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @SearchString = replace(@SearchString,@FirstWord,'')
		if      @FirstWord  <> '' begin
		set @FirstWord = replace(@FirstWord, '  ', ' ')
		set @FirstWord = replace(@FirstWord, ' ', '%'' and [HeaderSearch]   like 
''%')

			set @FirstWord = '[HeaderSearch]    like ''%' + @FirstWord + '%'''
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT top 1000 autoid, HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId 
FROM NU_DrugsFr WHERE '
			+ @FirstWord + ' order by autoid'
			exec( @SQL)

		end
		 
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord1 = @FirstWord
		if      @LeadWord1 <> '' begin
		set @LeadWord1 = replace(@LeadWord1, '  ', ' ')
		set @LeadWord1 = replace(@LeadWord1, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord1 = '[HeaderSearch]    like ''%' + @LeadWord1 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT top 1000 autoid, HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId 
FROM NU_DrugsFr WHERE '
			+ @LeadWord1 + ' order by autoid'
			exec( @SQL)

		end
		--print 'Second Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord2 = @FirstWord
		if  @LeadWord2 <> '' begin
		set @LeadWord2 = replace(@LeadWord2, '  ', ' ')
		set @LeadWord2 = replace(@LeadWord2, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord2 = '[HeaderSearch]    like ''%' + @LeadWord2 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT top 1000 autoid,HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_DrugsFr WHERE '
			+ @LeadWord2 + ' order by autoid'
			exec( @SQL)

		end
		--print 'Third Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end
		set @LeadWord3 = @FirstWord
		if  @LeadWord3 <> '' begin
		set @LeadWord3 = replace(@LeadWord3, '  ', ' ')
		set @LeadWord3 = replace(@LeadWord3, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord3 = '[HeaderSearch]    like ''%' + @LeadWord3 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid,HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_DrugsFr WHERE '
			+ @LeadWord3 + ' order by autoid'
			exec( @SQL)

		--print 'Fourth Word ' + @FirstWord
		end
		SELECT DISTINCT  HeaderDesc  ,CodeLink  ,HeaderId ,SubheaderId ,autoid
		FROM #T order by autoid
END


-- 		SELECT  HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId   FROM #T
-- 		GROUP BY  HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId
-- 		ORDER BY min(autoid)


IF @OptionalStmt = '0' BEGIN
		set @TempString = @SearchString
		set nocount on
		set @LeadWord = ''
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @SearchString = replace(@SearchString,@FirstWord,'')
		if      @FirstWord  <> '' begin
		set @FirstWord = replace(@FirstWord, '  ', ' ')
		set @FirstWord = replace(@FirstWord, ' ', '%'' and [HeaderSearch]   like 
''%')

			set @FirstWord = '[HeaderSearch]    like ''%' + @FirstWord + '%'''
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT top 1000 autoid, HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId 
FROM NU_Drugs WHERE '
			+ @FirstWord + ' order by autoid'
			exec( @SQL)

		end
		 
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord1 = @FirstWord
		if      @LeadWord1 <> '' begin
		set @LeadWord1 = replace(@LeadWord1, '  ', ' ')
		set @LeadWord1 = replace(@LeadWord1, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord1 = '[HeaderSearch]    like ''%' + @LeadWord1 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT top 1000 autoid, HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId 
FROM NU_Drugs WHERE '
			+ @LeadWord1 + ' order by autoid'
			exec( @SQL)

		end
		--print 'Second Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord2 = @FirstWord
		if  @LeadWord2 <> '' begin
		set @LeadWord2 = replace(@LeadWord2, '  ', ' ')
		set @LeadWord2 = replace(@LeadWord2, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord2 = '[HeaderSearch]    like ''%' + @LeadWord2 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT top 1000 autoid,HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_Drugs WHERE '
			+ @LeadWord2 + ' order by autoid'
			exec( @SQL)

		end
		--print 'Third Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end
		set @LeadWord3 = @FirstWord
		if  @LeadWord3 <> '' begin
		set @LeadWord3 = replace(@LeadWord3, '  ', ' ')
		set @LeadWord3 = replace(@LeadWord3, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord3 = '[HeaderSearch]    like ''%' + @LeadWord3 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid,HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_Drugs WHERE '
			+ @LeadWord3 + ' order by autoid'
			exec( @SQL)

		--print 'Fourth Word ' + @FirstWord
		end
		SELECT DISTINCT  HeaderDesc  ,CodeLink  ,HeaderId ,SubheaderId ,autoid
		FROM #T order by autoid
END


-- 		SELECT  HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId   FROM #T
-- 		GROUP BY  HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId
-- 		ORDER BY min(autoid)



















GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO





























CREATE                                                     PROCEDURE 
[NU_LookUpDrugs_C]
@SearchString  as varchar(800),
@OptionalStmt as varchar(10)
AS

create table #T (
--AutoId int  IDENTITY (1, 1) NOT NULL ,
autoid int ,
HeaderDesc VARCHAR(255),
CodeLink VARCHAR(15),
HeaderId int,
SubHeaderId int,
)

Declare @TempString as varchar(1000)
Declare @FirstWord as varchar(100)
Declare @LeadWord as varchar(100)
Declare @LeadWord1 as varchar(100)
Declare @LeadWord2 as varchar(100)
Declare @LeadWord3 as varchar(100)
Declare @SQL as varchar(5000)
Declare @Index as int

IF @OptionalStmt = '10000' BEGIN
		set @TempString = @SearchString
		set nocount on
		set @LeadWord = ''
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @SearchString = replace(@SearchString,@FirstWord,'')
		if      @FirstWord  <> '' begin
		set @FirstWord = replace(@FirstWord, '  ', ' ')
		set @FirstWord = replace(@FirstWord, ' ', '%'' and [HeaderSearch]   like 
''%')

			set @FirstWord = '[HeaderSearch]    like ''%' + @FirstWord + '%'''
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT top 1000 autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId 
FROM NU_DrugsFr WHERE '
			+ @FirstWord + ' AND SUBHEADERID1 = 0 order by autoid'
			--print @SQL
			exec( @SQL)

		end

		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord1 = @FirstWord
		if      @LeadWord1 <> '' begin
		set @LeadWord1 = replace(@LeadWord1, '  ', ' ')
		set @LeadWord1 = replace(@LeadWord1, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord1 = '[HeaderSearch]    like ''%' + @LeadWord1 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT top 1000  autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId 
FROM NU_DrugsFr WHERE '
			+ @LeadWord1 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			--print @SQL
			exec( @SQL)

		end
		--print 'Second Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord2 = @FirstWord
		if  @LeadWord2 <> '' begin
		set @LeadWord2 = replace(@LeadWord2, '  ', ' ')
		set @LeadWord2 = replace(@LeadWord2, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord2 = '[HeaderSearch]    like ''%' + @LeadWord2 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT top 1000  autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId 
FROM NU_DrugsFr WHERE '
			+ @LeadWord2 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			 --print @SQL
			exec( @SQL)

		end
		--print 'Third Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end
		set @LeadWord3 = @FirstWord
		if  @LeadWord3 <> '' begin
		set @LeadWord3 = replace(@LeadWord3, '  ', ' ')
		set @LeadWord3 = replace(@LeadWord3, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord3 = '[HeaderSearch]    like ''%' + @LeadWord3 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT top 1000  autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId 
FROM NU_DrugsFr WHERE '
			+ @LeadWord3 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			--print @SQL
			exec( @SQL)

		--print 'Fourth Word ' + @FirstWord
		end
		SELECT DISTINCT  HeaderDesc  ,CodeLink  ,HeaderId ,SubheaderId ,autoid
		FROM #T order by autoid
END


IF @OptionalStmt = '0' BEGIN
		set @TempString = @SearchString
		set nocount on
		set @LeadWord = ''
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @SearchString = replace(@SearchString,@FirstWord,'')
		if      @FirstWord  <> '' begin
		set @FirstWord = replace(@FirstWord, '  ', ' ')
		set @FirstWord = replace(@FirstWord, ' ', '%'' and [HeaderSearch]   like 
''%')

			set @FirstWord = '[HeaderSearch]    like ''%' + @FirstWord + '%'''
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT top 1000 autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId 
FROM NU_Drugs WHERE '
			+ @FirstWord + ' AND SUBHEADERID1 = 0 order by autoid'
			--print @SQL
			exec( @SQL)

		end

		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord1 = @FirstWord
		if      @LeadWord1 <> '' begin
		set @LeadWord1 = replace(@LeadWord1, '  ', ' ')
		set @LeadWord1 = replace(@LeadWord1, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord1 = '[HeaderSearch]    like ''%' + @LeadWord1 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT top 1000  autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId 
FROM NU_Drugs WHERE '
			+ @LeadWord1 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			--print @SQL
			exec( @SQL)

		end
		--print 'Second Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord2 = @FirstWord
		if  @LeadWord2 <> '' begin
		set @LeadWord2 = replace(@LeadWord2, '  ', ' ')
		set @LeadWord2 = replace(@LeadWord2, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord2 = '[HeaderSearch]    like ''%' + @LeadWord2 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT top 1000  autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId 
FROM NU_Drugs WHERE '
			+ @LeadWord2 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			 --print @SQL
			exec( @SQL)

		end
		--print 'Third Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end
		set @LeadWord3 = @FirstWord
		if  @LeadWord3 <> '' begin
		set @LeadWord3 = replace(@LeadWord3, '  ', ' ')
		set @LeadWord3 = replace(@LeadWord3, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord3 = '[HeaderSearch]    like ''%' + @LeadWord3 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT top 1000  autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId 
FROM NU_Drugs WHERE '
			+ @LeadWord3 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			--print @SQL
			exec( @SQL)

		--print 'Fourth Word ' + @FirstWord
		end
		SELECT DISTINCT  HeaderDesc  ,CodeLink  ,HeaderId ,SubheaderId ,autoid
		FROM #T order by autoid
END






































GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO


























CREATE                             PROCEDURE [NU_LookUpDrugs_F]
@SearchString  as varchar(800),
@OptionalStmt as varchar(10)
AS
DECLARE @SQL varchar(2000)
set nocount on
set @SearchString = replace(@SearchString, '  ', ' ')
set @SearchString = replace(@SearchString, ' ', '%'' and [HeaderSearch]   
like ''%')
set @SearchString = '[HeaderSearch]    like ''%' + @SearchString + '%'''
--print @SearchString
IF @OptionalStmt = '0' BEGIN

set @SQL =
'SELECT DISTINCT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId , autoid FROM NU_DRUGS WHERE '
+ @SearchString + ' order by autoid'
--print @SQL
exec( @SQL)
END
IF @OptionalStmt = '10000' BEGIN


set @SQL =
'SELECT DISTINCT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId , autoid FROM NU_DRUGSFR WHERE '
+ @SearchString + ' order by autoid'
--print @SQL
set nocount off
exec( @SQL)




END












GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO












CREATE                                        PROCEDURE [NU_LookUpDrugsLast_B]
@SearchString  as varchar(800),
@OptionalStmt as varchar(10)
AS

-- Author: Brenda Vargas : Jan 24, 2007
-- Latest Change: 	   Feb 1, 2007
-- Prototype Drugs : It will replace the current Sp --> NU_LookUpDrugs_B 

--- Aug 21, 2007:
---             Sp renamed.  It was TMP_LookUpDrugs_B
---		renamed tmp_drugslast to Nu_DrugsLast
--- 		Renamed tmp_drugsFrlast to Nu_DrugsFrlast

Create table #T (
Autoid integer, 
HeaderDesc VARCHAR(255),
Chapter_XIX VARCHAR (15),
Accidental VARCHAR (15),
Intentional_Self_Harm VARCHAR (15),
Undetermined_Intent VARCHAR (15),
Adverse_effect_in_therapeutic_use VARCHAR (15), 
HeaderId int,
SubHeaderId int,
SubHeaderId1 int, 
SubHeaderId2 int,
SubHeaderId3 int,
HeaderSearch VARCHAR(255), 
HitNumber int, 
)

Declare @SQL as varchar(5000)
Declare @Index as int
Declare @Flag as int   			 -- use for first word   
Declare @WordToSearch as varchar(100) 

-- French 
if @OptionalStmt = '10000'
BEGIN
    set @Flag = 1 

    WHILE @SearchString <> ' ' 
    begin
	
	set nocount on
	
	set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
	set @Index = CHARINDEX (' ',  @SearchString  ,1 ) 
	set @WordToSearch =  rtrim(Left(@SearchString,@Index))

        if @WordToSearch = ''
	begin
	   set @WordToSearch = @SearchString
	end
	
	set @SearchString = replace(@SearchString,@WordToSearch,'')

	if  @WordToSearch  <> '' 
	begin
		set @WordToSearch = replace(@WordToSearch, '  ', ' ')
		set @WordToSearch = replace(@WordToSearch, ' ', '%'' and [HeaderSearch]   like ''%')

		if @Flag = 1  -- begin procedure for First word
		begin

			set @WordToSearch = '[HeaderSearch]    like '' ' + @WordToSearch + '%'''
				
			-- HitNumber = 1 : Means first work on the search  
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT top 1000 Autoid, HeaderDesc ,Chapter_XIX, Accidental, Intentional_Self_Harm, 
			Undetermined_Intent, Adverse_effect_in_therapeutic_use, HeaderId ,SubheaderId,
			SubHeaderId1, SubHeaderId2,SubHeaderId3, HeaderSearch, 1
			FROM Nu_DrugsFrlast WHERE '
			+ @WordToSearch + '  and subheaderid = 0 order by autoid'
			exec( @SQL)

			-- Add ALL children RELATED to this headerid with HitNumber = 0 
			
			INSERT INTO #T 
			SELECT top 1000 A.Autoid, A.HeaderDesc ,A.Chapter_XIX, A.Accidental, 
			A.Intentional_Self_Harm, A.Undetermined_Intent, A.Adverse_effect_in_therapeutic_use, 
			A.HeaderId ,A.SubheaderId, A.SubheaderId1, A.SubheaderId2, A.SubheaderId3, A.HeaderSearch, 0
			FROM Nu_DrugsFrlast as A, #T  
			WHERE  A.headerid = #T.headerid and A.subheaderid <> 0 order by A.autoid

			set @Flag = @Flag + 1

		end -- end procedure for First word
		else 
		  begin
			-- Others Words procedure
			set @WordToSearch = '[HeaderSearch]    like ''% ' + @WordToSearch + '%'''
			
			set @SQL = 'UPDATE #T SET HitNumber = ' + cast(@Flag as varchar)  + ' WHERE ' + @WordToSearch 
			exec( @SQL)
		
			set @Flag = @Flag + 1
		  end
		
	end  -- ENDS IF 
   END  -- ENDS WHILE 
END  ---- ENDS FRENCH  


--English 
IF @OptionalStmt = '0' 
BEGIN
    set @Flag = 1 

    WHILE @SearchString <> ' ' 
    begin
	
	set nocount on
	
	set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
	set @Index = CHARINDEX (' ',  @SearchString  ,1 ) 
	set @WordToSearch =  rtrim(Left(@SearchString,@Index))

        if @WordToSearch = ''
	begin
	   set @WordToSearch = @SearchString
	end
	
	set @SearchString = replace(@SearchString,@WordToSearch,'')

	if  @WordToSearch  <> '' 
	begin
		set @WordToSearch = replace(@WordToSearch, '  ', ' ')
		set @WordToSearch = replace(@WordToSearch, ' ', '%'' and [HeaderSearch]   like ''%')

		if @Flag = 1  -- begin procedure for First word
		begin

			set @WordToSearch = '[HeaderSearch]    like '' ' + @WordToSearch + '%'''
				
			-- HitNumber = 1 : Means first work on the search  
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT top 1000 Autoid, HeaderDesc ,Chapter_XIX, Accidental, Intentional_Self_Harm, 
			Undetermined_Intent, Adverse_effect_in_therapeutic_use, HeaderId ,SubheaderId,
			SubHeaderId1, SubHeaderId2,SubHeaderId3, HeaderSearch, 1
			FROM Nu_DrugsLast WHERE '
			+ @WordToSearch + '  and subheaderid = 0 order by autoid'
			exec( @SQL)

			-- Add ALL children RELATED to this headerid with HitNumber = 0 
			
			INSERT INTO #T 
			SELECT top 1000 A.Autoid, A.HeaderDesc ,A.Chapter_XIX, A.Accidental, 
			A.Intentional_Self_Harm, A.Undetermined_Intent, A.Adverse_effect_in_therapeutic_use, 
			A.HeaderId ,A.SubheaderId, A.SubheaderId1, A.SubheaderId2, A.SubheaderId3, A.HeaderSearch, 0
			FROM Nu_DrugsLast as A, #T  
			WHERE  A.headerid = #T.headerid and A.subheaderid <> 0 order by A.autoid

			set @Flag = @Flag + 1

		end -- end procedure for First word
		else 
		  begin
			-- Others Words procedure
			set @WordToSearch = '[HeaderSearch]    like ''% ' + @WordToSearch + '%'''
			
			set @SQL = 'UPDATE #T SET HitNumber = ' + cast(@Flag as varchar)  + ' WHERE ' + @WordToSearch 
			exec( @SQL)
		
			set @Flag = @Flag + 1
		  end
		
	end  -- ENDS IF 
   END  -- ENDS WHILE 
END


SELECT DISTINCT  HeaderDesc,Chapter_XIX, Accidental, Intentional_Self_Harm, 
	Undetermined_Intent, Adverse_effect_in_therapeutic_use,HeaderId ,
	SubheaderId, SubheaderId1, SubheaderId2, SubheaderId3, HitNumber, Autoid 
FROM #T order by Autoid








GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO











CREATE                                                 PROCEDURE 
[NU_LookUpNeoplasm_B]
@SearchString  as varchar(800),
@OptionalStmt as varchar(10)
AS
create table #T (
--AutoId int  IDENTITY (1, 1) NOT NULL ,
autoid int ,
HeaderDesc VARCHAR(255),
CodeLink VARCHAR(15),
HeaderId int,
SubHeaderId int,
)

Declare @TempString as varchar(1000)
Declare @FirstWord as varchar(100)
Declare @LeadWord as varchar(100)
Declare @LeadWord1 as varchar(100)
Declare @LeadWord2 as varchar(100)
Declare @LeadWord3 as varchar(100)
Declare @SQL as varchar(5000)
Declare @Index as int

IF @OptionalStmt = '10000' BEGIN
		set @TempString = @SearchString
		set nocount on
		set @LeadWord = ''
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @SearchString = replace(@SearchString,@FirstWord,'')
		if      @FirstWord  <> '' begin
		set @FirstWord = replace(@FirstWord, '  ', ' ')
		set @FirstWord = replace(@FirstWord, ' ', '%'' and [HeaderSearch]   like 
''%')

			set @FirstWord = '[HeaderSearch]    like ''%' + @FirstWord + '%'''
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid, HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_NeoplasmFr WHERE '
			+ @FirstWord + ' order by autoid'
			exec( @SQL)

		end

		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord1 = @FirstWord
		if      @LeadWord1 <> '' begin
		set @LeadWord1 = replace(@LeadWord1, '  ', ' ')
		set @LeadWord1 = replace(@LeadWord1, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord1 = '[HeaderSearch]    like ''%' + @LeadWord1 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT  autoid, HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_NeoplasmFr WHERE '
			+ @LeadWord1 + ' order by autoid'
			exec( @SQL)

		end
		--print 'Second Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord2 = @FirstWord
		if  @LeadWord2 <> '' begin
		set @LeadWord2 = replace(@LeadWord2, '  ', ' ')
		set @LeadWord2 = replace(@LeadWord2, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord2 = '[HeaderSearch]    like ''%' + @LeadWord2 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid,HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_NeoplasmFr WHERE '
			+ @LeadWord2 + ' order by autoid'
			exec( @SQL)

		end
		--print 'Third Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end
		set @LeadWord3 = @FirstWord
		if  @LeadWord3 <> '' begin
		set @LeadWord3 = replace(@LeadWord3, '  ', ' ')
		set @LeadWord3 = replace(@LeadWord3, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord3 = '[HeaderSearch]    like ''%' + @LeadWord3 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid,HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_NeoplasmFr WHERE '
			+ @LeadWord3 + ' order by autoid'
			exec( @SQL)

		--print 'Fourth Word ' + @FirstWord
		end
		SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId  FROM #T order by 
autoid
END 
IF @OptionalStmt = '0' BEGIN
		set @TempString = @SearchString
		set nocount on
		set @LeadWord = ''
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @SearchString = replace(@SearchString,@FirstWord,'')
		if      @FirstWord  <> '' begin
		set @FirstWord = replace(@FirstWord, '  ', ' ')
		set @FirstWord = replace(@FirstWord, ' ', '%'' and [HeaderSearch]   like 
''%')

			set @FirstWord = '[HeaderSearch]    like ''%' + @FirstWord + '%'''
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid, HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_Neoplasm WHERE '
			+ @FirstWord + ' order by autoid'
			exec( @SQL)

		end

		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord1 = @FirstWord
		if      @LeadWord1 <> '' begin
		set @LeadWord1 = replace(@LeadWord1, '  ', ' ')
		set @LeadWord1 = replace(@LeadWord1, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord1 = '[HeaderSearch]    like ''%' + @LeadWord1 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT  autoid, HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_Neoplasm WHERE '
			+ @LeadWord1 + ' order by autoid'
			exec( @SQL)

		end
		--print 'Second Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord2 = @FirstWord
		if  @LeadWord2 <> '' begin
		set @LeadWord2 = replace(@LeadWord2, '  ', ' ')
		set @LeadWord2 = replace(@LeadWord2, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord2 = '[HeaderSearch]    like ''%' + @LeadWord2 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid,HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_Neoplasm WHERE '
			+ @LeadWord2 + ' order by autoid'
			exec( @SQL)

		end
		--print 'Third Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end
		set @LeadWord3 = @FirstWord
		if  @LeadWord3 <> '' begin
		set @LeadWord3 = replace(@LeadWord3, '  ', ' ')
		set @LeadWord3 = replace(@LeadWord3, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord3 = '[HeaderSearch]    like ''%' + @LeadWord3 + '%'''

			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid,HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_Neoplasm WHERE '
			+ @LeadWord3 + ' order by autoid'
			exec( @SQL)

		--print 'Fourth Word ' + @FirstWord
		end
		SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId  FROM #T order by 
autoid
END
-- 		SELECT  HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId   FROM #T
-- 		GROUP BY  HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId
-- 		ORDER BY min(autoid)














GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO













CREATE                                                PROCEDURE 
[NU_LookUpNeoplasm_C]
@SearchString  as varchar(800),
@OptionalStmt as varchar(10)
AS

create table #T (
--AutoId int  IDENTITY (1, 1) NOT NULL ,
autoid int ,
HeaderDesc VARCHAR(255),
CodeLink VARCHAR(15),
HeaderId int,
SubHeaderId int,
)

Declare @TempString as varchar(1000)
Declare @FirstWord as varchar(100)
Declare @LeadWord as varchar(100)
Declare @LeadWord1 as varchar(100)
Declare @LeadWord2 as varchar(100)
Declare @LeadWord3 as varchar(100)
Declare @SQL as varchar(5000)
Declare @Index as int

IF @OptionalStmt = '10000' BEGIN
		set @TempString = @SearchString
		set nocount on
		set @LeadWord = ''
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @SearchString = replace(@SearchString,@FirstWord,'')
		if      @FirstWord  <> '' begin
		set @FirstWord = replace(@FirstWord, '  ', ' ')
		set @FirstWord = replace(@FirstWord, ' ', '%'' and [HeaderSearch]   like 
''%')

			set @FirstWord = '[HeaderSearch]    like ''%' + @FirstWord + '%'''
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_NeoplasmFr WHERE '
			+ @FirstWord + ' AND SUBHEADERID1 = 0 order by autoid'
			--print @SQL
			exec( @SQL)

		end

		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord1 = @FirstWord
		if      @LeadWord1 <> '' begin
		set @LeadWord1 = replace(@LeadWord1, '  ', ' ')
		set @LeadWord1 = replace(@LeadWord1, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord1 = '[HeaderSearch]    like ''%' + @LeadWord1 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_NeoplasmFr WHERE '
			+ @LeadWord1 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			--print @SQL
			exec( @SQL)

		end
		--print 'Second Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord2 = @FirstWord
		if  @LeadWord2 <> '' begin
		set @LeadWord2 = replace(@LeadWord2, '  ', ' ')
		set @LeadWord2 = replace(@LeadWord2, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord2 = '[HeaderSearch]    like ''%' + @LeadWord2 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_NeoplasmFr WHERE '
			+ @LeadWord2 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			 --print @SQL
			exec( @SQL)

		end
		--print 'Third Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end
		set @LeadWord3 = @FirstWord
		if  @LeadWord3 <> '' begin
		set @LeadWord3 = replace(@LeadWord3, '  ', ' ')
		set @LeadWord3 = replace(@LeadWord3, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord3 = '[HeaderSearch]    like ''%' + @LeadWord3 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_NeoplasmFr WHERE '
			+ @LeadWord3 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			--print @SQL
			exec( @SQL)

		--print 'Fourth Word ' + @FirstWord
		end
		SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId  FROM #T order by 
autoid
END





IF @OptionalStmt = '0' BEGIN
		set @TempString = @SearchString
		set nocount on
		set @LeadWord = ''
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @SearchString = replace(@SearchString,@FirstWord,'')
		if      @FirstWord  <> '' begin
		set @FirstWord = replace(@FirstWord, '  ', ' ')
		set @FirstWord = replace(@FirstWord, ' ', '%'' and [HeaderSearch]   like 
''%')

			set @FirstWord = '[HeaderSearch]    like ''%' + @FirstWord + '%'''
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_Neoplasm WHERE '
			+ @FirstWord + ' AND SUBHEADERID1 = 0 order by autoid'
			--print @SQL
			exec( @SQL)

		end

		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord1 = @FirstWord
		if      @LeadWord1 <> '' begin
		set @LeadWord1 = replace(@LeadWord1, '  ', ' ')
		set @LeadWord1 = replace(@LeadWord1, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord1 = '[HeaderSearch]    like ''%' + @LeadWord1 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_Neoplasm WHERE '
			+ @LeadWord1 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			--print @SQL
			exec( @SQL)

		end
		--print 'Second Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end

		set @LeadWord2 = @FirstWord
		if  @LeadWord2 <> '' begin
		set @LeadWord2 = replace(@LeadWord2, '  ', ' ')
		set @LeadWord2 = replace(@LeadWord2, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord2 = '[HeaderSearch]    like ''%' + @LeadWord2 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_Neoplasm WHERE '
			+ @LeadWord2 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			 --print @SQL
			exec( @SQL)

		end
		--print 'Third Word ' + @FirstWord

		set @SearchString = replace(@SearchString,@FirstWord,'')
		set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
		set @Index = CHARINDEX (' ',  @SearchString  ,1 )
		set @FirstWord =  rtrim(Left(@SearchString,@Index))
		   if @FirstWord = ''
			begin
			   set @FirstWord = @SearchString
			end
		set @LeadWord3 = @FirstWord
		if  @LeadWord3 <> '' begin
		set @LeadWord3 = replace(@LeadWord3, '  ', ' ')
		set @LeadWord3 = replace(@LeadWord3, ' ', '%'' and [HeaderSearch]   like 
''%')
		set @LeadWord3 = '[HeaderSearch]    like ''%' + @LeadWord3 + '%'''

			set @SQL = 	'INSERT INTO #T  ' +
			'SELECT autoid , HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM 
NU_Neoplasm WHERE '
			+ @LeadWord3 + 'AND  SUBHEADERID IN (SELECT SUBHEADERID FROM #T) order by 
autoid'
			--print @SQL
			exec( @SQL)

		--print 'Fourth Word ' + @FirstWord
		end
		SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId  FROM #T order by 
autoid
END







































GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO










CREATE         PROCEDURE [NU_LookUpNeoplasm_F]
@SearchString  as varchar(800),
@OptionalStmt as varchar(10)
AS
DECLARE @SQL varchar(2000)
set nocount on
set @SearchString = replace(@SearchString, '  ', ' ')
set @SearchString = replace(@SearchString, ' ', '%'' and [HeaderSearch]   
like ''%')
set @SearchString = '[HeaderSearch]    like ''%' + @SearchString + '%'''
--print @SearchString
IF @OptionalStmt = '0' BEGIN

set @SQL =
'SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM NU_Neoplasm WHERE 
'
+ @SearchString + ' order by autoid'
--print @SQL
exec( @SQL)
END
IF @OptionalStmt = '10000' BEGIN


set @SQL =
'SELECT HeaderDesc ,CodeLink  ,HeaderId ,SubheaderId FROM NU_NeoplasmFr 
WHERE '
+ @SearchString + ' order by autoid'
--print @SQL
set nocount off
exec( @SQL)

END










GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO










CREATE                                           PROCEDURE [NU_LookUpNeoplasmLast_B]
@SearchString  as varchar(800),
@OptionalStmt as varchar(10)
AS

-- Author: Brenda Vargas : Feb 7, 2007
-- Latest Change: 	   Feb 7, 2007
-- Prototype Neoplasm : It will replace the current Sp --> NU_LookUpNeoplasm_B 

--- Aug 21, 2007:
---             Sp renamed.  It was TMP_LookUpNeoplasm_B
---		renamed tmp_Neoplasmlast to NU_Neoplasmlast
--- 		Renamed tmp_NeoplasmFrlast to NU_NeoplasmFrlast 

Create table #T (
Autoid integer, 
HeaderDesc VARCHAR(255),
Malignant_Primary VARCHAR (15),
Malignant_Secondary VARCHAR (15),
In_Situ VARCHAR (15),
Benign VARCHAR (15),
Uncertain_or_Unknown_Behaviour VARCHAR (15),
HeaderId int,
SubHeaderId int,
SubHeaderId1 int, 
SubHeaderId2 int,
SubHeaderId3 int,
SubHeaderId4 int, 
HeaderSearch VARCHAR(255), 
HitNumber int, 
)



Declare @SQL as varchar(5000)
Declare @Index as int
Declare @Flag as int   			 -- use for first word   
Declare @WordToSearch as varchar(100) 

-- French 
if @OptionalStmt = '10000'
BEGIN
    set @Flag = 1 

    WHILE @SearchString <> ' ' 
    begin
	
	set nocount on
	
	set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
	set @Index = CHARINDEX (' ',  @SearchString  ,1 ) 
	set @WordToSearch =  rtrim(Left(@SearchString,@Index))

        if @WordToSearch = ''
	begin
	   set @WordToSearch = @SearchString
	end
	
	set @SearchString = replace(@SearchString,@WordToSearch,'')

	if  @WordToSearch  <> '' 
	begin
		set @WordToSearch = replace(@WordToSearch, '  ', ' ')
		set @WordToSearch = replace(@WordToSearch, ' ', '%'' and [HeaderSearch]   like ''%')

		if @Flag = 1  -- begin procedure for First word
		begin

			set @WordToSearch = '[HeaderSearch]    like '' ' + @WordToSearch + '%'''
				
			-- HitNumber = 1 : Means first work on the search  
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT top 1000 Autoid, HeaderDesc ,Malignant_Primary, Malignant_Secondary, 
			In_Situ, Benign, Uncertain_or_Unknown_Behaviour, HeaderId ,SubheaderId,
			SubHeaderId1, SubHeaderId2,SubHeaderId3, SubHeaderId4, HeaderSearch, 1
			FROM NU_NeoplasmFrLast WHERE '
			+ @WordToSearch + '  and subheaderid1 = 0 order by autoid'
			
			print @sql

			exec( @SQL)

			-- Add ALL children RELATED to this headerid with HitNumber = 0 
			INSERT INTO #T 
			SELECT top 1000 A.Autoid, A.HeaderDesc ,A.Malignant_Primary, A.Malignant_Secondary, 
			A.In_Situ, A.Benign, A.Uncertain_or_Unknown_Behaviour,
			A.HeaderId ,A.SubheaderId, A.SubheaderId1, A.SubheaderId2, A.SubheaderId3, A.SubHeaderId4, A.HeaderSearch, 0
			FROM NU_NeoplasmFrLast as A, #T  
			WHERE  A.headerid = #T.headerid and 
		        A.subheaderid = #T.subheaderid and A.subheaderid1 <> 0 order by A.autoid

			set @Flag = @Flag + 1

		end -- end procedure for First word
		else 
		  begin
			-- Others Words procedure
			set @WordToSearch = '[HeaderSearch]    like ''% ' + @WordToSearch + '%'''
			
			set @SQL = 'UPDATE #T SET HitNumber = ' + cast(@Flag as varchar)  + ' WHERE ' + @WordToSearch 
			exec( @SQL)
		
			set @Flag = @Flag + 1
		  end
		
	end  -- ENDS IF 
   END  -- ENDS WHILE 
END  ---- ENDS FRENCH 

--English 
IF @OptionalStmt = '0' 
BEGIN

    set @Flag = 1 

    WHILE @SearchString <> ' ' 
    begin
	
	set nocount on
	
	set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
	set @Index = CHARINDEX (' ',  @SearchString  ,1 ) 
	set @WordToSearch =  rtrim(Left(@SearchString,@Index))

        if @WordToSearch = ''
	begin
	   set @WordToSearch = @SearchString
	end
	
	set @SearchString = replace(@SearchString,@WordToSearch,'')

	if  @WordToSearch  <> '' 
	begin

		set @WordToSearch = replace(@WordToSearch, '  ', ' ')
		set @WordToSearch = replace(@WordToSearch, ' ', '%'' and [HeaderSearch]   like ''%')

		if @Flag = 1  -- begin procedure for First word
		begin

			set @WordToSearch = '[HeaderSearch]    like ''%' + @WordToSearch + '%'''
				
			-- HitNumber = 1 : Means first work on the search  
			set @SQL = 	'INSERT INTO #T ' +
			'SELECT top 1000 Autoid, HeaderDesc ,Malignant_Primary, Malignant_Secondary, 
			In_Situ, Benign, Uncertain_or_Unknown_Behaviour, HeaderId ,SubheaderId,
			SubHeaderId1, SubHeaderId2,SubHeaderId3, 0,  HeaderSearch, 1    
			FROM NU_NeoplasmLast WHERE '
			+ @WordToSearch + '  and subheaderid1 = 0 order by autoid'   -- Ojo solo para English falta agregar SubHeaderId4
	
			print @SQL

			exec( @SQL)

			-- Add ALL children RELATED to this headerid with HitNumber = 0 
			INSERT INTO #T 
			SELECT top 1000 A.Autoid, A.HeaderDesc ,A.Malignant_Primary, A.Malignant_Secondary, 
			A.In_Situ, A.Benign, A.Uncertain_or_Unknown_Behaviour,
			A.HeaderId ,A.SubheaderId, A.SubheaderId1, A.SubheaderId2, A.SubheaderId3,0, A.HeaderSearch, 0
			FROM NU_NeoplasmLast as A, #T      -- Ojo solo para English falta agregar SubHeaderId4
			WHERE  A.headerid = #T.headerid and 
		        A.subheaderid = #T.subheaderid and A.subheaderid1 <> 0 order by A.autoid

			set @Flag = @Flag + 1

		end -- end procedure for First word
		else 
		  begin
			-- Others Words procedure
			set @WordToSearch = '[HeaderSearch]    like ''% ' + @WordToSearch + '%'''
			
			set @SQL = 'UPDATE #T SET HitNumber = ' + cast(@Flag as varchar)  + ' WHERE ' + @WordToSearch 
			exec( @SQL)
		
			set @Flag = @Flag + 1
		  end
		
	end  -- ENDS IF 
   END  -- ENDS WHILE 
END

SELECT DISTINCT  HeaderDesc,Malignant_Primary, Malignant_Secondary, 
	In_Situ, Benign, Uncertain_or_Unknown_Behaviour, HeaderId ,
	SubheaderId, SubheaderId1, SubheaderId2, SubheaderId3, SubheaderId4, HitNumber, Autoid
FROM #T order by Autoid










GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO











CREATE                                             PROCEDURE [NU_LookUpRangeCode]
		@StartCode  as varchar(15),
		@EndCode  as varchar(15),
		@StartCode2  as varchar(15),  --PR-01658 APPLY ONLY FOR ENGLISH 
		@EndCode2  as varchar(15),    --PR-01658  APPLY ONLY FOR ENGLISH 
		@SwitchFlag as int,
		@OptionalStmt as varchar(10)
 AS	

---- 	EN-00411 add nuc.Flagged for intervention english 

IF @OptionalStmt = '10000' BEGIN

	if  @SwitchFlag = 1
			begin 

 

SELECT nuc.Codeid, 
nuc.ChapterId,   
nuc.HeaderId, 
nuc.SubHeaderId, 
nuc.CodeNum AS [Dispaly Code],  nuc.CodeDesc AS [Description], 
Dagger,  
Asteriks, 
nuc.CodeHeader,  
nuc.SubCodeHeader ,  
nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
nuc.AgeHigh ,
nuc.DiagnosisGender FROM NU_CODESFR nuc WHERE( CODENUM >= @StartCode AND CODENUM <= @EndCode ) 
OR CODENUM LIKE @EndCode + '%' ORDER BY CODENUM
			end
	if  @SwitchFlag = 2 
			begin
SELECT nuc.Codeid, 
nuc.ChapterId,   
nuc.HeaderId, 
nuc.SubHeaderId, 
nuc.CodeNum AS [Dispaly Code],  nuc.CodeDesc AS [Description], 
Dagger,  
Asteriks, 
nuc.CodeHeader,  
nuc.SubCodeHeader ,  
nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
nuc.AgeHigh ,
nuc.DiagnosisGender FROM NU_INTCODESFR nuc  WHERE( CODENUM >= @StartCode AND CODENUM <= @EndCode ) 
OR CODENUM LIKE @EndCode + '%' ORDER BY CODENUM
			end
 

END

----- ED-00758   Add code for english side
-- ED-01642: Add column Canadian to the select 
-- PR-01658 : Add another range to the search  - Two new parameters
            
IF @OptionalStmt = '0' BEGIN

	if  @SwitchFlag = 1
			begin 

 
if @StartCode2 = ''  
Begin

	SELECT nuc.Codeid, 
	nuc.ChapterId,   
	nuc.HeaderId, 
	nuc.SubHeaderId, 
	nuc.CodeNum AS [Dispaly Code],  nuc.CodeDesc AS [Description], 
	Dagger,  
	Asteriks, 
	nuc.CodeHeader,  
	nuc.SubCodeHeader ,  
	nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
	nuc.AgeHigh ,
	nuc.DiagnosisGender,
	nuc.Canadian FROM NU_CODES nuc WHERE(( CODENUM >= @StartCode AND CODENUM <= @EndCode ) 
	OR CODENUM LIKE @EndCode + '%') ORDER BY CODENUM
end 
else 
begin 
	SELECT nuc.Codeid, 
	nuc.ChapterId,   
	nuc.HeaderId, 
	nuc.SubHeaderId, 
	nuc.CodeNum AS [Dispaly Code],  nuc.CodeDesc AS [Description], 
	Dagger,  
	Asteriks, 
	nuc.CodeHeader,  
	nuc.SubCodeHeader ,  
	nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
	nuc.AgeHigh ,
	nuc.DiagnosisGender,
	nuc.Canadian FROM NU_CODES nuc WHERE(( CODENUM >= @StartCode AND CODENUM <= @EndCode ) 
	OR CODENUM LIKE @EndCode + '%') 
	-- PR-01658
	OR (( CODENUM >= @StartCode2 AND CODENUM <= @EndCode2 )   
	OR CODENUM LIKE @EndCode2 + '%') 
	ORDER BY CODENUM
end 

			end
	if  @SwitchFlag = 2 
			begin
SELECT nuc.Codeid, 
nuc.ChapterId,   
nuc.HeaderId, 
nuc.SubHeaderId, 
nuc.CodeNum AS [Dispaly Code],  nuc.CodeDesc AS [Description], 
Dagger,  
Asteriks, 
nuc.CodeHeader,  
nuc.SubCodeHeader ,  
nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
nuc.AgeHigh ,
nuc.DiagnosisGender, 
-- 	EN-00411
nuc.Flagged 
 FROM NU_INTCODES nuc  WHERE( CODENUM >= @StartCode AND CODENUM <= @EndCode ) 
OR CODENUM LIKE @EndCode + '%' ORDER BY CODENUM
			end
 

END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



















CREATE                                            PROCEDURE [NU_LookUpRangeMorph]
		@StartCode  as varchar(15),
		@EndCode  as varchar(15),
		@SwitchFlag as int,
		@OptionalStmt as varchar(10)
 AS	



IF @OptionalStmt = '10000' BEGIN

	if  @SwitchFlag = 1
			begin 

	SELECT nuc.Codeid, 
	nuc.ChapterId,   
	nuc.HeaderId, 
	nuc.SubHeaderId, 
	nuc.CodeNum AS [Dispaly Code],  nuc.CodeDesc AS [Description], 
	Dagger,  
	Asteriks, 
	nuc.CodeHeader,  
	nuc.SubCodeHeader ,  
	nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
	nuc.AgeHigh ,
	nuc.DiagnosisGender FROM NU_CODESFR nuc
        WHERE( CODENUM liKE '%/3%' OR  CODENUM LIKE '%/6%'  ) 
	ORDER BY CODENUM
        end
	 
END

IF @OptionalStmt = '0' BEGIN

	if  @SwitchFlag = 1
	begin 

	SELECT nuc.Codeid, 
	nuc.ChapterId,   
	nuc.HeaderId, 
	nuc.SubHeaderId, 
	nuc.CodeNum AS [Dispaly Code],  nuc.CodeDesc AS [Description], 
	Dagger,  
	Asteriks, 
	nuc.CodeHeader,  
	nuc.SubCodeHeader ,  
	nuc.ICDNotes ,isnull( nuc.AgeLow,150) as Age  ,
	nuc.AgeHigh ,
	nuc.DiagnosisGender,
	nuc.Canadian  FROM NU_CODES nuc
        WHERE( CODENUM liKE '%/3%' OR  CODENUM LIKE '%/6%'  ) 
	ORDER BY CODENUM
	end

	 
END









GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO













CREATE    PROCEDURE [NU_Security]
	@Coder as int, --Internal coder number
	@Users as int, --Number of users allowed
	@YesNo as bit output--Return 1 for OK, 0 for not OK
AS

	if @Coder <= 2 
		Set @YesNo = 1
	else
	begin
		If (select count(*) from M_NCoder where userid = @Coder) = 1
		 	Set @YesNo = 1
		Else If @Users >= (select count(*) from M_NCoder) + 1
		Begin
			Insert into M_NCoder Values (@coder, getdate(),1)
			Set @YesNo = 1
		End
		Else
		Begin
			Insert into M_NCoder Values (@coder, getdate(),1)  -- PR - 04003 added 
			Set @YesNo = 1 -- PR - 04003 Set @YesNo = 0
		End

	end











GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO












CREATE   PROCEDURE [NU_StandAloneSecurity]
	@Coder as varchar(50), --Internal coder number
	@Users as int, --Number of users allowed
	@YesNo as bit output--Return 1 for OK, 0 for not OK
AS
	If (select count(*) from M_NCoder where stdalnuser = @Coder) = 1
	 	Set @YesNo = 1
	Else If @Users >= (select count(*) from M_NCoder) + 1
	Begin
		Insert into M_NCoder Values (0, getdate(),@coder)
		Set @YesNo = 1
	End
	Else
		Set @YesNo = 0












GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO












CREATE    PROCEDURE [NU_TopXDiagInterv]
	@CareType as int,
	@Months as int,
	@TopX as int, 
	@DiagInterv as int, --1 for Diagnosis, 2 for Intervention
	@Userid as int = 0
AS
	Declare @SQL as VarChar(1000)
	Declare @SQL2 as VarChar(100)
	If @Userid = 0
		Set @SQL2 = ''
	Else
		Set @SQL2 = ' and CoderNumber = ' + Cast(@Userid as Varchar(7))
	If @DiagInterv = 1
		Set @SQL  = 'SELECT TOP ' + cast(@TopX as varchar(4)) + ' dbo.AB_Diagnosis.DiagnosisCode AS [ ], COUNT(dbo.AB_Diagnosis.DiagnosisCode) AS Occurrences, dbo.ICD_DiagFile10.DisplayCode, 
			dbo.ICD_DiagFile10.UserDescription
		FROM dbo.AB_Diagnosis LEFT OUTER JOIN
			dbo.ICD_DiagFile10 ON dbo.AB_Diagnosis.DiagnosisCode = dbo.ICD_DiagFile10.Code RIGHT OUTER JOIN
			dbo.AB_Abstract ON dbo.AB_Diagnosis.AbstractID = dbo.AB_Abstract.AbstractID
		WHERE     (dbo.AB_Abstract.CareType = ' + cast(right(@CareType, 1) as varchar(1)) + ') AND (dbo.AB_Abstract.ICDType = ''T'') AND (dbo.AB_Abstract.DischargeDate >= 
		DATEADD ( m , - ' + cast(@Months as varchar(2)) + ', getdate() ) )' + @SQL2 + ' 
		GROUP BY dbo.AB_Diagnosis.DiagnosisCode, dbo.ICD_DiagFile10.DisplayCode, dbo.ICD_DiagFile10.UserDescription
		ORDER BY COUNT(dbo.AB_Diagnosis.DiagnosisCode) DESC'
	Else
		Set @SQL  = 'SELECT TOP ' + cast(@TopX as varchar(4)) + ' dbo.AB_Intervention.IntervCode AS [ ], COUNT(dbo.AB_Intervention.IntervCode) AS Occurrences, dbo.ICD_ProcFile10.DisplayCode, 
			dbo.ICD_ProcFile10.UserDescription
		FROM dbo.AB_Intervention LEFT OUTER JOIN
			dbo.ICD_ProcFile10 ON dbo.AB_Intervention.IntervCode = dbo.ICD_ProcFile10.Code RIGHT OUTER JOIN
			dbo.AB_Abstract ON dbo.AB_Intervention.AbstractID = dbo.AB_Abstract.AbstractID
		WHERE     (dbo.AB_Abstract.CareType = ' + cast(right(@CareType, 1) as varchar(1)) + ') AND (dbo.AB_Abstract.ICDType = ''T'') AND (dbo.AB_Abstract.DischargeDate >= 
		DATEADD ( m , - ' + cast(@Months as varchar(2)) + ', getdate() ) )' + @SQL2 + ' 
		GROUP BY dbo.AB_Intervention.IntervCode, dbo.ICD_ProcFile10.DisplayCode, dbo.ICD_ProcFile10.UserDescription
		ORDER BY COUNT(dbo.AB_Intervention.IntervCode) DESC'
	Exec(@SQL)












GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [NU_UpdateUserRule]
	(@GuidelineID as [int],
	@StartCode as [varchar] (20),
	@EndCode as [varchar] (20),
	@MultipleOcc as [int],
	@MessageText as [nvarchar] (500) ,
	@ErrorLevel as [int],
	@ValidFrom as [smalldatetime],
	@ValidTo as [smalldatetime],
	@IsInclude as [int],
	@GuidelinkID as [int],
	@RuleStartCode as [varchar] (20),
	@RuleEndCode as [varchar] (20),
	@DiagTypeID as [nvarchar] (12))
AS 


UPDATE  [NU_UserGuidelines] 
	SET 	[StartCode] 	=	@StartCode,
		[EndCode] 	=	@EndCode,
		[MultipleOcc]	=	@MultipleOcc,
		[MessageText]	=	@MessageText,
		[ErrorLevel]	=	@ErrorLevel,
		[ValidFrom]	=	@ValidFrom,
		[ValidTo]	=	@ValidTo
WHERE 
		([GuidelineID]	= @GuidelineID) 


UPDATE  [NU_UserGuidelineLink] 
	SET 	[StartCode] 	=	@RuleStartCode,
		[EndCode] 	=	@RuleEndCode,
		[IsInclude]	=	@IsInclude,
		[IsMandatory]	=	@MultipleOcc,
		[DiagTypeID]	=	@DiagTypeID
WHERE 
		([GuidelineLinkID]	= @GuidelinkID) 




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- This is called by Amcare ICD 10 to display the List of Errors CIHI returns.
--Ticket 10393, add BatchYear to M_AmcareErrors table
CREATE   PROCEDURE [P_AmcareCIHIErrorList]
	@AbstractID AS INT
AS 
SELECT distinct
[ ] = AB_NACRS10_Errors.AbstractID
, [Err #] = dbo.M_AmcareErrors.ErrorNumber
, [Error] = dbo.M_AmcareErrors.ErrorDescription
, [CIHI File] = dbo.AB_NACRS10_Errors.ErrorFileName
FROM dbo.AB_NACRS10_Errors 
    join AB_Abstract on AB_NACRS10_Errors.AbstractID = AB_Abstract.AbstractID
    JOIN dbo.M_AmcareErrors 
    ON RTRIM(LTRIM(dbo.AB_NACRS10_Errors.ErrorID)) = RTRIM(LTRIM(dbo.M_AmcareErrors.ErrorNumber)) 
        and (case when AB_Abstract.BatchYear < 2004 then 2004 else AB_Abstract.BatchYear end) = M_AmcareErrors.BatchYear 
WHERE dbo.AB_NACRS10_Errors.AbstractID = @AbstractID


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE  PROCEDURE [P_ChangeCCRS_AssessType]
	@RecordID 	int,
	@NewAA8	int
AS 
	DECLARE @OldAA8 AS INT
	SELECT @OldAA8 = AA8 FROM CRS_Demographic WHERE AbstractID = @RecordID
	UPDATE CRS_Demographic SET AA8 = @NewAA8 WHERE AbstractID = @RecordID
	
	--If it was a Full and is now a Qtr then we need to remove the Full field values from the record
	IF @OldAA8 IN (14503, 14504, 14505) AND @NewAA8 IN (14506, 14511)
	BEGIN
		UPDATE CRS_AssessShare2 SET G2B = 0, G6c = 0, G6d = 0, G6e = 0, H2a = 0, H2b = 0, H3e = 0, H3f = 0, H3g = 0, H3h = 0 WHERE AbstractID = @RecordID
		UPDATE CRS_AssessShare3 SET I1b = 0, I1c = 0, I1d = 0, I1e = 0, I1f = 0, I1g = 0, I1h = 0, I1i = 0, I1j = 0, I1k = 0, I1l = 0, I1n = 0, I1o = 0, I1p = 0, I1r = 0, I1z = 0, I1aa = 0, I1cc = 0, I1dd = 0, I1ee = 0, I1ff = 0, I1jj = 0, I1kk = 0, I1ll = 0, I1mm = 0, I1nn = 0, I1oo = 0, I1pp = 0, I1qq = 0, I1rr = 0, I1uu = 0 WHERE AbstractID = @RecordID
		UPDATE CRS_AssessShare4 SET K1c = 0, K4a = 0, K4b = 0, K5c = 0, K5d = 0, K5e = 0 WHERE AbstractID = @RecordID
	
		DELETE FROM CRS_AssessFull1 WHERE AbstractID = @RecordID
		DELETE FROM CRS_AssessFull2 WHERE AbstractID = @RecordID
	END
	
	--If it was a Qtr and is now a Full then we need to Add blank Full records to the Full only tables
	IF @OldAA8 IN (14506, 14511) AND @NewAA8 IN (14503, 14504, 14505)
	BEGIN
		EXEC I_CRS_AssessFull1 @RecordID, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
		EXEC I_CRS_AssessFull2 @RecordID, 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
	END



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE  PROCEDURE [P_ChangeOMHRS_AssessType]
	@RecordID 	int,
	@NewZ1	int,
    @NewApp int
AS 
	update OMHRS_SecAA set Z1 = @NewZ1, AppID = @NewApp where AbstractID = @RecordID	


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE  PROCEDURE [P_Check_CLLoan]
--Check if a chart is still on loan
	@VolumeID as int,
	@ActivityID as int output
AS 

	Set @ActivityID = (SELECT Top 1 CLActivityID FROM dbo.CL_Activity 
	WHERE (VolumeID = @VolumeID) AND (ActivityType = 1) AND ActivityDateIn IS NULL)

	Return 0




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [P_Check_CLRequest]
	--Check to see if there are outstanding requests for a chart.
	@VolumeID as int, 
    @HospID as int
AS 

SELECT  
    CL.CLActivityID as [ ], 
    ISNULL(CL.HospitalID, 0) as [ ],
    H.UserDescription as [Request Hospital],
    B.UserDescription AS [Borrower], 
    L.UserDescription AS [Location],
    CONVERT(varchar(10), CL.ActivityExpectedReturn, 111) AS [Expected Return], 
    CONVERT(varchar(10), CL.ActivityDateOut, 111) AS [Date From], 
    CONVERT(varchar(5), CL.ActivityTimeOut, 14) AS [Time From], 
    (SELECT UserDescription FROM LoanLU_Location WHERE LoanLU_Location.Code = (select ClCurrentLocation from cm_cpi_volume v where v.VolumeID = @VolumeID)) AS [Current Location],
    RP.UserDescription AS [Request Priority],
    L_RP.UserDescription AS [Location Priority],
    B_RP.UserDescription AS [Borrower Priority]
FROM         dbo.CL_Activity CL
    left join LoanLU_RequestPriority RP on CL.CLRequestPriority = RP.Code
    left join LoanLU_Borrower B on CL.ActivityBorrower = B.Code
    left join LoanLU_Location L on CL.ActivityLocation = L.Code
    left join LoanLU_RequestPriority B_RP on B.CLRequestPriority = B_RP.Code
    left join LoanLU_RequestPriority L_RP on L.CLRequestPriority = L_RP.Code
    left join H_HospitalProfile H on CL.HospitalID = H.Code
WHERE     (CL.VolumeID = @Volumeid) AND (CL.ActivityType = 4)
   	AND (ISNULL(CL.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(CL.HospitalID, 0) end)
ORDER BY 
(case when isnull(RP.PriorityRate, 0) > isnull(B_RP.PriorityRate, 0) 
      then (case when isnull(RP.PriorityRate, 0) > isnull(L_RP.PriorityRate, 0) then RP.PriorityRate else isnull(L_RP.PriorityRate, 0) end)
      else (case when isnull(L_RP.PriorityRate, 0) > isnull(B_RP.PriorityRate, 0)then L_RP.PriorityRate else isnull(B_RP.PriorityRate, 0) end)
 end) desc, 
CONVERT(varchar(10), CL.ActivityDateOut, 111) 

Return 0




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE   PROCEDURE [P_Check_DeficiencyActivity]
--Check if a deficiency is activity, when a chart move to permanent loaction
	@VolumeID as int,
	@DefActivity as int output
AS 

    set @DefActivity = (select count(DefeciencyID) from Def_SlipMain M 
                            inner join DefLU_ChartStatus S on M.DefMainStatus = S.Code
                            inner join CM_CPI_Volume V on M.DefVolumeID = V.VolumeID 
                        where S.DisplayCode not in ('C', 'X') and 
                            M.DefVolumeID = @VolumeID)
    if @DefActivity is null set @DefActivity = 0
	Return 0





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [P_Check_OMHRS_Admission_A1]
    @ChartNumber varchar(10),
    @InstitutionNumber int,
    @AA3 varchar(20),
    @A1 datetime
as
declare @return int
declare @A1_Admission datetime

set @return = 0
select @A1_Admission = A1 from dbo.OMHRS_SecAA 
            inner join dbo.OMHRS_SecA on OMHRS_SecAA.AbstractID = OMHRS_SecA.AbstractID
            where OMHRS_SecAA.ChartNumber = @ChartNumber 
                and OMHRS_SecAA.InstitutionNumber = @InstitutionNumber
                and OMHRS_SecAA.AA3 = @AA3
                and Z1 = 200373 --Full admission

if isnull(@A1_Admission, '1900/01/01') > @A1 set @return = 1

return @return
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [P_Check_OMHRS_LastX80]
    @ChartNumber varchar(10),
    @InstitutionNumber int,
    @AdmitDate datetime
as
declare @return int
declare @X80 datetime
declare @CC1 datetime

set @return = 0
select @X80 = max(X80), @CC1 = max(AdmitDate) 
from dbo.OMHRS_SecAA 
        left  join dbo.OMHRS_SecS on OMHRS_SecAA.AbstractID = OMHRS_SecS.AbstractID
        inner join dbo.OMHRS_RecInfo on OMHRS_SecAA.AbstractID = OMHRS_RecInfo.AbstractID
where OMHRS_SecAA.ChartNumber = @ChartNumber 
    and OMHRS_SecAA.InstitutionNumber = @InstitutionNumber
    and OMHRS_RecInfo.IsSubmited = 1 and OMHRS_RecInfo.IsDeleted = 2
if isnull(@X80, '1900/01/01') > @AdmitDate or @CC1 > @AdmitDate set @return = 1

return @return
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE  PROCEDURE [P_Check_ProviderSuspend]
--Check if a provider is in suspend situation
	@BorrowNumber as int
AS 

    select top 1 DateFrom, DateTo 
    from LLU_Provider_Suspention S
        inner join LU_Provider P on S.ProviderID = P.Code
    where P.ProvdrBorrower = @BorrowNumber and 
          getdate() between DateFrom and DateTo

	Return 0




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE  PROCEDURE [P_CheckAbsComplete]
AS 

DECLARE @IsComplete INT

SELECT @IsComplete = IsCompleted
FROM AB_Abstract 
WHERE IsCompleted <> 1 

RETURN @IsComplete




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [P_CheckALCLOS]
	@AbstractID int
as
	--PR - 04643 sometime the ALCLOS of Abstract is not match the ALC LOS in patient service table
	--By now, we do not call from WinRecs.
	declare @ALCLOS int, @ALCLOS_ABS int
	
	set @ALCLOS = (select top 1 ServiceDays from dbo.AB_PatientService
						inner join LU_PatientService on PatientService = Code
					where AbstractID = @AbstractID and LU_PatientService.CIHIValue like '99%')
	if @ALCLOS > 0 
	begin
		set @ALCLOS_ABS = (select ALCLOS from AB_Abstract where AbstractID = @AbstractID)

		if @ALCLOS <> isnull(@ALCLOS_ABS, 0)
			Update AB_Abstract
			set ALCLOS = @ALCLOS, AcuteLos = LosDays - @ALCLOS
			where AbstractID = @AbstractID
	end
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE   PROCEDURE [P_CheckBasicOption]
	@InstitutionNumber AS INT,
	@BOPNumber AS INT,
	@BOPState AS INT OUTPUT
AS 

    select @BOPState = case @BOPNumber
        when 1  then BOP_State1 
        when 2  then BOP_State2 
        when 3  then BOP_State3 
        when 4  then BOP_State4 
        when 5  then BOP_State5 
        when 6  then BOP_State6 
        when 7  then BOP_State7 
        when 8  then BOP_State8 
        when 9  then BOP_State9 
        when 10 then BOP_State10
        when 11 then BOP_State11
        when 12 then BOP_State12
        when 13 then BOP_State13
        when 14 then BOP_State14
        when 15 then BOP_State15
        when 16 then BOP_State16
        when 17 then BOP_State17
        when 18 then BOP_State18
        when 19 then BOP_State19
    end
    from H_InstitutionProfile where Code = @InstitutionNumber






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_CheckCCDiagnosisStaging]
	@DiagCode 	AS VARCHAR(10), 
	@Clinical	AS VARCHAR(50),
    @SearchDate as varchar(10)
AS 
	
	select CODE 
    from LLU_CC_SITE_GROUP 
    where icd10ca like @DiagCode AND AJCC_SITE_GRP  like  @Clinical
        and @SearchDate between validfrom and validto --ED - 01905
	RETURN @@RowCount




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE  PROCEDURE [P_CheckCCRecordExists]
	@LinkID 	AS INT
AS 
	select CC_Demographic.AbstractID  	from CC_Demographic, CC_NDFP
	where AppID = 676 and CC_Demographic.LinkID = @LinkID and CC_Demographic.AbstractID = CC_NDFP.AbstractID


	RETURN @@RowCount



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [P_CheckCCTopoStaging]
	@TopoCode 	AS VARCHAR(10), 
	@Clinical	AS int ,
    @SearchDate as varchar(10), 
    @Version    as varchar(10) 
AS 
	-- PR - 05045: New edits based on Topo code instead of DiagCode
	-- Now there are 2 AJCC: Versions 6 and 7 
	
	    SELECT distinct gp.ICD10CA
		FROM LLU_CC_SITE_GROUP gp, LLU_CC_STAGE_VALUE t2 
		WHERE gp.AJCC_SITE_GRP =   t2.AJCC_SITE_GRP 
		AND gp.STAGEABLE = 'Y' 
		AND gp.Staging_Version = @Version
        AND gp.ICD10CA = @TopoCode
        AND t2.AJCC_SITE_GRP  like ( select AJCC_SITE_GRP  from  LLU_CC_STAGE_VALUE where Code = @Clinical ) 
        AND @SearchDate between gp.validfrom and gp.validto 

	RETURN @@RowCount


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [P_CheckCPIDeleteOK]
	@PatientID as Int,
	@HospID as int = 0
AS 

	declare @CNT as int
	declare @ChartNumber as varchar(10)
		
	set @ChartNumber = (select Top 1 ChartNumber from CM_CPI where PatientID = @PatientID)

	--VISIT HISTORY PR-00468 (PR-00838 excluded the CPI record in the VH)
	select @CNT = count(ChartNumber) from AB_Main where AppID <> 0 and ChartNumber = @ChartNumber and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)

	--ABSTRACTING
	if @CNT <= 0 select @CNT = count(ChartNumber) from AB_Abstract where ChartNumber = @ChartNumber and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	
	--REHAB
	if @CNT <= 0 select @CNT = count(ChartNumber) from RH_ClientInfo where ChartNumber = @ChartNumber and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)

	--CCRS -- PR-00468
	if @CNT <= 0 select @CNT = count(ChartNumber) from CRS_Demographic where ChartNumber = @ChartNumber and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)

	--OMHRS -- PR-00468
	if @CNT <= 0 select @CNT = count(ChartNumber) from OMHRS_SecAA where ChartNumber = @ChartNumber and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)

	--CLINIC
	if @CNT <= 0 select @CNT = count(ChartNumber) from CR_Demographic where ChartNumber = @ChartNumber --and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)

	--ROI 
	if @CNT <= 0 select @CNT = count(ChartNumber) from ROI_Main where ChartNumber = @ChartNumber --and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)

	--CHART DEFICIENCY
	if @CNT <= 0 select @CNT = count(DefPatientID) from Def_SlipMain where DefPatientID = @PatientID and DefMainStatus <> 11 --PR - 02842

	--CHART LOCATor (PULL LISTS)
	if @CNT <= 0 select @CNT = count(VolumeID) from CL_PullList where VolumeID IN (select VolumeID from CM_CPI_Volume where PatientID = @PatientID and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end))
	
	return @CNT


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO






-- Called by Diagnosis Multi-Form to detemine if Diagnosis Code can be on Main Line.
CREATE     PROCEDURE [P_CheckDiagnosisM]
	@DiagnosisNumber as int,
	@ICDType as VarChar(1),
	@CareType as VarChar(10), --PR-04819
	@DiagPass as VarChar(1) Output
AS 

set @DiagPass = 'N'

if @ICDType = '9'
begin
	if exists (select Code from ICD_DiagFile9 where Code = @DiagnosisNumber and (MRDxFlag = 'Y' or (MRDxFlag = 'A' and @CareType = '5')))
		set @DiagPass = 'Y'		
end
else if @ICDType = 'C'
begin
	if exists (select Code from ICD_DiagFile9cm where Code = @DiagnosisNumber and (MRDxFlag = 'Y' or (MRDxFlag = 'A' and @CareType = '5')))
		set @DiagPass = 'Y'
end
else if @ICDType = 'T'
begin
	if exists (select Code from ICD_DiagFile10 where Code = @DiagnosisNumber and (MRDxFlag = 'Y' or (MRDxFlag = 'A' and (@CareType in ('105', '5')))))
		set @DiagPass = 'Y'
end

return 0



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- Looks for the CareType of Institution Number
CREATE PROCEDURE [P_CheckInstitutionCareType]
	@InstitutionNumber 	AS INTEGER,
	@CareType  		AS INTEGER
AS 

	SELECT Code FROM H_InstitutionProfile WHERE Code = @InstitutionNumber AND AssociationID = @CareType
	RETURN  @@RowCount




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Looks for the CIHI Code in a Look Up Table. Called by LOOK UP CIHI
CREATE     PROCEDURE [P_CheckLUCIHICode]
	@SearchTable AS VarChar(50), 
	@SearchString AS VarChar(50),
	@UseDate as varchar(10),
	@HospID as varchar(100) = '0'
AS 

--PR-02277 [Added Valid Dates & Hospital Link to the search criteria]
declare @SQL as varchar(1000)
select @SQL = 'select CihiValue from ' + @SearchTable + 
		' where CihiValue like ''%' + @SearchString + '%''' +
		' and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
if isdate(@UseDate) = 1 select @SQL = @SQL + ' and ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo]) ' 
	
execute (@SQL)
return @@RowCount
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO








-- Looks for the CIHI Code in a Look Up Table. Called by LOOK UP CIHI
CREATE     PROCEDURE [P_CheckLUCIHICodeCF]
	@LookUpID AS int, 
	@SearchString AS VarChar(50),
	@UseDate as varchar(10),
	@HospID as int = 0
AS 

--PR-02277 [Added Valid Dates & Hospital Link to the search criteria]
if isdate(@UseDate) = 1 
	select CIHIValue 
	from LU_CodeFile 
	where LookUpID = @LookUpID 
	and CIHIValue like '%' + @SearchString + '%'
	and ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end) 

else
	select CIHIValue 
	from LU_CodeFile 
	where LookUpID = @LookUpID 
	and CIHIValue like '%' + @SearchString + '%'
	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end) 

return @@RowCount







GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Looks for the Display Code in a Look Up Table. Called by LOOK UP MAIN / LOOK UP ASSOCIATE
CREATE     PROCEDURE [P_CheckLUDisplayCode]
	@SearchTable AS VarChar(50), 
	@SearchString AS VarChar(50),
	@UseDate as varchar(10),
	@HospID as varchar(100) = '0'
AS 
--20585 duplicate ICD_EDInterventionValueSet value
--PR-02277 [Added Valid Dates & Hospital Link to the search criteria]
declare @SQL as varchar(1000)
select @SQL = 'select DisplayCode from ' + @SearchTable + 
		(case when @SearchTable = 'ICD_EDInterventionValueSet' 
			  then ' where replace(replace(DisplayCode, ''.'', ''''), ''-'', '''') like ''%' + replace(replace(@SearchString, '.', ''), '-', '') + '%'''
			  else ' where DisplayCode like ''%' + @SearchString + '%''' 
		end) +
		(case when len(@HospID) > 0 and @HospID <> '0' then ' and (isnull(HospitalID, 0) = 0 or HospitalID = ' + @HospID + ')' else '' end) 
		--' and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '

if isdate(@UseDate) = 1 select @SQL = @SQL + ' and ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo]) ' 
--print @sql
execute(@SQL)
return @@RowCount
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO







-- Looks for the Display Code in a Look Up Table. Called by LOOK UP MAIN / LOOK UP ASSOCIATE
CREATE    PROCEDURE [P_CheckLUDisplayCodeCF]
	@LookUpID AS int, 
	@SearchString AS VarChar(50),
	@UseDate as varchar(10),
	@HospID as int = 0
	
AS 

--PR-02277 [Added Valid Dates & Hospital Link to the search criteria]
if isdate(@UseDate) = 1 
	select DisplayCode 
	from LU_CodeFile 
	where LookUpID = @LookUpID 
	and DisplayCode like '%' + @SearchString + '%'
	and ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end) 
else
	select DisplayCode 
	from LU_CodeFile 
	where LookUpID = @LookUpID 
	and DisplayCode like '%' + @SearchString + '%'
	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end) 

return @@RowCount


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [P_CheckMergeParent]
    @SourceChart int, @TargetChart int  --PR - 03348
--    @SourceChart varchar(10), @TargetChart varchar(10), @HospitalID int
as 
    declare @count int

    set @count = (select count(*) from
        (select masterchart from cm_cpi 
        where PatientID = @TargetChart ) t 	
        inner join
        (select patientid from cm_cpi 
        where PatientID = @SourceChart ) s 	
        on t.masterchart = s.PatientID)
    if isnull(@count, 0) = 0
    set @count = 0 - (select count(*) from
        (select patientid from cm_cpi 
        where PatientID = @TargetChart ) t 	
        inner join
        (select masterchart from cm_cpi 
        where PatientID = @SourceChart ) s 	
        on s.masterchart = t.PatientID)


--    set @count = (select count(*) from
--        (select masterchart from cm_cpi 
--        where ChartNumber = @TargetChart 
--            AND (ISNULL(HospitalID, 0) = 0 OR @HospitalID = case @HospitalID when 0 then 0 else ISNULL(HospitalID, 0) end)) t 	
--        inner join
--        (select patientid from cm_cpi 
--        where ChartNumber = @SourceChart 
--            AND (ISNULL(HospitalID, 0) = 0 OR @HospitalID = case @HospitalID when 0 then 0 else ISNULL(HospitalID, 0) end)) s 	
--        on t.masterchart = s.PatientID)
--    if isnull(@count, 0) = 0
--    set @count = 0 - (select count(*) from
--        (select patientid from cm_cpi 
--        where ChartNumber = @TargetChart 
--            AND (ISNULL(HospitalID, 0) = 0 OR @HospitalID = case @HospitalID when 0 then 0 else ISNULL(HospitalID, 0) end)) t 	
--        inner join
--        (select masterchart from cm_cpi 
--        where ChartNumber = @SourceChart 
--            AND (ISNULL(HospitalID, 0) = 0 OR @HospitalID = case @HospitalID when 0 then 0 else ISNULL(HospitalID, 0) end)) s 	
--        on s.masterchart = t.PatientID)
    return (isnull(@count, 0))
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [P_CheckNTAuthority](
    @Code int, @NTAuthority varchar(100), @HospitalID int)
AS 
declare @value int
set @value = 0
if (select count(*) from H_HospitalProfile) > 1
    set @value = (select count(*) from U_Users where Code <> @Code and NTAuthority = @NTAuthority and HospitalID <> @HospitalID)
return (@value)

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO









-- Looks for the Code in a NU Look Up Table. Called by LOOK UP NU
CREATE PROCEDURE [P_CheckNUCode]
	@SearchTable AS VarChar(50), 
	@SearchString AS VarChar(50)
AS 

	DECLARE @SQL AS VarChar(100)

	select @SQL = 'select * from ' + @SearchTable + ' where CodeNum like ''%' + @SearchString + '%'''
	EXECUTE(@SQL)
	RETURN  @@RowCount








GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [P_CheckPreviouPassword]
	@UserID int, @UserPassword varchar(20), @IsDuplicated int output
as

declare @Password varchar(50)
set @Password = replace(isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 1, 1)) - 10), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 2, 1)) - 11), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 3, 1)) - 12), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 4, 1)) - 13), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 5, 1)) - 14), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 6, 1)) - 15), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 7, 1)) - 16), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 8, 1)) - 17), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 9, 1)) - 18), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 10, 1)) - 19), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 11, 1)) - 20), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 12, 1)) - 21), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 13, 1)) - 22), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 14, 1)) - 23), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 15, 1)) - 24), ''), '               ', '')
if exists (select * from dbo.U_Users_Password where	UserID = @UserID and UserPassword = @Password)
	set @IsDuplicated = 1
else
	set @IsDuplicated = 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE   PROCEDURE [P_CheckProjectQuestion]
	@ProjectNumber AS INT,
	@QuestionNumber AS INT,
	@QuestionState AS INT OUTPUT
AS 
 
    select @QuestionState = (
        case @QuestionNumber
            when 1  then QuestionState1 
            when 2  then QuestionState2 
            when 3  then QuestionState3 
            when 4  then QuestionState4 
            when 5  then QuestionState5 
            when 6  then QuestionState6 
            when 7  then QuestionState7 
            when 8  then QuestionState8 
            when 9  then QuestionState9 
            when 10 then QuestionState10
            when 11 then QuestionState11
            when 12 then QuestionState12
            when 13 then QuestionState13
            when 14 then QuestionState14
            when 15 then QuestionState15
            when 16 then QuestionState16
            when 17 then QuestionState17
            when 18 then QuestionState18
            when 19 then QuestionState19
            when 20 then QuestionState20
            when 21 then QuestionState21
            when 22 then QuestionState22
            when 23 then QuestionState23
            when 24 then QuestionState24
        end )
    from LU_Project where Code = @ProjectNumber






GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE  PROCEDURE [P_CheckRehabAdmitValue]
	@FieldName AS VARCHAR(255),
	@TableName AS VARCHAR(255),
	@AbstractID AS VARCHAR(15)
AS 

	DECLARE @SQL VarChar(800)	
	SET @SQL = 'SELECT ' + @FieldName + ' FROM ' + @TableName + ' WHERE AbstractID = ' + @AbstractID
	EXECUTE (@SQL)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE   PROCEDURE [P_CheckRehabDischValue]
	@FieldName AS VARCHAR(255),
	@TableName AS VARCHAR(255),
	@LinkID AS VARCHAR(15)
AS 

	declare @SQL varchar(800)	
	if upper(@TableName) = 'RH_CLIENTINFO'
		set @SQL = 'select ' + @FieldName + ' from ' + @TableName + ' where AssessmentType = 135 and LinkID = ' + @LinkID
	else
		set @SQL = 'select ' + @FieldName + ' from ' + @TableName + ' where AbstractID = (select AbstractID from RH_ClientInfo where AssessmentType = 135 and LinkID = ' + @LinkID + ')'

	execute (@SQL)


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE  PROCEDURE [P_CheckRehabRecordExists]
	@LinkID 	AS INT, 
	@CheckType 	AS INT
AS 
	DECLARE @Type AS INT
	SET @Type = 135
	IF @CheckType = 1 SET @Type = 136

	SELECT AbstractID FROM RH_ClientInfo WHERE LinkID = @LinkID AND AssessmentType = @Type
	RETURN @@RowCount



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE     PROCEDURE [P_CheckUniqueMISCode]
	@MISCode AS INT,
	@AbstractID AS INT,
	@Encounter AS VARCHAR(20)
AS 
	Declare @SQL as NVarchar(4000)
	Declare @CNCount as varchar(6)
	Declare @ENCSCount as varchar(6)

	set @SQL = 'select @CNCount = count(*) from AB_Abstract 
		where (EncounterNumber = ''' + @Encounter + ''') 
		and (EncounterSequence = ''1'')
		and IsDeleted = 2 
		and InstitutionNumber = (select InstitutionNumber from AB_Abstract where AbstractID = ''' + cast(@AbstractID as varchar(10)) + ''')
		and AdmitDate = (select AdmitDate from AB_Abstract where AbstractID = ''' + cast(@AbstractID as varchar(10)) + ''') 
		and AdmitTime = (select AdmitTime from AB_Abstract where AbstractID = ''' + cast(@AbstractID as varchar(10)) + ''')'
	exec sp_executesql @sql, N'@CNCount varchar(6) output', @CNCount output

	if @CNCount < 2
		SELECT AB_Abstract.EncounterNumber
		FROM AB_Abstract LEFT JOIN AB_MIS ON AB_Abstract.AbstractID = AB_MIS.AbstractID
		WHERE (AB_MIS.MISCode = @MISCode OR AB_Abstract.MISCode = @MISCode) AND (AB_Abstract.AbstractID <> @AbstractID AND AB_Abstract.EncounterNumber = @Encounter)
		AND InstitutionNumber = (SELECT InstitutionNumber FROM AB_Abstract WHERE AbstractID = @AbstractID)
		AND AdmitDate = (SELECT AdmitDate FROM AB_Abstract WHERE AbstractID = @AbstractID)
		AND AdmitTime = (SELECT AdmitTime FROM AB_Abstract WHERE AbstractID = @AbstractID)
	Else
		SELECT AB_Abstract.EncounterNumber
		FROM AB_Abstract where EncounterNumber = 'WERWERRRR'
	RETURN @@RowCount
	--return 0

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE   PROCEDURE [P_CheckUniqueProvider]
	@ProviderCode AS INT,
	@AbstractID AS INT,
	@Encounter AS VARCHAR(20)
AS 

	SELECT EncounterNumber FROM CR_Visit WHERE AbstractID <> @AbstractID AND ProviderNumber = @ProviderCode AND EncounterNumber = @Encounter
	RETURN @@RowCount



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE  PROCEDURE [P_CheckUserIsRole]
	@UserID AS INT
AS 
DECLARE @IsRole INT

SELECT @IsRole = COUNT(RoleID) FROM U_Users WHERE ISNULL(RoleID, 0) = @UserID
RETURN @IsRole



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [P_CheckVIPStatus]
    @AppID int, @RecordID int, @VIP int output
as
    declare @ChartNumber varchar(20)
    declare @HospitalID int
     
    if @AppID = 0 
        set @VIP = isnull((select top 1 Secret from CM_CPI where patientid = @RecordID), 0)
    else if @AppID = 15 --
        set @VIP = isnull((select top 1 Secret from CM_CPI where patientid = (select top 1 DefPatientID from dbo.Def_SlipMain where DefID = @RecordID)), 0)
    else 
    begin
        if @AppID not in (0, 1, 10, 11, 15, 20, 30)
            select top 1 @ChartNumber = ChartNumber, @HospitalID = isnull(HospitalID, 0) from ab_main where AbstractID = @RecordID and AppID = @AppID
        else if @AppID = 30 --ROI
            select top 1 @ChartNumber = ChartNumber, @HospitalID = isnull(HospitalID, 0) from ROI_Main where ROIID = @RecordID
            
        set @VIP = isnull((select top 1 Secret from CM_CPI where ChartNumber = @ChartNumber 
                            AND (ISNULL(HospitalID, 0) = 0 OR @HospitalID  = (case @HospitalID when 0 then 0 else ISNULL(HospitalID, 0) end) )
                            order by hospitalid desc), 0)
    end
    
    if exists (select * from LU_YesBlank where code =  @VIP and CIHIValue in ('Y', '1'))
        set @VIP = 1
    else                           
        set @VIP = 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_CloseLoginSession]
	@LoginID int, @Coder int
AS 
    --2.x-0836
    declare @UserID int 
	declare @LogID int 

    select top 1 @UserID = UserID, @LogID = LogID
    from WM_WorkLoad 
    where loginid = @LoginID and OpType = 18501

    exec [dbo].[I_WM_WorkLoad] @UserID, @LogID, -1, 0, 0, 0, 18511, @LoginID

    Update M_Login
    set LogoutTime = getdate(), 
        CloseBy = @Coder
    where LogID = @LoginID

    Delete from W_RecordLock where UserID = @UserID
    Delete from W_SubmitLock where UserID = @UserID
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE PROCEDURE [P_CM_MergeLog] (@UserCode int, @MType varchar(5), @OldPatientID int, @NewPatientID int, @LogID int output)
AS

INSERT INTO CM_MergeLog 
       (	NewPatientID,
	OldPatientID,
	MergeDate, 
	UserCode, 
	MType) 
VALUES 
       (	@NewPatientID,
	@OldPatientID,
	getdate(), 
	@UserCode, 
	@MType)

SELECT @LogID = @@Identity
EXEC P_CM_MergeLogDetail @LogID



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE PROCEDURE [P_CM_MergeLog_UNDO] (@UserCode int, @MergeID int)
AS

DECLARE @LogID int
SELECT @LogID = MAX(LogID) FROM CM_MergeLog WHERE MergeID = @MergeID
print @LogID
SELECT AbstractID FROM CM_MergeLogDetail WHERE CM_MergeLogDetail.LogID = @LogID 

--UPDATE cm_cpi SET PatientID = (SELECT OldPatientID FROM CM_MergeLogDetail WHERE CM_MergeLogDetail.LogID = @LogID AND CM_MergeLogDetail.AbstractID = cm_cpi.AbstractID)

INSERT INTO CM_MergeLog 
       (MergeID, 
	MergeDate, 
	UserCode, 
	MType) 
VALUES 
       (@MergeID, 
	getdate(), 
	@UserCode, 
	'U')

INSERT INTO CM_MergeLogDetail
       (LogID, 
	NewPatientID, 
	OldPatientID, 
	AbstractID) 
	SELECT 
		LogID,
		OldPatientID,
		NewPatientID,
		AbstractID
	FROM CM_MergeLogDetail
	WHERE CM_MergeLogDetail.LogID = @LogID




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE PROCEDURE [P_CM_MergeLogDetail] (@LogID int)
AS

INSERT INTO CM_MergeLogDetail(LogID, AbstractID) 
	SELECT @LogID, AbstractID
	FROM AB_Main ab INNER JOIN CM_MergeLog cm ON
		ab.PatientID = cm.OldPatientID




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE                                      PROCEDURE [P_CMG2000_9]  
    @Age as Int,    
    @AgeCode as int,
    @LOS as int,    
    @AcuteLOS as int,    
    @ICDType as VarChar(2),    
    @Gender as VarChar(1),    
    @Weight as int,    
    @DDisposition as VarChar(2),    
    @InstNumber as int,    
    @InstTo as int,    
    @InstFrom as int,    
    @DiagMostResposible as VarChar(10),   
    @DiagnosisAll as VarChar(500),   
    @DiagTypeAll as VarChar(500),   
    @DiagTyped1 as VarChar(500),   
    @DiagTyped2 as VarChar(500),   
    @DiagTyped0 as VarChar(500),   
    @DiagTyped3 as VarChar(500),   
    @ProceduresAll as VarChar(500),   
    @Procedure1 as VarChar(10),   
    @FinalCMG as VarChar(3) output,    
    @ComplexityLevel as Int output,    
    @MCC as VarChar(3) output,    
    @AcuteQuartile as VarChar(10) output,    
    @CmgRIW as VarChar(10) output,    
    @CmgMOH as VarChar(10) output,    
    @CmgRIW$ as VarChar(20) output,    
    @CmgMOH$ as VarChar(20) output,    
    @CmgELOS as VarChar(10) output,    
    @CmgTrim as VarChar(10) output,    
    @CmgDesc as VarChar(60) output,    
    @MedOrSurg as VarChar(1) output, 
    @AbstractID as int = Null,
    @Occurance as int = 1,	--Ticket 9011 Placeholder for VB6 not used otherwise in this proc
    @ExpiryDate as varchar(10) = NULL, --Ticket 9011 Placeholder for VB6 not used otherwise in this proc
--Ticket 9373
    @AgeGroup as int,
      @Plx4 as VarChar(1),
	  @FlagRecord as VarChar(1) = 'N'

 AS     
    Declare @MRDxCMG VarChar(8)    
    Declare @Branch VarChar(10)    
    Declare @BranchTemp VarChar(10)    
    Declare @BranchCMG VarChar(3)    
    Declare @Partition as VarChar(2)    
    Declare @FinalSubBranch as VarChar(2)    
    Declare @FinalMCCCode as VarChar(14)    
    Declare @CmgALOS as VarChar(10)    
    Declare @CmgPDRA as VarChar(10)    
    Declare @CmgPDWGT as VarChar(10)    
    Declare @Cat1 as int    
    Declare @Cat2 as int    
    Declare @PlexDiagnosis as VarChar(6)    
    Declare @PlexHomeMcc as VarChar(2)    
    Declare @PlexCount as int    
    Declare @PlexLevel as VarChar(1)    
    Declare @PlexA as int    
    Declare @PlexB as int    
    Declare @PlexC as int    
    Declare @PlexD as int    
    Declare @PlexP as int    
    Declare @Complexity as int    
    Declare @PlexCMCC as int    
    Declare @MedSurg as int      
    Declare @RIW$ as VarChar(10)    
    Declare @CMGProc as Varchar(10)    
    Declare @FinalMCCCodeTemp as VarChar(14)    
    Declare @FinalCMGTemp as VarChar(14)    
    Declare @RIWDeath as VarChar(10)    
    Declare @HospProv as VarChar(2)    
    Declare @IsAcuteTo as bit    
    Declare @IsAcuteFrom as bit    
    Declare @SQL as NVarChar(3000)    
    Declare @count as int    
    Declare @AgeNumber as int    
    Declare @DUsed as VarChar(10)    

    Set @IsAcuteTo = 0    
    Set @IsAcuteFrom = 0    
    If @AgeCode = 0  
 	Set @Age = 0  
    else if @AgeCode = 1  
 	Set @Age = 1  
    else if @AgeCode = 2 and @Age < 13  
 	Set @Age = 1  
    else if @AgeCode = 2 and @Age > 12  
 	Set @Age = 2  
    else if @AgeCode = 3  
         Set @Age = @Age  
 
    If @Gender = 'M'     
        Set @Gender = '1'    
    Else If @Gender = 'F'    
        Set @Gender = '2'    
  
    Set @HospProv = (SELECT top 1 dbo.LU_Province.CIHIValue FROM dbo.H_HospitalProfile LEFT OUTER JOIN    
                       dbo.LU_Province ON dbo.H_HospitalProfile.ProvinceNumber = dbo.LU_Province.Code)    
   
    If @Instto is not null and @HospProv = '5'    
    Begin  
        Declare @InstToV as VarChar(4)  
        select @InstToV = cihivalue from LU_Institution_9 where code = @InstTo   
        if exists (SELECT * FROM dbo.LLU_CMG_InstAcuteON2 WHERE (Cihivalue = @InstToV))    
            set @IsAcuteTo = 1    
    End    
    Else If @Instto is not null    
    Begin    
        if exists (SELECT Top 1 * FROM dbo.LU_Institution_9 WHERE (Code = @InstTo) and LEFT(RIGHT(CIHIValue, 4), 1) = '0')    
             set @IsAcuteTo = 1    
    End    
    If @Instfrom is not null and @HospProv = '5'    
    Begin    
        Declare @InstfromV as VarChar(4)  
        select @InstfromV = cihivalue from LU_Institution_9 where code = @Instfrom   
        if exists (SELECT * FROM dbo.LLU_CMG_InstAcuteON2 WHERE (Cihivalue = @Instfromv))    
            set @IsAcuteFrom = 1    
    End    
    Else If @Instfrom is not null    
    Begin    
        if exists (SELECT Top 1 * FROM dbo.LU_Institution_9 WHERE (Code = @Instfrom) and LEFT(RIGHT(CIHIValue, 4), 1) = '0')    
            set @IsAcuteFrom = 1    
    End    
     
    If rtrim(@DiagTypeAll) = ''  
        Set @DiagTypeAll = '''XXX'''    
 
    Declare @AdmitCat as VarChar(2) 
    If isnull(@DDisposition, ' ') = ' ' and @Weight > 0 and @Abstractid > 0
    Begin
 	Set @AdmitCat = ''
 	set @AdmitCat = (SELECT dbo.LU_EntryCode.CIHIValue FROM dbo.AB_Abstract LEFT OUTER JOIN dbo.LU_EntryCode 
 	ON dbo.AB_Abstract.EntryCode = dbo.LU_EntryCode.Code where dbo.AB_Abstract.abstractid = @Abstractid)
 	If Isnull(@AdmitCat, '') <> 'S'
 		Set @AdmitCat = ''
    End
    Else
 	Set @AdmitCat = 'S'
 
 /*Search main cmg table for Category(MCC) on Most responsible Diagnosis */     
    If (@Weight = 0 and isnull(@AgeCode, 0) <> 1) or (@Weight <> 0 and isnull(@AgeCode, 0) > 1)    
        SELECT Top 1 @MCC = [MCC], @MRDxCMG = [rtCMG], @BranchTemp = [MCCCode]  FROM CMG_Main    
        WHERE ([ProcDiagCode]= @DiagMostResposible) AND ([ICDType] = @ICDType) AND ([Priority] = 3) AND (Gender = @Gender Or Gender = 3)    
    Else if @Weight > 0 and isnull(@DDisposition, ' ') = ' ' and @AdmitCat = 'S' 
    Begin  
        set @MCC = '15X'    
        Set @FinalCMG = '997'    
        Set @CmgDesc = 'Stillbirth'   
    End   
   Else if @Weight < 750 AND @Weight >= 200
   Begin
      Set @MCC = '99'
      Set @FinalCMG = '999'
   End 
    Else if @Weight < 750    
    Begin    
        set @MCC = '15X'    
        Set @FinalCMG = '625'    
    End    
    Else if @Weight < 1000    
    Begin    
        set @MCC = '15X'    
        Set @MRDxCMG = '626'    
    End    
    Else if @Weight < 1500    
    Begin    
        set @MCC = '15X'    
        Set @MRDxCMG = '628'    
        Set @BranchTemp = 'MC15XM03MD'    
    End    
    Else if @Weight < 2000    
    Begin    
        set @MCC = '15X'    
        Set @MRDxCMG = '632'    
        Set @BranchTemp = 'MC15XM04MD'    
    End    
    Else if @Weight < 2500    
    Begin    
        set @MCC = '15X'    
        Set @MRDxCMG = '640'    
        Set @BranchTemp = 'MC15XM05MD'    
    End    
    Else if @Weight > 2499 AND @Weight < 9000
    Begin    
        set @MCC = '15X'    
        Set @MRDxCMG = '648'    
        Set @BranchTemp = 'MC15XM06MD'    
    End    
   Else if @Weight > 8999
   Begin
      Set @MCC = '99'
      Set @FinalCMG = '999'
   End
   
 /*If you don't get a match and it is a 5 digit diag codee, search main cmg table for Category(MCC)    
     on first four numbers of most responsible Diagnosis */     
    Declare @TypeZero as VarChar(10)  
    IF @MCC is null and Len(@DiagMostResposible) > 4    
    BEGIN    
        SELECT Top 1 @MCC = [MCC], @MRDxCMG = [rtCMG], @BranchTemp = [MCCCode]  FROM CMG_Main    
        WHERE ([ProcDiagCode]= left(@DiagMostResposible,4)) AND ([ICDType] = @ICDType) AND ([Priority] = 3) AND (Gender = @Gender Or Gender = 3)    
        Set @DiagMostResposible = left(@DiagMostResposible,4)    
    END    
   
    If (@BranchTemp = 'MC19XM01MD' or @BranchTemp = 'MC19XM02MD' or @BranchTemp = 'MC19XM05MD') and @DDisposition = 'D' and @LOS < 6    
    Begin    
        Set @FinalCMG = @MRDxCMG + 1    
        Set @Branch = @BranchTemp    
    End    
    Else If (@BranchTemp = 'MC19XM01MD' or @BranchTemp = 'MC19XM02MD' or @BranchTemp = 'MC19XM05MD') and @LOS < 6 and @Instfrom = 0 and @InstTo = 0    
    Begin     
        Set @FinalCMG = @MRDxCMG + 1    
        Set @Branch = @BranchTemp    
    End    
   
    If @ProceduresAll = '' 
    	Set @ProceduresAll = '''XXX'''    
    Declare @DiagMProcAll as VarChar(2000)    
    Declare @DiagMProc as VarChar(2000)    
    Set @DiagMProcAll = ''    
    If @DiagMostResposible <> ''    
    Begin    
        set @DiagMProcAll = '''' + @DiagMostResposible + ''', '     
        set @DiagMProc = '''' + @DiagMostResposible + ''', '     
    End    
   
    Set @DiagMProcAll = replace(@DiagMProcAll, ', ,',  ', ')    
     
    If @DiagnosisAll <> ''    
        Set @DiagMProcAll = @DiagMProcAll + @DiagnosisAll + ', '    
    If @ProceduresAll <> ''    
    Begin    
        Set @DiagMProcAll = @DiagMProcAll + @ProceduresAll    
        Set @DiagMProc = @DiagMProc + @ProceduresAll    
    End    
    If right(@DiagMProcAll, 2) = ', '    
        Set @DiagMProcAll = Left(@DiagMProcAll, len(@DiagMProcAll) - 2)    
    If right(@DiagMProc, 2) = ', '    
        Set @DiagMProc = Left(@DiagMProc, len(@DiagMProc) - 2)    
   
    Set @DiagMProcAll = replace(@DiagMProcAll, ', ,',  '')    
    Set @DiagnosisAll = replace(@DiagnosisAll, ', ,',  '')    
    If right(@DiagMProcAll, 1) <> ''''    
        Set @DiagMProcAll = @DiagMProcAll + ''''    
 --New 2002/09/24  
    set @DiagnosisAll = replace(@DiagMProcAll, @ProceduresAll, '')  
    If right(@DiagnosisAll, 2) = ', '    
        Set @DiagnosisAll = Left(@DiagnosisAll, len(@DiagnosisAll) - 2)    
    If right(@DiagnosisAll, 1) <> ''''    
        Set @DiagnosisAll = @DiagnosisAll + ''''    
   
    if isnull(@DiagnosisAll, '') = ''     
        Set @DiagnosisAll = '''XXXX'''  
   
 /*Search main cmg table for Partition or branch on procedures */       
    If @FinalCMG is NULL    
    Begin    
        set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = rtCMG, @CMGProc = ProcDiagCode FROM CMG_Main     
        WHERE ProcDiagCode in (' + @ProceduresAll + ')     
        AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND Priority < 3 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', @Branch output, @BranchCMG Output, @CMGProc Output    
     
        Set @Partition = SUBSTRING(@Branch, 7, 2)    
        If isnull(@Branch, '0') = '0' and @MCC = '18X' and isnull(@Procedure1, '0') <> '0'    
        begin    
            Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = rtCMG, @CMGProc = ProcDiagCode FROM CMG_Main     
            WHERE ProcDiagCode in (' + @ProceduresAll + ')     
            AND (ICDType = ''' + @ICDType + ''') and translatefrom like ''appdh%'''    
            exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', @Branch output, @BranchCMG Output, @CMGProc Output               If isnull(@Branch, '0') <> '0'    
            begin    
                Set @Branch = 'MC18XS02PR'    
                Set @BranchCMG = '750'    
            end    
        end    
        Else If isnull(@Branch, '0') = '0' and @MCC = '17A' and isnull(@Procedure1, '0') <> '0'    
        begin    
            Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = rtCMG, @CMGProc = ProcDiagCode FROM CMG_Main     
            WHERE ProcDiagCode in (' + @ProceduresAll + ')     
            AND (ICDType = ''' + @ICDType + ''') and translatefrom like ''appdh%'''    
            exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', @Branch output, @BranchCMG Output, @CMGProc Output    
            If isnull(@Branch, '0') <> '0'    
            begin    
                Set @Branch = 'MC17AS03PR'    
                Set @BranchCMG = '728'    
            end    
        end    
        Else If isnull(@Branch, '0') = '0' and @MCC = '17B' and isnull(@Procedure1, '0') <> '0'    
        begin    
            Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = rtCMG, @CMGProc = ProcDiagCode FROM CMG_Main     
            WHERE ProcDiagCode in (' + @ProceduresAll + ')     
            AND (ICDType = ''' + @ICDType + ''') and translatefrom like ''appdh%'''    
            exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', @Branch output, @BranchCMG Output, @CMGProc Output    
            If isnull(@Branch, '0') <> '0'    
            begin    
                Set @FinalCMG = '734'    
                Set @BranchCMG = '734'    
            end    
        end    
        Else if @MCC = '05A' and (@Partition = '06' or @Partition = '07') and SUBSTRING(@Branch, 5, 2) = 'AS'    
        Begin  
            SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main     
            WHERE ProcDiagCode = (@DiagMostResposible) AND (ICDType = @ICDType) AND MCC = @MCC AND (Partition = @Partition) AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= 'AS' ORDER BY SortOrder    
            If @FinalCMG is null    
            Begin    
                If @BranchCMG is null    
                    Set @FinalCMG = @MRDxCMG    
                Else    
                    Set @FinalCMG = @BranchCMG    
            End    
        End    
        else If isnull(@Branch, '0') = '0'    
            Set @Branch = @BranchTemp    
        Set @Partition = SUBSTRING(@Branch, 7, 2)    
        Set @FinalSubBranch = SUBSTRING(@Branch, 5, 2)    
    End    
 /* Extract Branch Procedure code out of procedure string and then     
    look for sub levels with both diagnosis other and remaining    
    procedures. */    
 --According to Shona 2002/09/20 I don't need to do this except for complexity and only then for diagnosis.  
    If @MCC = '15X'    
    Begin    
 
        Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
        WHERE ProcDiagCode in (' + @DiagMProcAll + ') AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''')     
        AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2) = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
    End    
    Else If @MCC = '13X'    
    Begin    
        Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
        WHERE ProcDiagCode in (' + @DiagMProc + ') AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''')     
        AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2) = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
    End    
    Else If @MCC = '24X'    
        Set @FinalCMG = @MRDxCMG    
    Else If @FinalCMG is null and SUBSTRING(@Branch, 6, 1) = 'S'    
    Begin    
        Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
        WHERE ProcDiagCode in (' + @ProceduresAll + ') AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''')     
        AND (Partition = ''' + @Partition + ''') and SUBSTRING(MCCCode, 6, 1) = ''S'' AND Priority = 4 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
    End    
    Else If @FinalCMG is null    
    Begin    
        Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
        WHERE ProcDiagCode in (' + @DiagMProcAll + ') AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''')     
        AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2) = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
    End    
   
    If @MCC = '05A' and (@Partition Between '03' and '15') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02'    
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
        Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
        WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))    
        AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and SortOrder > 6 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
        If @FinalCMG is Null    
            Set @FinalCMG = @FinalCMGTemp    
    End    
    --New 2002/09/20  
    Else If (@MCC = '05A' and (@Partition Between '19' and '21')) or (@MCC = '04X' and (@Partition Between '09' and '11')) or (@MCC = '01X' and (@Partition Between '09' and '11'))  
     or (@MCC = '06X' and (@Partition Between '19' and '21')) or (@MCC = '08X' and (@Partition Between '27' and '29')) or (@MCC = '11X' and (@Partition Between '17' and '19'))  
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
        Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
        WHERE ((ProcDiagCode) in (''' + @DiagMostResposible + '''))    
        AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
   
        If @FinalCMG is Null    
            Set @FinalCMG = @FinalCMGTemp    
    End    
    Else If @MCC = '05A' and (@Partition Between '03' and '15') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) <> 'L02'    
        Set @FinalCMG = Null    
    Else If (@MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02' AND (@LOS >= 4)) or     
        ((@MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02') and (@DDisposition in ('S', 'D') or @IsAcuteTo = 1 or @IsAcutefrom = 1))    
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
        set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))     
        AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and     
        SortOrder > 2 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
        If @FinalCMG is Null    
            Set @FinalCMG = @FinalCMGTemp    
        else if @Partition = '01'    
            Set @FinalCMG = @FinalCMG - 4    
        else     
            Set @FinalCMG = @FinalCMG - 2    
    end    
    Else If @MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02' And @LOS < 4    
        Set @FinalCMG = '218'    
    Else if @MCC = '05A' and (@Partition = '03' or @Partition = '04' or @Partition = '05')    
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
        set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))     
        AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
            
        If @FinalCMG is Null    
            Set @FinalCMG = @FinalCMGTemp    
        If @FinalCMG in ('176', '178', '181')    
            Set @FinalCMG = '183'    
        Else If @FinalCMG in ('177', '179', '182')    
        Begin    
            set @SQL = 'SELECT @Count = count(*) FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))     
            AND (ICDType = ''' + @ICDType + ''') AND MCCCode = ''MC05AS' + @Partition + 'NPL02'''    
            exec sp_executesql @sql, N'@count int output', @Count output    
            If isnull(@Count, 0) > 0    
                Set @FinalCMG = @FinalCMG - 1    
        End    
    end    
    Else if @MCC = '05A' and @Partition = '10' and (@FinalCMG = '181' or @FinalCMG = '182')    
    Begin    
        set @SQL = 'SELECT @Count = count(*) FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))     
        AND (ICDType = ''' + @ICDType + ''') AND MCCCode = ''MC15AS10NPL01'''    
        exec sp_executesql @sql, N'@count int output', @Count output    
        If isnull(@Count, 0) = 0    
            Set @FinalCMG = 194    
    End    
    --New 2002/09/19  
    Else If @MCC = '06X' and (@Partition = '12')  
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
        Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
        WHERE ((ProcDiagCode) in (''' + @DiagMostResposible + '''))    
        AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
        If @FinalCMG is Null    
            Set @FinalCMG = @FinalCMGTemp    
    End    
    --New 2002/09/24  
    Else If @MCC = '08X' and (@Partition in ('04', '05', '07')) and @FinalCMG = '350'  
    Begin    
        set @FinalCMG = NULL  
        Declare @MC08Count as int    
        Set @MC08Count = charindex(@ProceduresAll, @CMGProc, charindex(@ProceduresAll, @CMGProc) + 1)    
        If isnull(@MC08Count, 0) <> 0    
           Set @FinalCMG = 350    
        Else  
        Begin  
           Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
           WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))    
           AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SortOrder > 1 ORDER BY SortOrder'    
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
        End  
        If @FinalCMG is Null    
            Set @FinalCMG = @BranchCMG   
    End    
    --New 2002/09/19  
    Else If @MCC = '09X'  
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
        Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
        WHERE ((ProcDiagCode) in (' + @DiagnosisAll + '))    
        AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
        If @FinalCMG is Null    
            Set @FinalCMG = @FinalCMGTemp    
    End    
    --New 2002/09/25  
    Else If @MCC = '19X' and (@FinalCMG not in ('771', '778', '767'))  
    Begin    
        set @FinalCMGTemp = @FinalCMG   
        Set @FinalCMG = Null   
        Declare @LenDiag as int
        Declare @Diag19X as NVarChar(200)
        set @LenDiag = len(@DiagnosisAll) - len(@DiagMostResposible) - 4
        If @LenDiag < 0
        Begin
 		Set @LenDiag = 0
 		Set @Diag19X = ''''''
        End
        Else
 		Set @Diag19X = right(@DiagnosisAll, @LenDiag)
 
        Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
        WHERE ((ProcDiagCode) in (' + @Diag19X + '))    
        AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
        If @FinalCMG is Null    
        Begin  
           Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
           WHERE ((ProcDiagCode) in (''' + @DiagMostResposible + '''))    
           AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 1 ORDER BY SortOrder'    
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
        End  
    End    
    Else If @MCC = '11X' and (@Partition = '01') and right(@FinalMCCCode, 3) = 'L01' and @LOS < 3 and @DDisposition = 'D'    
        Set @FinalCMG = '999'    
    Else if @MCC = '13X' and @FinalMCCCode like 'MC13XS04%'    
    Begin    
        If @FinalMCCCode = 'MC13XS04PRL02'    
        Begin    
            set @FinalCMGTemp = @FinalCMG    
            Set @FinalCMG = Null    
            set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProc + '))     
            AND (ICDType = ''' + @ICDType + ''')  AND MCCCode in (''MC13XS04MDL03'', ''MC13XS04PRL04'') ORDER BY SortOrder'    
            exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
     
            If @FinalCMG is Null    
                Set @FinalCMG = '579'    
        End    
        Else If @FinalMCCCode = 'MC13XS04MDL01'    
        Begin    
            set @FinalCMGTemp = @FinalCMG    
            Set @FinalCMG = Null    
            set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProc + '))     
            AND (ICDType = ''' + @ICDType + ''')  AND MCCCode = ''MC13XS04PRL02'''    
            exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
                
            If @FinalCMG is Null    
                Set @FinalCMG = @FinalCMGTemp    
        End    
        If @FinalMCCCode = 'MC13XS04MDL03'    
        Begin    
            set @FinalCMGTemp = @FinalCMG    
            Set @FinalCMG = Null    
            set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProc + '))     
            AND (ICDType = ''' + @ICDType + ''')  AND MCCCode = ''MC13XS04PRL04'''    
            exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
                
            If @FinalCMG is Null    
                Set @FinalCMG = @FinalCMGTemp    
        End    
        Else If @FinalMCCCode = 'MC13XS04PRL04'    
            Set @FinalCMG = '579'    
    end    
    Else If @MCC = '14X' and (@Partition = '05') And (@LOS >= 3 or @IsAcuteTo = 1 or @IsAcuteFrom = 1)    
        Set @FinalCMG = '599'    
    Else If @MCC = '15X' and (@Partition Between '03' and '06') and right(@FinalMCCCode, 3) = 'L01' And @LOS < 6    
        Set @FinalCMG = 998    
    Else If @MCC = '15X' and (@Partition = '06') and (right(@FinalMCCCode, 3) in ('L04', 'L05') or @FinalCMG = '648' or  
    (@FinalCMG is null and @MRDxCMG = '648')) -- New added @DiagTyped0 2002/09/25 plus this line  
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
        set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagnosisAll + @DiagTyped0 + '))     
        AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and     
        SortOrder > 4 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
        If @FinalCMG is Null    
            Set @FinalCMG = @FinalCMGTemp    
     
        If @FinalCMG = '647'    
        Begin    
            set @SQL = 'SELECT @Count = count(*) FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagnosisAll + @DiagTyped0 + '))     
            AND (ICDType = ''' + @ICDType + ''') AND MCCCode = ''MC15XM06MOL05'''    
            exec sp_executesql @sql, N'@count int output', @Count output    
            If isnull(@Count, 0) > 0    
                Set @FinalCMG = @FinalCMG - 1    
        End    
    end    
    Else If @MCC = '14X' and (@Partition = '02')-- and right(@FinalMCCCode, 3) = 'L01' commented 2002/09/10   
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
    
        set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagnosisAll + '))     
        AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and    
        SortOrder = 1 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
    
        If @FinalCMG is Null   
            Set @FinalCMG = @FinalCMGTemp    
        Else   
        Begin   
           set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagnosisAll + '))     
           AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and     
           SortOrder > 1 ORDER BY SortOrder'    
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
               
           If @FinalCMG is Null    
               Set @FinalCMG = @FinalCMGTemp    
           If @FinalCMG = '601'    
               Set @FinalCMG = '603'    
           Else If @FinalCMG = '602'    
           Begin    
               set @SQL = 'SELECT @Count = count(*) FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))     
               AND (ICDType = ''' + @ICDType + ''') AND MCCCode = ''MC14XS02MOL03'''    
               exec sp_executesql @sql, N'@count int output', @Count output    
               If isnull(@Count, 0) > 0    
                   Set @FinalCMG = @FinalCMG - 1    
           End    
    End   
    end    
    Else If @MCC = '14X' and (@Partition = '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'XM' and right(@FinalMCCCode, 3) <> 'L01'    
        Set @FinalCMG = 999    
    Else If @MCC = '14X' and (@FinalCMG = '608' or @FinalCMG = '609')    
    Begin    
        If @FinalCMG = '608'   
             Set @FinalCMG = '610'    
        Else If @FinalCMG = '609'    
        Begin    
            set @SQL = 'SELECT @Count = count(*) FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagnosisAll + '))     
            AND (ICDType = ''' + @ICDType + ''') AND MCCCode = ''MC14XM01MOL04'''    
            exec sp_executesql @sql, N'@count int output', @Count output    
            If isnull(@Count, 0) > 0    
                Set @FinalCMG = @FinalCMG - 1    
        End    
    End    
    Else If @MCC = '14X' and (@FinalCMG = '621')    
    Begin    
        If @FinalCMG = '621'    
        Begin    
            set @SQL = 'SELECT @Count = count(*) FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagnosisAll + '))     
            AND (ICDType = ''' + @ICDType + ''') AND MCCCode = ''MC14XM06PRL10'''    
            exec sp_executesql @sql, N'@count int output', @Count output    
            If isnull(@Count, 0) > 0    
                Set @FinalCMG = @FinalCMG - 1    
        End    
    end    
    Else If @MCC = '24X'    
    Begin    
        If len(@DiagTyped1 + @DiagTyped2) > 0   
        Begin    
            set @FinalCMGTemp = @FinalCMG    
            Set @FinalCMG = Null    
            Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
            WHERE ProcDiagCode in (''' + @DiagnosisAll + ''') AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''')     
            AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2) = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'    
            exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
            If isnull(@FinalCMG, '') = ''    
                Set @FinalCMG = '868'    
        End    
        Else If isnull(@FinalCMG, '') = ''    
        Begin    
            Set @FinalCMG = '999'    
            Set @FinalMCCCode = 'MC99XM01MD'    
            Set @MCC = '99'    
        End    
    End    
    Else If @MCC = '25X' and SUBSTRING(@Branch, 6, 1) = 'S' and SUBSTRING(@Branch, 7, 2) = '04' and @FinalCMG in ('351', '350') --New 2002/09/26 Moved from above and this line  
    Begin    
        Declare @MC25Count as int    
        If @FinalCMG = 350    
            Set @MC25Count = charindex(@ProceduresAll, @CMGProc, charindex(@ProceduresAll, @CMGProc) + 1)    
        If isnull(@MC25Count, 0) = 0    
            Set @FinalCMG = 351    
    End    
    If @FinalCMG is null    
    Begin    
        If @BranchCMG is null    
            Set @FinalCMG = @MRDxCMG    
        Else    
            Set @FinalCMG = @BranchCMG    
    End    
    If isnull(@FinalCMG, '') = ''    
        Begin    
            Set @FinalCMG = '999'    
            Set @FinalMCCCode = 'MC99XM01MD'    
            Set @MCC = '99'    
        End    
 /* Calculate Complexity*/    
    if len(@FinalMCCCode) > 10    
        Set @Branch = left(isnull(@FinalMCCCode, ''), 10)    

    Declare @MedSurgInd as VarChar(1) 
    SELECT @MedSurg = cmgmcctype, @MedSurgInd = RIWInd FROM CMG_Etc_2001T WHERE (cmgcode = @FinalCMG) and (ciagegroup = @AgeGroup)    
    Set @PlexA = 0    
    Set @PlexB = 0    
    Set @PlexC = 0    
    Set @PlexD = 0    
    Set @PlexP = 0    
    Set @PlexCMCC = 0    
    If exists (SELECT * FROM CMG_Etc_2001T WHERE (cmgcode = @FinalCMG) AND (cicpxlvl = 9) and (ciagegroup = @AgeGroup)) or @MedSurg = '9'  
        set @Complexity = 9    
  
    If @ICDType = 'C' And patindex('%9672%', @ProceduresAll) > 0 
    Set  @Complexity = 4 
  
    if isnull(@DUsed, '0') = '0'  
         Set @DUsed = 'XXXX'  
 --   Set @DiagTypeAll = replace(@DiagTypeAll, left(@DUsed, 4), ' ')    
    Set @DiagTypeAll = replace(@DiagTypeAll, left(@DiagMostResposible, 4) + '|', 'XXXX|')   
    Set @DiagTypeAll = replace(@DiagTypeAll, @DiagMostResposible + '|', 'XXXXX|')   
    Set @SQL = 'SELECT HomeMCC, COUNT(GrLevel) AS CountLevel, GrLevel FROM dbo.CMG_Complexity    
    WHERE DiagTypeCombine in (' + @DiagTypeAll + ')    
    AND (MCC = Left(''' + @MCC + ''',2)) AND (ICDType = ''' + @ICDType + ''') AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''')    
    GROUP BY HomeMCC, GrLevel Order by GrLevel'    
    exec (@SQL)    
     
    if @Complexity is null and @@RowCount > 0    
    Begin    
        Set @SQL = 'Declare cur_Complexity cursor for     
        SELECT HomeMCC, COUNT(GrLevel) AS CountLevel, GrLevel, Diagnosis FROM dbo.CMG_Complexity    
        WHERE DiagTypeCombine in (' + @DiagTypeAll + ')    
        AND (MCC = Left(''' + @MCC + ''',2)) AND (ICDType = ''' + @ICDType + ''') AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''')    
        GROUP BY HomeMCC, GrLevel, diagnosis Order by GrLevel    
        Open cur_Complexity'    
        Exec (@SQL)    
        fetch next from cur_Complexity    
        into @PlexHomeMcc, @PlexCount, @PlexLevel, @PlexDiagnosis    
        while @@fetch_status = 0    
        begin    
            If not exists(SELECT * FROM dbo.CMG_PlxException WHERE (MCCEx = LEFT(@MCC,2)) AND (CMGEx = @FinalCMG) AND (DiagnosisEx = @PlexDiagnosis) AND ICDType = @ICDType)    
            Begin    
               If @PlexLevel = 'A'     
                   Set @PlexA = @PlexA + @PlexCount    
               Else If @PlexLevel = 'B'    
                   Set @PlexB = @PlexB + @PlexCount    
               Else If @PlexLevel = 'C'    
               Begin    
                   Set @PlexC = @PlexC + @PlexCount    
                   If @PlexHomeMcc <> Left(@MCC,2)    
                       Set @PlexCMCC = 1    
               End                     Else If @PlexLevel = 'D'    
                   Set @PlexD = @PlexD + @PlexCount    
               Else If @PlexLevel = 'P'    
                   Set @PlexP = @PlexP + @PlexCount    
      End                   
           fetch next from cur_Complexity    
           into @PlexHomeMcc, @PlexCount, @PlexLevel, @PlexDiagnosis    
        end    
        Close cur_Complexity    
        Deallocate cur_Complexity    
   
        If @PlexA > 0 or @PlexB > 1 or (@PlexB = 1 and @PlexC > 0 and @PlexCMCC = 1)    
            Set @Complexity = 4    
        Else If @PlexB > 0 or (@PlexC > 1 and @PlexCMCC = 1) or (@PlexC > 10 and @PlexCMCC = 0)    
            Set @Complexity = 3    
        Else If @PlexD > 0 or @PlexP > 0 or (@PlexC = 1 and @PlexCMCC = 1) or (@PlexC > 0 and @PlexC < 11 and @PlexCMCC = 0)  
            Set @Complexity = 2    
        Else    
            Set @Complexity = 1    
    End    
    If isnull(@Complexity, '') = ''    
        Set @Complexity = 1    
     
    Set @MCC = Replace(@MCC, 'X', '')    
    Set @ComplexityLevel = @Complexity    
 /*Get the rest of the stuff */    
    SELECT Top 1 @CmgDesc = cmgdesc, @CmgTrim = ciagtrim, @CmgELOS = ciagelos, @CmgPDRA = ciagpdra, @CmgPDWGT = ciagpdwgt, @CmgRIW = ciagriw    
    FROM dbo.CMG_Etc_2001T WHERE (cmgcode = @FinalCMG) AND (cicpxlvl = @ComplexityLevel) AND (ciagegroup = @AgeGroup)    
 --New 2002/09/30 
    If @MedSurg = 9 
    Set @MedSurg = 1 
 /* If @LOS < @CMGELOS    
        set @RIW = @LOS * */   /*Get RIW$ Value*/    
            If @FinalCMG in ('910', '912', '998', '999') and @LOS < cast(@CMGELOS as decimal(7,4))    
                    Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))    
            else if @DDisposition = ' ' and @LOS <= @CMGTrim and @LOS <= 10    
            Begin    
                Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer     
                    WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr is null and dxyear = 2000)    
                Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))    
            End    
            else if @DDisposition = ' ' and @LOS <= @CMGTrim and @LOS > 10    
            Begin    
                Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer    
                    WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr is null and dxyear = 2000)    
                Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))    
            End    
            Else If @DDisposition = 'S' and @LOS <= cast(@CMGELOS as decimal(7,4))    
                Set @CMGRIW = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,4))) as decimal(7,4))    
            Else If @DDisposition = 'S' and @LOS > cast(@CMGELOS as decimal(7,4)) and @LOS < @CMGTrim    
                Set @CMGRIW = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@CmgELOS as decimal(7,4))) as decimal(7,4))    
            Else If @IsAcuteTo = 1 and @LOS <= 10 and @LOS <= @CMGTrim    
            Begin    
                Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer    
                    WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='O' and dxyear = 2000)    
                Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))    
            End    
            Else If @IsAcuteTo = 1 and @LOS > 10 and @LOS <= @CMGTrim    
            Begin    
                Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
                WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='O' and dxyear = 2000)    
                Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))    
            End    
            Else If @IsAcutefrom = 1 and @LOS <= 10 and @LOS <= @CMGTrim    
            Begin    
                Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer    
                    WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='I' and dxyear = 2000)    
                Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))    
            End    
            Else If @IsAcutefrom = 1 and @LOS > 10 and @LOS <= @CMGTrim  
            Begin    
                Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer    
                    WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='I' and dxyear = 2000)    
                Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))    
            End    
            Else If @LOS > @CMGTrim    
                Set @CMGRIW = cast(cast(@CMGRIW as decimal(7,4)) + (cast(@CmgPDRA as decimal(7,4)) * cast((cast(@LOS as decimal(7,2)) - cast(@CmgELOS as decimal(7,4))) as decimal(7,4))) as decimal(7,4))    
    if @CmgRIW is not null    
    Begin    
        Set @RIW$ = (Select CostPerRiw from H_InstitutionProfile where code = @InstNumber)      
        if isnull(@RIW$, '0') = '0' or @RIW$ = ''    
            set @RIW$ = '0'    
        Set @CMGRIW$ = cast(@CmgRIW as decimal(7,4)) * cast(@RIW$ as decimal(6,2))    
        if @LOS - @CMGTrim > 0    
            Begin    
                Set @CMGMOH = left(@CMGRIW + (((@LOS - @CMGTrim) * cast(@CmgPDWGT as Decimal(4,4))) + (((@CMGTrim - cast(@CMGELOS as decimal(4,2))) * cast(@CmgPDWGT as Decimal(4,4)))) * .2), 10)    
                Set @CMGMOH$ = cast(@CmgMOH as decimal(7,4)) * cast(@RIW$ as decimal(6,2))    
            end    
        Else    
            Begin    
                Set @CMGMOH = @CMGRIW    
                Set @CMGMOH$ = @CMGRIW$    
            end    
        Set @CMGMOH = cast(@CMGMOH as decimal(8,4))    
        Set @CMGRIW$ = cast(@CMGRIW$ as decimal(10,2))    
 
        Set @CMGMOH$ = cast(@CMGMOH$ as decimal(10,2))    
    End    
 
    If @FinalCMG = '997'    
        Set @AcuteQuartile = 'I'    
    Else If @DDisposition = ' '    
        Set @AcuteQuartile = 'D'    
    Else If @DDisposition = 'S'    
        Set @AcuteQuartile = 'S'    
    Else If @IsAcuteFrom = 1 or @IsAcuteTo = 1    
        Set @AcuteQuartile = 'T'    
    Else If @LOS > @CMGTrim    
        Set @AcuteQuartile = 'O'    
    Else If @LOS > cast(@CMGELOS as decimal(7,4))    
        Set @AcuteQuartile = 'B'    
    Else    
        Set @AcuteQuartile = 'I'    
     
    If @MedSurg = '3'
 	Set @MedOrSurg = 'M'
    Else
 	Set @MedOrSurg = 'S'
   
    If isnull(@AbstractID, 0) > 0    
    Begin    
        Delete ab_CMG where Abstractid = @Abstractid and CMG_Year = 2000 and OccurrenceNumber = 1    
        If IsNull(@FinalCMG, '') <> ''    
        Begin    
            If @ICDType = 'C'    
                Set @DiagMostResposible = (select top 1 code from ICD_DiagFile9cm where cihivalue = @DiagMostResposible)    
            Else    
                Set @DiagMostResposible = (select top 1 code from ICD_DiagFile9 where cihivalue = @DiagMostResposible)      
            INSERT INTO [dbo].[AB_CMG] ([AbstractID], [OccurrenceNumber], [CMG_Year], [ICD_Type], [Diagnosis_Code],    
            [Diagnosis_Type], [CMG], [Complexity], [MCC], [AcuteQuartile], [CMG_RIW], [MOH_RIW],    
            [RIW_Dollar], [MOH_Dollar], [CMG_ELOS], [CMG_Trim], [CMG_Description], [MCC_Surg]) VALUES     
            (@AbstractID, 1, 2000, @ICDType, @DiagMostResposible, 11, @FinalCMG, @ComplexityLevel, Left(@MCC, 2), @AcuteQuartile, @CmgRIW, @CmgMOH,     
            cast(@CmgRIW$ as money), cast(@CmgMOH$ as money), @CmgELOS, @CMGTrim, @CMGDesc, @MedOrSurg)    
        End    
    End    
     
    Return 0



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE         PROCEDURE [P_CMG2001_9]    
    @Age as Int,    
    @AgeCode as int,
    @LOS as int,    
    @AcuteLOS as int,    
    @ICDType as VarChar(2),    
    @Gender as VarChar(1),    
    @Weight as int,    
    @DDisposition as VarChar(2),    
    @InstNumber as int,    
    @InstTo as int,    
    @InstFrom as int,    
    @DiagMostResposible as VarChar(10),   
    @DiagnosisAll as VarChar(500),   
    @DiagTypeAll as VarChar(500),   
    @DiagTyped1 as VarChar(500),   
    @DiagTyped2 as VarChar(500),   
    @DiagTyped0 as VarChar(500),   
    @DiagTyped3 as VarChar(500),   
    @ProceduresAll as VarChar(500),   
    @Procedure1 as VarChar(10),   
    @FinalCMG as VarChar(3) output,    
    @ComplexityLevel as Int output,    
    @MCC as VarChar(3) output,    
    @AcuteQuartile as VarChar(10) output,    
    @CmgRIW as VarChar(10) output,    
    @CmgMOH as VarChar(10) output,    
    @CmgRIW$ as VarChar(20) output,    
    @CmgMOH$ as VarChar(20) output,    
    @CmgELOS as VarChar(10) output,    
    @CmgTrim as VarChar(10) output,    
    @CmgDesc as VarChar(60) output,    
    @MedOrSurg as VarChar(1) output, 
    @AbstractID as int = Null,
    @Occurance as int = 1,	--Ticket 9011 Placeholder for VB6 not used otherwise in this proc
    @ExpiryDate as varchar(10) = NULL, --Ticket 9011 Placeholder for VB6 not used otherwise in this proc
--Ticket 9373
    @AgeGroup as int,
      @Plx4 as VarChar(1),
	  @FlagRecord as VarChar(1) = 'N'

 AS     
    Declare @MRDxCMG VarChar(8)    
    Declare @Branch VarChar(10)    
    Declare @BranchTemp VarChar(10)    
    Declare @BranchCMG VarChar(3)    
    Declare @Partition as VarChar(2)    
    Declare @FinalSubBranch as VarChar(2)    
    Declare @FinalMCCCode as VarChar(14)    
    Declare @CmgALOS as VarChar(10)    
    Declare @CmgPDRA as VarChar(10)    
    Declare @CmgPDWGT as VarChar(10)    
    Declare @Cat1 as int    
    Declare @Cat2 as int    
    Declare @PlexDiagnosis as VarChar(6)    
    Declare @PlexHomeMcc as VarChar(2)    
    Declare @PlexCount as int    
    Declare @PlexLevel as VarChar(1)    
    Declare @PlexA as int    
    Declare @PlexB as int    
    Declare @PlexC as int    
    Declare @PlexD as int    
    Declare @PlexP as int    
    Declare @Complexity as int    
    Declare @PlexCMCC as int    
    Declare @MedSurg as int    
    Declare @RIW$ as VarChar(10)    
    Declare @CMGProc as Varchar(10)    
    Declare @FinalMCCCodeTemp as VarChar(14)    
    Declare @FinalCMGTemp as VarChar(14)    
    Declare @RIWDeath as VarChar(10)    
    Declare @HospProv as VarChar(2)    
    Declare @IsAcuteTo as bit    
    Declare @IsAcuteFrom as bit    
    Declare @SQL as NVarChar(3000)    
    Declare @count as int    
    Declare @AgeNumber as int    
    Declare @DUsed as VarChar(10)    

    Set @IsAcuteTo = 0    
    Set @IsAcuteFrom = 0    
    If @AgeCode = 0  
 	Set @Age = 0  
    else if @AgeCode = 1  
 	Set @Age = 1  
    else if @AgeCode = 2 and @Age < 13  
 	Set @Age = 1  
    else if @AgeCode = 2 and @Age > 12  
 	Set @Age = 2  
    else if @AgeCode = 3  
         Set @Age = @Age  
 
    If @Gender = 'M'     
        Set @Gender = '1'    
    Else If @Gender = 'F'    
        Set @Gender = '2'    

    Set @HospProv = (SELECT top 1 dbo.LU_Province.CIHIValue FROM dbo.H_HospitalProfile LEFT OUTER JOIN    
                       dbo.LU_Province ON dbo.H_HospitalProfile.ProvinceNumber = dbo.LU_Province.Code)    
   
    If @Instto is not null and @HospProv = '5'    
    Begin  
        Declare @InstToV as VarChar(4)  
        select @InstToV = cihivalue from LU_Institution_9 where code = @InstTo   
        if exists (SELECT * FROM dbo.LLU_CMG_InstAcuteON2 WHERE (Cihivalue = @InstToV))    
            set @IsAcuteTo = 1    
    End    
    Else If @Instto is not null    
    Begin    
        if exists (SELECT Top 1 * FROM dbo.LU_Institution_9 WHERE (Code = @InstTo) and LEFT(RIGHT(CIHIValue, 4), 1) = '0')    
             set @IsAcuteTo = 1    
    End    
    If @Instfrom is not null and @HospProv = '5'    
    Begin    
        Declare @InstfromV as VarChar(4)  
        select @InstfromV = cihivalue from LU_Institution_9 where code = @Instfrom   
        if exists (SELECT * FROM dbo.LLU_CMG_InstAcuteON2 WHERE (Cihivalue = @Instfromv))    
            set @IsAcuteFrom = 1    
    End    
    Else If @Instfrom is not null    
    Begin    
        if exists (SELECT Top 1 * FROM dbo.LU_Institution_9 WHERE (Code = @Instfrom) and LEFT(RIGHT(CIHIValue, 4), 1) = '0')    
            set @IsAcuteFrom = 1    
    End    
     
    If rtrim(@DiagTypeAll) = ''  
        Set @DiagTypeAll = '''XXX'''    
 
    Declare @AdmitCat as VarChar(2) 
    If isnull(@DDisposition, ' ') = ' ' and @Weight > 0 and @Abstractid > 0
    Begin
 	Set @AdmitCat = ''
 	set @AdmitCat = (SELECT dbo.LU_EntryCode.CIHIValue FROM dbo.AB_Abstract LEFT OUTER JOIN dbo.LU_EntryCode 
 	ON dbo.AB_Abstract.EntryCode = dbo.LU_EntryCode.Code where dbo.AB_Abstract.abstractid = @Abstractid)
 	If Isnull(@AdmitCat, '') <> 'S'
 		Set @AdmitCat = ''
    End
    Else
 	Set @AdmitCat = 'S'
 
 /*Search main cmg table for Category(MCC) on Most responsible Diagnosis */     
    If (@Weight = 0 and isnull(@AgeCode, 0) <> 1) or (@Weight <> 0 and isnull(@AgeCode, 0) > 1)    
        SELECT Top 1 @MCC = [MCC], @MRDxCMG = [rtCMG], @BranchTemp = [MCCCode]  FROM CMG_Main    
        WHERE ([ProcDiagCode]= @DiagMostResposible) AND ([ICDType] = @ICDType) AND ([Priority] = 3) AND (Gender = @Gender Or Gender = 3)    
    Else if @Weight > 0 and isnull(@DDisposition, ' ') = ' ' and @AdmitCat = 'S' 
    Begin  
        set @MCC = '15X'    
        Set @FinalCMG = '997'    
        Set @CmgDesc = 'Stillbirth'   
    End    
Else if @Weight < 200 
   Begin
      Set @MCC = '99'
      Set @FinalCMG = '999'
   End
   Else if @Weight < 750 AND @Weight >= 200
    Begin    
        set @MCC = '15X'    
        Set @FinalCMG = '625'    
    End    
    Else if @Weight < 1000    
    Begin    
        set @MCC = '15X'    
        Set @MRDxCMG = '626'    
    End    
    Else if @Weight < 1500    
    Begin    
        set @MCC = '15X'    
        Set @MRDxCMG = '628'    
        Set @BranchTemp = 'MC15XM03MD'    
    End    
    Else if @Weight < 2000    
    Begin    
        set @MCC = '15X'    
        Set @MRDxCMG = '632'    
        Set @BranchTemp = 'MC15XM04MD'    
    End    
    Else if @Weight < 2500    
    Begin    
        set @MCC = '15X'    
        Set @MRDxCMG = '640'    
        Set @BranchTemp = 'MC15XM05MD'    
    End    
    Else if @Weight > 2499 AND @Weight <= 9000
    Begin    
        set @MCC = '15X'    
        Set @MRDxCMG = '648'    
        Set @BranchTemp = 'MC15XM06MD'    
    End   
    Else if @Weight > 8999 
    Begin
       Set @MCC = '99'
       Set @FinalCMG = '999'
    End 
   
 /*If you don't get a match and it is a 5 digit diag codee, search main cmg table for Category(MCC)    
     on first four numbers of most responsible Diagnosis */     
    Declare @TypeZero as VarChar(10)  
    IF @MCC is null and Len(@DiagMostResposible) > 4    
    BEGIN    
        SELECT Top 1 @MCC = [MCC], @MRDxCMG = [rtCMG], @BranchTemp = [MCCCode]  FROM CMG_Main    
        WHERE ([ProcDiagCode]= left(@DiagMostResposible,4)) AND ([ICDType] = @ICDType) AND ([Priority] = 3) AND (Gender = @Gender Or Gender = 3)    
        Set @DiagMostResposible = left(@DiagMostResposible,4)    
    END    
   
    If (@BranchTemp = 'MC19XM01MD' or @BranchTemp = 'MC19XM02MD' or @BranchTemp = 'MC19XM05MD') and @DDisposition = 'D' and @LOS < 6    
    Begin    
        Set @FinalCMG = @MRDxCMG + 1    
        Set @Branch = @BranchTemp    
    End    
    Else If (@BranchTemp = 'MC19XM01MD' or @BranchTemp = 'MC19XM02MD' or @BranchTemp = 'MC19XM05MD') and @LOS < 6 and @Instfrom = 0 and @InstTo = 0    
    Begin     
        Set @FinalCMG = @MRDxCMG + 1    
        Set @Branch = @BranchTemp    
    End    
   
    If @ProceduresAll = '' 
    	Set @ProceduresAll = '''XXX'''    
    Declare @DiagMProcAll as VarChar(2000)    
    Declare @DiagMProc as VarChar(2000)    
    Set @DiagMProcAll = ''    
    If @DiagMostResposible <> ''    
    Begin    
        set @DiagMProcAll = '''' + @DiagMostResposible + ''', '     
        set @DiagMProc = '''' + @DiagMostResposible + ''', '     
    End    
   
    Set @DiagMProcAll = replace(@DiagMProcAll, ', ,',  ', ')    
     
    If @DiagnosisAll <> ''    
        Set @DiagMProcAll = @DiagMProcAll + @DiagnosisAll + ', '    
    If @ProceduresAll <> ''    
    Begin    
        Set @DiagMProcAll = @DiagMProcAll + @ProceduresAll    
        Set @DiagMProc = @DiagMProc + @ProceduresAll    
    End    
    If right(@DiagMProcAll, 2) = ', '    
        Set @DiagMProcAll = Left(@DiagMProcAll, len(@DiagMProcAll) - 2)    
    If right(@DiagMProc, 2) = ', '    
        Set @DiagMProc = Left(@DiagMProc, len(@DiagMProc) - 2)    
   
    Set @DiagMProcAll = replace(@DiagMProcAll, ', ,',  '')    
    Set @DiagnosisAll = replace(@DiagnosisAll, ', ,',  '')    
    If right(@DiagMProcAll, 1) <> ''''    
        Set @DiagMProcAll = @DiagMProcAll + ''''    
 --New 2002/09/24  
    set @DiagnosisAll = replace(@DiagMProcAll, @ProceduresAll, '')  
    If right(@DiagnosisAll, 2) = ', '    
        Set @DiagnosisAll = Left(@DiagnosisAll, len(@DiagnosisAll) - 2)    
    If right(@DiagnosisAll, 1) <> ''''    
        Set @DiagnosisAll = @DiagnosisAll + ''''    
   
    if isnull(@DiagnosisAll, '') = ''     
        Set @DiagnosisAll = '''XXXX'''  
   
 /*Search main cmg table for Partition or branch on procedures */       
    If @FinalCMG is NULL    
    Begin    
        set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = rtCMG, @CMGProc = ProcDiagCode FROM CMG_Main     
        WHERE ProcDiagCode in (' + @ProceduresAll + ')     
        AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND Priority < 3 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', @Branch output, @BranchCMG Output, @CMGProc Output    
     
        Set @Partition = SUBSTRING(@Branch, 7, 2)    
        If isnull(@Branch, '0') = '0' and @MCC = '18X' and isnull(@Procedure1, '0') <> '0'    
        begin    
            Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = rtCMG, @CMGProc = ProcDiagCode FROM CMG_Main     
            WHERE ProcDiagCode in (' + @ProceduresAll + ')     
            AND (ICDType = ''' + @ICDType + ''') and translatefrom like ''appdh%'''    
            exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', @Branch output, @BranchCMG Output, @CMGProc Output               If isnull(@Branch, '0') <> '0'    
            begin    
                Set @Branch = 'MC18XS02PR'    
                Set @BranchCMG = '750'    
            end    
        end    
        Else If isnull(@Branch, '0') = '0' and @MCC = '17A' and isnull(@Procedure1, '0') <> '0'    
        begin    
            Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = rtCMG, @CMGProc = ProcDiagCode FROM CMG_Main     
            WHERE ProcDiagCode in (' + @ProceduresAll + ')     
            AND (ICDType = ''' + @ICDType + ''') and translatefrom like ''appdh%'''    
            exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', @Branch output, @BranchCMG Output, @CMGProc Output    
            If isnull(@Branch, '0') <> '0'    
            begin    
                Set @Branch = 'MC17AS03PR'    
                Set @BranchCMG = '728'    
            end    
        end    
        Else If isnull(@Branch, '0') = '0' and @MCC = '17B' and isnull(@Procedure1, '0') <> '0'    
        begin    
            Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = rtCMG, @CMGProc = ProcDiagCode FROM CMG_Main     
            WHERE ProcDiagCode in (' + @ProceduresAll + ')     
            AND (ICDType = ''' + @ICDType + ''') and translatefrom like ''appdh%'''    
            exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', @Branch output, @BranchCMG Output, @CMGProc Output    
            If isnull(@Branch, '0') <> '0'    
            begin    
                Set @FinalCMG = '734'    
                Set @BranchCMG = '734'    
            end    
        end    
        Else if @MCC = '05A' and (@Partition = '06' or @Partition = '07') and SUBSTRING(@Branch, 5, 2) = 'AS'    
        Begin  
            SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main     
            WHERE ProcDiagCode = (@DiagMostResposible) AND (ICDType = @ICDType) AND MCC = @MCC AND (Partition = @Partition) AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= 'AS' ORDER BY SortOrder    
            If @FinalCMG is null    
            Begin    
                If @BranchCMG is null    
                    Set @FinalCMG = @MRDxCMG    
                Else    
                    Set @FinalCMG = @BranchCMG    
            End    
        End    
        else If isnull(@Branch, '0') = '0'    
            Set @Branch = @BranchTemp    
        Set @Partition = SUBSTRING(@Branch, 7, 2)    
        Set @FinalSubBranch = SUBSTRING(@Branch, 5, 2)    
    End    
 /* Extract Branch Procedure code out of procedure string and then     
    look for sub levels with both diagnosis other and remaining    
    procedures. */    
 --According to Shona 2002/09/20 I don't need to do this except for complexity and only then for diagnosis.  
    If @MCC = '15X'    
    Begin    
 
        Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
        WHERE ProcDiagCode in (' + @DiagMProcAll + ') AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''')     
        AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2) = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
    End    
    Else If @MCC = '13X'    
    Begin    
        Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
        WHERE ProcDiagCode in (' + @DiagMProc + ') AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''')     
        AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2) = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
    End    
    Else If @MCC = '24X'    
        Set @FinalCMG = @MRDxCMG    
    Else If @FinalCMG is null and SUBSTRING(@Branch, 6, 1) = 'S'    
    Begin    
        Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
        WHERE ProcDiagCode in (' + @ProceduresAll + ') AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''')     
        AND (Partition = ''' + @Partition + ''') and SUBSTRING(MCCCode, 6, 1) = ''S'' AND Priority = 4 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
    End    
    Else If @FinalCMG is null    
    Begin    
        Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
        WHERE ProcDiagCode in (' + @DiagMProcAll + ') AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''')     
        AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2) = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
    End    
   
    If @MCC = '05A' and (@Partition Between '03' and '15') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02'    
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
        Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
        WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))    
        AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and SortOrder > 6 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
        If @FinalCMG is Null    
            Set @FinalCMG = @FinalCMGTemp    
    End    
    --New 2002/09/20  
    Else If (@MCC = '05A' and (@Partition Between '19' and '21')) or (@MCC = '04X' and (@Partition Between '09' and '11')) or (@MCC = '01X' and (@Partition Between '09' and '11'))  
     or (@MCC = '06X' and (@Partition Between '19' and '21')) or (@MCC = '08X' and (@Partition Between '27' and '29')) or (@MCC = '11X' and (@Partition Between '17' and '19'))  
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
        Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
        WHERE ((ProcDiagCode) in (''' + @DiagMostResposible + '''))    
        AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
   
        If @FinalCMG is Null    
            Set @FinalCMG = @FinalCMGTemp    
    End    
    Else If @MCC = '05A' and (@Partition Between '03' and '15') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) <> 'L02'    
        Set @FinalCMG = Null    
    Else If (@MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02' AND (@LOS >= 4)) or     
        ((@MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02') and (@DDisposition in ('S', 'D') or @IsAcuteTo = 1 or @IsAcutefrom = 1))    
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
        set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))     
        AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and     
        SortOrder > 2 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
        If @FinalCMG is Null    
            Set @FinalCMG = @FinalCMGTemp    
        else if @Partition = '01'    
            Set @FinalCMG = @FinalCMG - 4    
        else     
            Set @FinalCMG = @FinalCMG - 2    
    end    
    Else If @MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02' And @LOS < 4    
        Set @FinalCMG = '218'    
    Else if @MCC = '05A' and (@Partition = '03' or @Partition = '04' or @Partition = '05')    
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
        set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))     
        AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
            
        If @FinalCMG is Null    
            Set @FinalCMG = @FinalCMGTemp    
        If @FinalCMG in ('176', '178', '181')    
            Set @FinalCMG = '183'    
        Else If @FinalCMG in ('177', '179', '182')    
        Begin    
            set @SQL = 'SELECT @Count = count(*) FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))     
            AND (ICDType = ''' + @ICDType + ''') AND MCCCode = ''MC05AS' + @Partition + 'NPL02'''    
            exec sp_executesql @sql, N'@count int output', @Count output    
            If isnull(@Count, 0) > 0    
                Set @FinalCMG = @FinalCMG - 1    
        End    
    end    
    Else if @MCC = '05A' and @Partition = '10' and (@FinalCMG = '181' or @FinalCMG = '182')    
    Begin    
        set @SQL = 'SELECT @Count = count(*) FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))     
        AND (ICDType = ''' + @ICDType + ''') AND MCCCode = ''MC15AS10NPL01'''    
        exec sp_executesql @sql, N'@count int output', @Count output    
        If isnull(@Count, 0) = 0    
            Set @FinalCMG = 194    
    End    
    --New 2002/09/19  
    Else If @MCC = '06X' and (@Partition = '12')  
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
        Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
        WHERE ((ProcDiagCode) in (''' + @DiagMostResposible + '''))    
        AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
        If @FinalCMG is Null    
            Set @FinalCMG = @FinalCMGTemp    
    End    
    --New 2002/09/24  
    Else If @MCC = '08X' and (@Partition in ('04', '05', '07')) and @FinalCMG = '350'  
    Begin    
        set @FinalCMG = NULL  
        Declare @MC08Count as int    
        Set @MC08Count = charindex(@ProceduresAll, @CMGProc, charindex(@ProceduresAll, @CMGProc) + 1)    
        If isnull(@MC08Count, 0) <> 0    
           Set @FinalCMG = 350    
        Else  
        Begin  
           Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
           WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))    
           AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SortOrder > 1 ORDER BY SortOrder'    
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
        End  
        If @FinalCMG is Null    
            Set @FinalCMG = @BranchCMG   
    End    
    --New 2002/09/19  
    Else If @MCC = '09X'  
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
        Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
        WHERE ((ProcDiagCode) in (' + @DiagnosisAll + '))    
        AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
        If @FinalCMG is Null    
            Set @FinalCMG = @FinalCMGTemp    
    End    
    --New 2002/09/25  
    Else If @MCC = '19X' and (@FinalCMG not in ('771', '778', '767'))  
    Begin    
        set @FinalCMGTemp = @FinalCMG   
        Set @FinalCMG = Null   
        Declare @LenDiag as int
        Declare @Diag19X as NVarChar(200)
        set @LenDiag = len(@DiagnosisAll) - len(@DiagMostResposible) - 4
        If @LenDiag < 0
        Begin
 		Set @LenDiag = 0
 		Set @Diag19X = ''''''
        End
        Else
 		Set @Diag19X = right(@DiagnosisAll, @LenDiag)
 
        Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
        WHERE ((ProcDiagCode) in (' + @Diag19X + '))    
        AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
        If @FinalCMG is Null    
        Begin  
           Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
           WHERE ((ProcDiagCode) in (''' + @DiagMostResposible + '''))    
           AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 1 ORDER BY SortOrder'    
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
        End  
    End    
    Else If @MCC = '11X' and (@Partition = '01') and right(@FinalMCCCode, 3) = 'L01' and @LOS < 3 and @DDisposition = 'D'    
        Set @FinalCMG = '999'    
    Else if @MCC = '13X' and @FinalMCCCode like 'MC13XS04%'    
    Begin    
        If @FinalMCCCode = 'MC13XS04PRL02'    
        Begin    
            set @FinalCMGTemp = @FinalCMG    
            Set @FinalCMG = Null    
            set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProc + '))     
            AND (ICDType = ''' + @ICDType + ''')  AND MCCCode in (''MC13XS04MDL03'', ''MC13XS04PRL04'') ORDER BY SortOrder'    
            exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
     
            If @FinalCMG is Null    
                Set @FinalCMG = '579'    
        End    
        Else If @FinalMCCCode = 'MC13XS04MDL01'    
        Begin    
            set @FinalCMGTemp = @FinalCMG    
            Set @FinalCMG = Null    
            set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProc + '))     
            AND (ICDType = ''' + @ICDType + ''')  AND MCCCode = ''MC13XS04PRL02'''    
            exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
                
            If @FinalCMG is Null    
                Set @FinalCMG = @FinalCMGTemp    
        End    
        If @FinalMCCCode = 'MC13XS04MDL03'    
        Begin    
            set @FinalCMGTemp = @FinalCMG    
            Set @FinalCMG = Null    
            set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProc + '))     
            AND (ICDType = ''' + @ICDType + ''')  AND MCCCode = ''MC13XS04PRL04'''    
            exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
                
            If @FinalCMG is Null    
                Set @FinalCMG = @FinalCMGTemp    
        End    
        Else If @FinalMCCCode = 'MC13XS04PRL04'    
            Set @FinalCMG = '579'    
    end    
    Else If @MCC = '14X' and (@Partition = '05') And (@LOS >= 3 or @IsAcuteTo = 1 or @IsAcuteFrom = 1)    
        Set @FinalCMG = '599'    
    Else If @MCC = '15X' and (@Partition Between '03' and '06') and right(@FinalMCCCode, 3) = 'L01' And @LOS < 6    
        Set @FinalCMG = 998    
    Else If @MCC = '15X' and (@Partition = '06') and (right(@FinalMCCCode, 3) in ('L04', 'L05') or @FinalCMG = '648' or  
    (@FinalCMG is null and @MRDxCMG = '648')) -- New added @DiagTyped0 2002/09/25 plus this line  
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
        set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagnosisAll + @DiagTyped0 + '))     
        AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and     
        SortOrder > 4 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
        If @FinalCMG is Null    
            Set @FinalCMG = @FinalCMGTemp    
     
        If @FinalCMG = '647'    
        Begin    
            set @SQL = 'SELECT @Count = count(*) FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagnosisAll + @DiagTyped0 + '))     
            AND (ICDType = ''' + @ICDType + ''') AND MCCCode = ''MC15XM06MOL05'''    
            exec sp_executesql @sql, N'@count int output', @Count output    
            If isnull(@Count, 0) > 0    
                Set @FinalCMG = @FinalCMG - 1    
        End    
    end    
    Else If @MCC = '14X' and (@Partition = '02')-- and right(@FinalMCCCode, 3) = 'L01' commented 2002/09/10   
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
    
        set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagnosisAll + '))     
        AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and    
        SortOrder = 1 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
    
        If @FinalCMG is Null   
            Set @FinalCMG = @FinalCMGTemp    
        Else   
        Begin   
           set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagnosisAll + '))     
           AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and     
           SortOrder > 1 ORDER BY SortOrder'    
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
               
           If @FinalCMG is Null    
               Set @FinalCMG = @FinalCMGTemp    
           If @FinalCMG = '601'    
               Set @FinalCMG = '603'    
           Else If @FinalCMG = '602'    
           Begin    
               set @SQL = 'SELECT @Count = count(*) FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))     
               AND (ICDType = ''' + @ICDType + ''') AND MCCCode = ''MC14XS02MOL03'''    
               exec sp_executesql @sql, N'@count int output', @Count output    
               If isnull(@Count, 0) > 0    
                   Set @FinalCMG = @FinalCMG - 1    
           End    
    End   
    end    
    Else If @MCC = '14X' and (@Partition = '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'XM' and right(@FinalMCCCode, 3) <> 'L01'    
        Set @FinalCMG = 999    
    Else If @MCC = '14X' and (@FinalCMG = '608' or @FinalCMG = '609')    
    Begin    
        If @FinalCMG = '608'   
             Set @FinalCMG = '610'    
        Else If @FinalCMG = '609'    
        Begin    
            set @SQL = 'SELECT @Count = count(*) FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagnosisAll + '))     
            AND (ICDType = ''' + @ICDType + ''') AND MCCCode = ''MC14XM01MOL04'''    
            exec sp_executesql @sql, N'@count int output', @Count output    
            If isnull(@Count, 0) > 0    
                Set @FinalCMG = @FinalCMG - 1    
        End    
    End    
    Else If @MCC = '14X' and (@FinalCMG = '621')    
    Begin    
        If @FinalCMG = '621'    
        Begin    
            set @SQL = 'SELECT @Count = count(*) FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagnosisAll + '))     
            AND (ICDType = ''' + @ICDType + ''') AND MCCCode = ''MC14XM06PRL10'''    
            exec sp_executesql @sql, N'@count int output', @Count output    
            If isnull(@Count, 0) > 0    
                Set @FinalCMG = @FinalCMG - 1    
        End    
    end    
    Else If @MCC = '24X'    
    Begin    
        If len(@DiagTyped1 + @DiagTyped2) > 0   
        Begin    
            set @FinalCMGTemp = @FinalCMG    
            Set @FinalCMG = Null    
            Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
            WHERE ProcDiagCode in (''' + @DiagnosisAll + ''') AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''')     
            AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2) = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'    
            exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
            If isnull(@FinalCMG, '') = ''    
                Set @FinalCMG = '868'    
        End    
        Else If isnull(@FinalCMG, '') = ''    
        Begin    
            Set @FinalCMG = '999'    
            Set @FinalMCCCode = 'MC99XM01MD'    
            Set @MCC = '99'    
        End    
    End    
    Else If @MCC = '25X' and SUBSTRING(@Branch, 6, 1) = 'S' and SUBSTRING(@Branch, 7, 2) = '04' and @FinalCMG in ('351', '350') --New 2002/09/26 Moved from above and this line  
    Begin    
        Declare @MC25Count as int    
        If @FinalCMG = 350    
            Set @MC25Count = charindex(@ProceduresAll, @CMGProc, charindex(@ProceduresAll, @CMGProc) + 1)    
        If isnull(@MC25Count, 0) = 0    
            Set @FinalCMG = 351    
    End    
    If @FinalCMG is null    
    Begin    
        If @BranchCMG is null    
            Set @FinalCMG = @MRDxCMG    
        Else    
            Set @FinalCMG = @BranchCMG    
    End    
    If isnull(@FinalCMG, '') = ''    
        Begin    
            Set @FinalCMG = '999'    
            Set @FinalMCCCode = 'MC99XM01MD'    
            Set @MCC = '99'    
        End    
 /* Calculate Complexity*/    
    if len(@FinalMCCCode) > 10    
        Set @Branch = left(isnull(@FinalMCCCode, ''), 10)    

    Declare @MedSurgInd as VarChar(1) 
    SELECT @MedSurg = cmgmcctype, @MedSurgInd = RIWInd FROM CMG_Etc_2001T WHERE (cmgcode = @FinalCMG) and (ciagegroup = @AgeGroup)    
    Set @PlexA = 0    
    Set @PlexB = 0    
    Set @PlexC = 0    
    Set @PlexD = 0    
    Set @PlexP = 0    
    Set @PlexCMCC = 0    
    If exists (SELECT * FROM CMG_Etc_2001T WHERE (cmgcode = @FinalCMG) AND (cicpxlvl = 9) and (ciagegroup = @AgeGroup)) or @MedSurg = '9'  
        set @Complexity = 9    
  
    If @ICDType = 'C' And patindex('%9672%', @ProceduresAll) > 0 
    Set  @Complexity = 4 
  
    if isnull(@DUsed, '0') = '0'  
         Set @DUsed = 'XXXX'  
 --   Set @DiagTypeAll = replace(@DiagTypeAll, left(@DUsed, 4), ' ')    
    Set @DiagTypeAll = replace(@DiagTypeAll, left(@DiagMostResposible, 4) + '|', 'XXXX|')   
    Set @DiagTypeAll = replace(@DiagTypeAll, @DiagMostResposible + '|', 'XXXXX|')   
    Set @SQL = 'SELECT HomeMCC, COUNT(GrLevel) AS CountLevel, GrLevel FROM dbo.CMG_Complexity    
    WHERE DiagTypeCombine in (' + @DiagTypeAll + ')    
    AND (MCC = Left(''' + @MCC + ''',2)) AND (ICDType = ''' + @ICDType + ''') AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''')    
    GROUP BY HomeMCC, GrLevel Order by GrLevel'    
    exec (@SQL)    
     
    if @Complexity is null and @@RowCount > 0    
    Begin    
        Set @SQL = 'Declare cur_Complexity cursor for     
        SELECT HomeMCC, COUNT(GrLevel) AS CountLevel, GrLevel, Diagnosis FROM dbo.CMG_Complexity    
        WHERE DiagTypeCombine in (' + @DiagTypeAll + ')    
        AND (MCC = Left(''' + @MCC + ''',2)) AND (ICDType = ''' + @ICDType + ''') AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''')    
        GROUP BY HomeMCC, GrLevel, diagnosis Order by GrLevel    
        Open cur_Complexity'    
        Exec (@SQL)    
        fetch next from cur_Complexity    
        into @PlexHomeMcc, @PlexCount, @PlexLevel, @PlexDiagnosis    
        while @@fetch_status = 0    
        begin    
            If not exists(SELECT * FROM dbo.CMG_PlxException WHERE (MCCEx = LEFT(@MCC,2)) AND (CMGEx = @FinalCMG) AND (DiagnosisEx = @PlexDiagnosis) AND ICDType = @ICDType)    
            Begin    
               If @PlexLevel = 'A'     
                   Set @PlexA = @PlexA + @PlexCount    
               Else If @PlexLevel = 'B'    
                   Set @PlexB = @PlexB + @PlexCount    
               Else If @PlexLevel = 'C'    
               Begin    
                   Set @PlexC = @PlexC + @PlexCount    
                   If @PlexHomeMcc <> Left(@MCC,2)    
                       Set @PlexCMCC = 1    
               End                     Else If @PlexLevel = 'D'    
                   Set @PlexD = @PlexD + @PlexCount    
               Else If @PlexLevel = 'P'    
                   Set @PlexP = @PlexP + @PlexCount    
      End                   
           fetch next from cur_Complexity    
           into @PlexHomeMcc, @PlexCount, @PlexLevel, @PlexDiagnosis    
        end    
        Close cur_Complexity    
        Deallocate cur_Complexity    
   
        If @PlexA > 0 or @PlexB > 1 or (@PlexB = 1 and @PlexC > 0 and @PlexCMCC = 1)    
            Set @Complexity = 4    
        Else If @PlexB > 0 or (@PlexC > 1 and @PlexCMCC = 1) or (@PlexC > 10 and @PlexCMCC = 0)    
            Set @Complexity = 3    
        Else If @PlexD > 0 or @PlexP > 0 or (@PlexC = 1 and @PlexCMCC = 1) or (@PlexC > 0 and @PlexC < 11 and @PlexCMCC = 0)  
            Set @Complexity = 2    
        Else    
            Set @Complexity = 1    
    End    
    If isnull(@Complexity, '') = ''    
        Set @Complexity = 1    
     
    Set @MCC = Replace(@MCC, 'X', '')    
    Set @ComplexityLevel = @Complexity    
 /*Get the rest of the stuff */    
    SELECT Top 1 @CmgDesc = cmgdesc, @CmgTrim = ciagtrim, @CmgELOS = ciagelos, @CmgPDRA = ciagpdra, @CmgPDWGT = ciagpdwgt, @CmgRIW = ciagriw    
    FROM dbo.CMG_Etc_2001T WHERE (cmgcode = @FinalCMG) AND (cicpxlvl = @ComplexityLevel) AND (ciagegroup = @AgeGroup)    
 --New 2002/09/30 
    If @MedSurg = 9 
    Set @MedSurg = 1 
 /* If @LOS < @CMGELOS    
        set @RIW = @LOS * */   /*Get RIW$ Value*/    
            If @FinalCMG in ('910', '912', '998', '999') and @LOS < cast(@CMGELOS as decimal(7,4))    
                    Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))    
            else if @DDisposition = ' ' and @LOS <= @CMGTrim and @LOS <= 10    
            Begin    
                Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer     
                    WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr is null and dxyear = 2001)    
                Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))    
            End    
            else if @DDisposition = ' ' and @LOS <= @CMGTrim and @LOS > 10    
            Begin    
                Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer    
                    WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr is null and dxyear = 2001)    
                Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))    
            End    
            Else If @DDisposition = 'S' and @LOS <= cast(@CMGELOS as decimal(7,4))    
                Set @CMGRIW = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,4))) as decimal(7,4))    
            Else If @DDisposition = 'S' and @LOS > cast(@CMGELOS as decimal(7,4)) and @LOS < @CMGTrim    
                Set @CMGRIW = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@CmgELOS as decimal(7,4))) as decimal(7,4))    
            Else If @IsAcuteTo = 1 and @LOS <= 10 and @LOS <= @CMGTrim    
            Begin    
                Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer    
                    WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='O' and dxyear = 2001)    
                Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))    
            End    
            Else If @IsAcuteTo = 1 and @LOS > 10 and @LOS <= @CMGTrim    
            Begin    
                Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
                WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='O' and dxyear = 2001)    
                Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))    
            End    
            Else If @IsAcutefrom = 1 and @LOS <= 10 and @LOS <= @CMGTrim    
            Begin    
                Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer    
                    WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='I' and dxyear = 2001)    
                Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))    
            End    
            Else If @IsAcutefrom = 1 and @LOS > 10 and @LOS <= @CMGTrim  
            Begin    
                Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer    
                    WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='I' and dxyear = 2001)    
                Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))    
            End    
            Else If @LOS > @CMGTrim    
                Set @CMGRIW = cast(cast(@CMGRIW as decimal(7,4)) + (cast(@CmgPDRA as decimal(7,4)) * cast((cast(@LOS as decimal(7,2)) - cast(@CmgELOS as decimal(7,4))) as decimal(7,4))) as decimal(7,4))    
    if @CmgRIW is not null    
    Begin    
        Set @RIW$ = (Select CostPerRiw from H_InstitutionProfile where code = @InstNumber)      
        if isnull(@RIW$, '0') = '0' or @RIW$ = ''    
            set @RIW$ = '0'    
        Set @CMGRIW$ = cast(@CmgRIW as decimal(7,4)) * cast(@RIW$ as decimal(6,2))    
        if @LOS - @CMGTrim > 0    
            Begin    
                Set @CMGMOH = left(@CMGRIW + (((@LOS - @CMGTrim) * cast(@CmgPDWGT as Decimal(4,4))) + (((@CMGTrim - cast(@CMGELOS as decimal(4,2))) * cast(@CmgPDWGT as Decimal(4,4)))) * .2), 10)    
                Set @CMGMOH$ = cast(@CmgMOH as decimal(7,4)) * cast(@RIW$ as decimal(6,2))    
            end    
        Else    
            Begin    
                Set @CMGMOH = @CMGRIW    
                Set @CMGMOH$ = @CMGRIW$    
            end    
        Set @CMGMOH = cast(@CMGMOH as decimal(8,4))    
        Set @CMGRIW$ = cast(@CMGRIW$ as decimal(10,2))    
 
        Set @CMGMOH$ = cast(@CMGMOH$ as decimal(10,2))    
    End    
 
    If @FinalCMG = '997'    
        Set @AcuteQuartile = 'I'    
    Else If @DDisposition = ' '    
        Set @AcuteQuartile = 'D'    
    Else If @DDisposition = 'S'    
        Set @AcuteQuartile = 'S'    
    Else If @IsAcuteFrom = 1 or @IsAcuteTo = 1    
        Set @AcuteQuartile = 'T'    
    Else If @LOS > @CMGTrim    
        Set @AcuteQuartile = 'O'    
    Else If @LOS > cast(@CMGELOS as decimal(7,4))    
        Set @AcuteQuartile = 'B'    
    Else    
        Set @AcuteQuartile = 'I'    
     
    If @MedSurg = '3'
 	Set @MedOrSurg = 'M'
    Else
 	Set @MedOrSurg = 'S'
   
    If isnull(@AbstractID, 0) > 0    
    Begin    
        Delete ab_CMG where Abstractid = @Abstractid and CMG_Year = 2001 and OccurrenceNumber = 1    
        If IsNull(@FinalCMG, '') <> ''    
        Begin    
            If @ICDType = 'C'    
                Set @DiagMostResposible = (select top 1 code from ICD_DiagFile9cm where cihivalue = @DiagMostResposible)    
            Else    
                Set @DiagMostResposible = (select top 1 code from ICD_DiagFile9 where cihivalue = @DiagMostResposible)      
            INSERT INTO [dbo].[AB_CMG] ([AbstractID], [OccurrenceNumber], [CMG_Year], [ICD_Type], [Diagnosis_Code],    
            [Diagnosis_Type], [CMG], [Complexity], [MCC], [AcuteQuartile], [CMG_RIW], [MOH_RIW],    
            [RIW_Dollar], [MOH_Dollar], [CMG_ELOS], [CMG_Trim], [CMG_Description], [MCC_Surg]) VALUES     
            (@AbstractID, 1, 2001, @ICDType, @DiagMostResposible, 11, @FinalCMG, @ComplexityLevel, Left(@MCC, 2), @AcuteQuartile, @CmgRIW, @CmgMOH,     
            cast(@CmgRIW$ as money), cast(@CmgMOH$ as money), @CmgELOS, @CMGTrim, @CMGDesc, @MedOrSurg)    
        End    
    End    
     
    Return 0



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE        PROCEDURE [P_CMG2001_T]   
    @Age as Int,   
    @AgeCode as int, 
    @LOS as int,   
    @AcuteLOS as int,   
    @ICDType as VarChar(2),   
    @Gender as VarChar(1),   
    @Weight as int,   
    @DDisposition as VarChar(2),   
    @InstNumber as int,   
    @InstTo as int,   
    @InstFrom as int,   
    @DiagMostResposible as VarChar(10),   
    @DiagnosisAll as VarChar(500),   
    @DiagTypeAll as VarChar(500),   
    @DiagTyped1 as VarChar(500),   
    @DiagTyped2 as VarChar(500),   
    @DiagTyped0 as VarChar(500),   
    @DiagTyped3 as VarChar(500),   
    @ProceduresAll as VarChar(1000),   
    @Procedure1 as VarChar(10),   
    @FinalCMG as VarChar(3) output,   
    @ComplexityLevel as Int output,   
    @MCC as VarChar(3) output,   
    @AcuteQuartile as VarChar(10) output,   
    @CmgRIW as VarChar(10) output,   
    @CmgMOH as VarChar(10) output,   
    @CmgRIW$ as VarChar(20) output,   
    @CmgMOH$ as VarChar(20) output,   
    @CmgELOS as VarChar(10) output,   
    @CmgTrim as VarChar(10) output,   
    @CmgDesc as VarChar(60) output,   
    @MedOrSurg as VarChar(1) output,  
    @AbstractID as Int,
    @Occurance as int = 1,	--Ticket 9011 Placeholder for VB6 not used otherwise in this proc
    @ExpiryDate as varchar(10) = NULL, --Ticket 9011 Placeholder for VB6 not used otherwise in this proc
--Ticket 9373
      @AgeGroup as int,
      @Plx4 as VarChar(1),
	  @FlagRecord as VarChar(1) = 'N'
 AS    
    Declare @MRDxCMG VarChar(8)   
    Declare @Branch VarChar(10)   
    Declare @BranchTemp VarChar(10)   
    Declare @BranchCMG VarChar(3)   
    Declare @IBranchCMG VarChar(3)   
    Declare @Partition as VarChar(2)   
    Declare @FinalSubBranch as VarChar(2)   
    Declare @FinalMCCCode as VarChar(14)   
    Declare @CmgALOS as VarChar(10)   
    Declare @CmgPDRA as VarChar(10)   
    Declare @CmgPDWGT as VarChar(10)   
    Declare @Cat1 as int   
    Declare @Cat2 as int   
    Declare @PlexHomeMcc as VarChar(2)   
    Declare @PlexCount as int   
    Declare @PlexLevel as VarChar(1)   
    Declare @PlexDiagnosis as VarChar(6)   
    Declare @PlexA as int   
    Declare @PlexB as int   
    Declare @PlexC as int   
    Declare @PlexD as int   
    Declare @PlexP as int   
    Declare @Complexity as int   
    Declare @PlexCMCC as int   
    Declare @MedSurg as int    
    Declare @RIW$ as VarChar(10)   
    Declare @CMGProc as Varchar(12)   
    Declare @FinalMCCCodeTemp as VarChar(14)   
    Declare @FinalCMGTemp as VarChar(14)   
    Declare @RIWDeath as VarChar(10)   
    Declare @HospProv as VarChar(2)   
    Declare @IsAcuteTo as bit   
    Declare @IsAcuteFrom as bit   
    Declare @SQL as NVarChar(3000)   
    Declare @count as int   
    Declare @AgeNumber as int   
    Declare @SDate as datetime   
 set @SDate = getdate()   
    Set Nocount on
    Set @IsAcuteTo = 0   
    Set @IsAcuteFrom = 0   
    
   If @AgeCode = 1 and @Age > 28 
   Set @AgeCode = 3 
 
    If @Gender = 'M'   
        Set @Gender = '1'   
    Else If @Gender = 'F'   
        Set @Gender = '2'   
    If isnull(@DiagMostResposible, '0') = '0'   
        Set @DiagMostResposible = ''   
    
    if exists (SELECT * FROM LU_Institution_10 WHERE code = @InstTo and InstCareType = 'A')   
	set @IsAcuteTo = 1  
    if exists (SELECT * FROM LU_Institution_10 WHERE code = @InstFrom and InstCareType = 'A')   
	set @IsAcuteFrom = 1  
    
    If rtrim(@DiagTypeAll) = ''   
        Set @DiagTypeAll = '''XXX'''   
    If @ProceduresAll = ''   
        Set @ProceduresAll = '''XXX'''   
    
    Declare @DiagMProcAll as VarChar(2000)   
    Declare @DiagMProc as VarChar(2000)   
    Set @DiagMProcAll = ''   
    If @DiagMostResposible <> ''   
    Begin   
        set @DiagMProcAll = '''' + @DiagMostResposible + ''', '    
        set @DiagMProc = '''' + @DiagMostResposible + ''', '    
    End   
    Set @DiagMProcAll = replace(@DiagMProcAll, ', ,',  ', ')   
    Set @DiagTypeAll = replace(@DiagTypeAll, ', ,',  ', ')   
    
    If @DiagnosisAll <> ''   
        Set @DiagMProcAll = @DiagMProcAll + @DiagnosisAll + ', '   

    If @ProceduresAll <> ''   
    Begin   
        Set @DiagMProcAll = @DiagMProcAll + @ProceduresAll   
        Set @DiagMProc = @DiagMProc + @ProceduresAll   
    End   
    If right(@DiagMProcAll, 2) = ', '   
        Set @DiagMProcAll = Left(@DiagMProcAll, len(@DiagMProcAll) - 2)   
    If right(@DiagMProc, 2) = ', '   
        Set @DiagMProc = Left(@DiagMProc, len(@DiagMProc) - 2)   
    Set @DiagMProcAll = replace(@DiagMProcAll, ', ,',  '')   
  
    If right(@DiagMProcAll, 1) <> ''''   
        Set @DiagMProcAll = @DiagMProcAll + ''''   
    If isnull(@DiagnosisAll, '') = '' 
        Set @DiagnosisAll = '''XXX''' 

    If (@Weight = 0 and isnull(@AgeCode, 0) <> 1) or (@Weight <> 0 and isnull(@AgeCode, 0) > 1)   
        SELECT Top 1 @MCC = [MCC], @MRDxCMG = [CMG], @BranchTemp = [MCCCode]  FROM CMG_Main2002   
        WHERE ([DiagProcCode]= @DiagMostResposible) AND ([Priority] = 3) AND (Gender = @Gender Or Gender = 3)   
    Else if @DDisposition = '09'   
    Begin   
        set @MCC = '99'
        Set @FinalCMG = '997'
        Set @CmgDesc = 'Stillbirth'
    End   
    Else if @Weight < 750 AND @Weight >= 200
    Begin
        Set @MCC = '99'
        Set @FinalCMG = '999'
    End
    Else if @Weight < 750   
    Begin   
        set @MCC = '15X'   
        Set @FinalCMG = '625'   
    End   
    Else if @Weight < 1000   
    Begin   
        set @MCC = '15X'   
        Set @MRDxCMG = '626'   
    End   
    Else if @Weight < 1500   
    Begin   
        set @MCC = '15X'   
        Set @MRDxCMG = '628'   
        Set @BranchTemp = 'MC15XM03MD'   
    End   
    Else if @Weight < 2000   
    Begin   
        set @MCC = '15X'   
        Set @MRDxCMG = '632'   
        Set @BranchTemp = 'MC15XM04MD'   
    End   
    Else if @Weight < 2500   
    Begin   
        set @MCC = '15X'   
        Set @MRDxCMG = '640'   
        Set @BranchTemp = 'MC15XM05MD'   
    End   
    Else if @Weight > 2499 AND @Weight < 9000
    Begin   
        set @MCC = '15X'   
        Set @MRDxCMG = '648'   
        Set @BranchTemp = 'MC15XM06MD'   
    End 
   Else if @Weight > 8999 
   Begin
      Set @MCC = '99'
      Set @FinalCMG = '999'
   End 
 
    If (@BranchTemp in ('MC19XM01MD', 'MC19XM02MD', 'MC19XM05MD') and (@DDisposition = '05' and @LOS < 6)) 
    Begin   
        Set @FinalCMG = @MRDxCMG + 1   
        Set @Branch = @BranchTemp   
    End   
    Else If (@BranchTemp = 'MC19XM01MD' or @BranchTemp = 'MC19XM02MD' or @BranchTemp = 'MC19XM05MD') and @LOS < 6 and @IsAcuteTo = 0 and @IsAcuteTo = 0  and @DDisposition not in ('06', '07') 
    Begin 
        Set @FinalCMG = @MRDxCMG + 1   
        Set @Branch = @BranchTemp   
    End   
    If left(@DiagMostResposible, 3) = 'Z53' 
    Begin 
	   Set @FinalCMG = @MRDxCMG  
	   Set @FinalMCCCode = @BranchTemp         
    End 

    If @DDisposition = '08' 
    Begin 
	   set @FinalCMG = 996 
    End 
 
    If @FinalCMG is NULL   
    Begin   
        Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2002    
        WHERE DiagProcCode in (' + @ProceduresAll + ') AND MCC = ''' + @MCC + ''' AND Priority < 3 ORDER BY SortOrder'   
        exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
		@Branch output, @BranchCMG Output, @CMGProc Output
        Set @Partition = SUBSTRING(@Branch, 7, 2)   
        If isnull(@Branch, '0') = '0' and @MCC = '18X' and isnull(@Procedure1, '0') <> '0'   
        begin   
            Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2002    
            WHERE DiagProcCode in (' + @ProceduresAll + ')  and translatefrom like ''appdh%'' ORDER BY SortOrder'   
            exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
		@Branch output, @BranchCMG Output, @CMGProc Output
            If isnull(@Branch, '0') <> '0'   
            begin   
                Set @Branch = 'MC18XS02PR'   
                Set @BranchCMG = '750'   
            end   
        end   
        Else If isnull(@Branch, '0') = '0' and @MCC = '17A' and isnull(@Procedure1, '0') <> '0'   
        begin   
            Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2002    
            WHERE DiagProcCode in (' + @ProceduresAll + ') and translatefrom like ''appdh%'' ORDER BY SortOrder'   
            exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output',
		@Branch output, @BranchCMG Output, @CMGProc Output
 
            If isnull(@Branch, '0') <> '0'   
            begin   
	           Set @Branch = Null 
	           Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2002    
	           WHERE DiagProcCode in (' + @DiagMProcAll + ') AND MCCCode = ''MC17AS03MDL01'' ORDER BY SortOrder'   
	           exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
			@Branch output, @BranchCMG Output, @CMGProc Output
	 
	           If isnull(@Branch, '0') = '0'   
	           begin   
	                   Set @FinalMCCCode = 'MC17AS03PR'   
	                   Set @FinalCMG = '728'   
	           End 
            end   
        end   
        Else If isnull(@Branch, '0') = '0' and @MCC = '17B' and isnull(@Procedure1, '0') <> '0'   
        begin   
            Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2002    
            WHERE DiagProcCode in (' + @ProceduresAll + ') and translatefrom like ''appdh%'' ORDER BY SortOrder'   
            exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
		@Branch output, @BranchCMG Output, @CMGProc Output
            If isnull(@Branch, '0') <> '0'   
            begin   
                Set @FinalCMG = '734'   
                Set @BranchCMG = '734'   
            end   
        end   
        Else if @MCC = '05A' and (@Partition = '06' or @Partition = '07') and SUBSTRING(@Branch, 5, 2) = 'AS'   
        Begin   
            SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002    
            WHERE DiagProcCode = (@DiagMostResposible) AND MCC = @MCC AND (Partition = @Partition) AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= 'AS' ORDER BY SortOrder   
            If @FinalCMG is null   
            Begin   
                If @BranchCMG is null   
                    Set @FinalCMG = @MRDxCMG   
                Else   
                    Set @FinalCMG = @BranchCMG   
            End   
        End   
        else If isnull(@Branch, '0') = '0'   
            Set @Branch = @BranchTemp   
        Set @Partition = SUBSTRING(@Branch, 7, 2)   
	if isnull(@FinalSubBranch, '') = ''
	Begin
            Set @SQL = 'SELECT Top 1 @FinalSubBranch = MedicalSurgical FROM CMG_Main2002   WHERE MCCCode = ''' + @Branch + ''''   
            exec sp_executesql @sql, N'@FinalSubBranch VarChar(1) output', @FinalSubBranch output
	    if isnull(@FinalSubBranch, '') = ''
		Set @FinalSubBranch = '2'
	end
    End   

    If @MCC = '15X'   
    Begin   
        Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
        WHERE DiagProcCode in (' + @DiagMProcAll + ') AND (MCC = ''' + @MCC + ''')    
        AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
    End   
    Else If @MCC = '13X'   
    Begin   
        Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
        WHERE DiagProcCode in (' + @DiagMProc + ') AND (MCC = ''' + @MCC + ''')    
        AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
    End   
    Else If @MCC = '24X'   
        Set @FinalCMG = @MRDxCMG   
    Else If @FinalCMG is null and @BranchCMG is not null and @MCC not in ('05A', '08X', '10X') 
    Begin 
	Declare @ProcTemp as VarChar(15) 
        set @FinalCMGTemp = @BranchCMG   
	Set @ProcTemp = @CMGProc 
	Set @BranchTemp = @BranchCMG 
        Set @BranchCMG = Null   
 
        Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2002    
        WHERE DiagProcCode in (' + @ProceduresAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
        AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
        exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', @Branch output, @BranchCMG Output, @CMGProc Output   
	If @BranchCMG is null 

		Begin 
	           Set @FinalCMG = @FinalCMGTemp 
	           Set @FinalMCCCode = @BranchTemp 
	           Set @CMGProc = @ProcTemp 
		End 
	Else 
		Begin 
	           Set @FinalCMG = @BranchCMG 
	           Set @FinalMCCCode = @Branch 
		End 
    End 
    Else If @FinalCMG is null   
	Begin   
	        Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002    
	        WHERE DiagProcCode in (' + @DiagMProcAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
	        AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
	        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
	End   
 
    If @MCC = '05A' and (@Partition Between '03' and '15') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02'   
    Begin   
	declare @Diag05 as VarChar(1000) 
        set @FinalCMGTemp = @FinalCMG   
        Set @FinalCMG = Null   
 
   set @Diag05 = replace(@DiagMProcAll, replace(replace(Replace(substring(@DiagTypeAll, charindex('|3', @DiagTypeAll) -5, 6), '|', ''), ' ', ''), '''', ''), 'xxx') 
        Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
        WHERE (DiagProcCode) in (' + @Diag05 + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
        AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch +  ''' and SortOrder > 6 ORDER BY SortOrder'   
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
    
        If @FinalCMG is Null   
            Set @FinalCMG = @FinalCMGTemp   
    End   
    --New 2002/09/20  
    Else If (@MCC = '05A' and (@Partition Between '19' and '21')) or (@MCC = '04X' and (@Partition Between '09' and '11')) or (@MCC = '01X' and (@Partition Between '09' and '11'))  
     or (@MCC = '06X' and (@Partition Between '19' and '21')) or (@MCC = '08X' and (@Partition Between '27' and '29')) or (@MCC = '11X' and (@Partition Between '17' and '19'))  
     or (@MCC = '05B' and (@Partition Between '12' and '14')) 
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
        Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
        WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
        AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
   
        If @FinalCMG is Null and isnull(@FinalCMGTemp, '0')  = '902' 
	Begin 
           Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002    
           WHERE DiagProcCode in (' + @ProceduresAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
           AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
	End 
	Else If @FinalCMG is Null 
            Set @FinalCMG = @FinalCMGTemp    
    End    
    Else If @MCC = '05A' and (@Partition Between '03' and '15') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) <> 'L02'   
        Set @FinalCMG = Null   
    Else If (@MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02' AND (@LOS >= 4)) or    
        ((@MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02') and (@DDisposition in ('07', '06') or @IsAcuteTo = 1 or @IsAcutefrom = 1))   
    Begin   
        set @FinalCMGTemp = @FinalCMG   
        Set @FinalCMG = Null   
        Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002    
        WHERE (DiagProcCode) in (' + @DiagMProcAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
        AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' and SortOrder > 2 ORDER BY SortOrder'   
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
        If @FinalCMG is Null   
            Set @FinalCMG = @FinalCMGTemp   
        else if @Partition = '01'   
            Set @FinalCMG = @FinalCMG - 4   
        else   
            Set @FinalCMG = @FinalCMG - 2   
    end   
    Else If @MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02' And @LOS < 4   
        Set @FinalCMG = '218'   
    Else if @MCC = '05A' and (@Partition = '03' or @Partition = '04' or @Partition = '05')   
    Begin   
        set @FinalCMGTemp = @FinalCMG   
        Set @FinalCMG = Null   
        set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
        AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
           
        If @FinalCMG is Null   
            Set @FinalCMG = @FinalCMGTemp   
        If @FinalCMG in ('176', '178', '181')   
            Set @FinalCMG = '183'   
        Else If @FinalCMG in ('177', '179', '182')   
        Begin   
            set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
            AND MCCCode = ''MC05AS' + @Partition + 'NPL02'''   
            exec sp_executesql @sql, N'@count int output', @Count output   
            If isnull(@Count, 0) > 0   
                Set @FinalCMG = @FinalCMG - 1   
        End   
    end   
    Else if @MCC = '05A' and @Partition = '10' and (@FinalCMG = '181' or @FinalCMG = '182')   
    Begin   
        set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
        AND MCCCode = ''MC05AS10NPL01'''   
        exec sp_executesql @sql, N'@count int output', @Count output   
        If isnull(@Count, 0) = 0   
            Set @FinalCMG = 194   
    End   
    --New 2002/09/19  
    Else If @MCC = '06X' and (@Partition = '12')  
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
        Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
        WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
         AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
        If @FinalCMG is Null    
            Set @FinalCMG = @FinalCMGTemp    
    End    
    --New 2002/09/24  
    Else If @MCC = '08X' and (@Partition in ('04', '05', '07')) and @FinalCMG = '350'  
    Begin    
        set @FinalCMG = NULL  
        Declare @MC08Count as int    
        set @SQL = 'SELECT @MC08Count = count(*) FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @ProceduresAll + '))    
        AND MCCCode = ''MC08XS' + @Partition + 'PRL01''' 
        exec sp_executesql @sql, N'@MC08Count int output', @MC08Count output   
 
        If isnull(@MC08Count, 0) > 1 and len(@ProceduresAll) > 30 
           Set @FinalCMG = 350    
        Else  
        Begin  
           Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
           WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
            AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SortOrder > 1 ORDER BY SortOrder'    
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
        End  
 
        If @FinalCMG is Null    
            Set @FinalCMG = @BranchCMG   
    End    
    Else If @MCC = '08X' and (@Partition between '10' and '25') and SUBSTRING(@Branch, 6, 1) = 'S' 
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
        Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
        WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
         AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
        If @FinalCMG is Null    
            Set @FinalCMG = @FinalCMGTemp    
    End    
    --New 2002/09/19  
    Else If @MCC = '09X'  
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
        Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
        WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
         AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
        If @FinalCMG is Null    
            Set @FinalCMG = @FinalCMGTemp    
    End    
    Else If @MCC = '10X' and @Partition = '01' and SUBSTRING(@FinalMCCCode, 5, 2) = 'XS' 
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
        Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
        WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
         AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
        If @FinalCMG is Null    
            Set @FinalCMG = @FinalCMGTemp    
    End    
    --New 2002/09/25  
    Else If @MCC = '19X' and (@FinalCMG not in ('771', '778', '767')) and @FinalCMG is not null 
    Begin    
        set @FinalCMGTemp = @FinalCMG    
        Set @FinalCMG = Null    
        Declare @LenDiag as int 
        Declare @Diag19X as NVarChar(200) 
        set @LenDiag = len(@DiagMProcAll) - len(@DiagMostResposible) - 4 
        If @LenDiag < 0 
        Begin 
           Set @LenDiag = 0 
           Set @Diag19X = '''''' 
        End 
        Else 
           Set @Diag19X = right(@DiagMProcAll, @LenDiag) 
        set @Diag19X = replace(@Diag19X, replace(replace(Replace(substring(@DiagTypeAll, charindex('|3', @DiagTypeAll) -5, 6), '|', ''), ' ', ''), '''', ''), 'xxx') 
        Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
        WHERE ((DiagProcCode) in (' + @Diag19X + '))    
        AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
        If @FinalCMG is Null    
        Begin  
           Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
           WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
            AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 1 ORDER BY SortOrder'    
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
        End  
    End   
     Else If @MCC = '11X' and (@Partition = '01') and right(@FinalMCCCode, 3) = 'L01' 
      Begin	
	If @LOS > 2 or @DDisposition in ('06','07') or @isAcuteTo = 1 or @isAcuteFrom = 1
		Set @FinalCMG = '520'	
	Else if @LOS < 2 AND @isAcuteTo = 0 and @isAcuteFrom = 0
		Set @FinalCMG = '999'	
      End
    Else if @MCC = '13X' and @FinalMCCCode like 'MC13XS04%'   
    Begin   
        If @FinalMCCCode = 'MC13XS04PRL02'   
        Begin   
            set @FinalCMGTemp = @FinalCMG   
            Set @FinalCMG = Null   
            set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProc + '))    
            AND MCCCode in (''MC13XS04MDL03'', ''MC13XS04PRL04'') ORDER BY SortOrder'   
            exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
    
            If @FinalCMG is Null   
                Set @FinalCMG = '579'   
        End   
        Else If @FinalMCCCode = 'MC13XS04MDL01'   
        Begin   
            set @FinalCMGTemp = @FinalCMG   
            Set @FinalCMG = Null   
            set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProc + '))    
            AND MCCCode = ''MC13XS04PRL02'''   
            exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
 
            If @FinalCMG is Null   
                Set @FinalCMG = @FinalCMGTemp   
        End   
        If @FinalMCCCode = 'MC13XS04MDL03'   
        Begin   
            set @FinalCMGTemp = @FinalCMG   
            Set @FinalCMG = Null   
            set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProc + '))    
            AND MCCCode = ''MC13XS04PRL04'''   
            exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
               
            If @FinalCMG is Null   
                Set @FinalCMG = @FinalCMGTemp   
        End   
        Else If @FinalMCCCode = 'MC13XS04PRL04'   
            Set @FinalCMG = '579'   
    end   
    Else If (@MCC = '14X' and (@Partition = '05')) And (@LOS >= 3 or @IsAcuteTo = 1 or @IsAcuteTo = 1) 
        Set @FinalCMG = '599'   
    Else If @MCC = '14X' and (@Partition = '01') and @FinalSubBranch = 1 and ((@FinalCMG = '612' or (@FinalCMG is null and @MRDxCMG = '612')))
    Begin   
        Set @FinalCMG = Null   
        set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002 WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
        AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
        SortOrder = 1 ORDER BY SortOrder' 
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
        If @FinalCMG is Null   
            Set @FinalCMG = 600   
    end   
    Else If @MCC = '15X' and (@Partition Between '03' and '06') and right(@FinalMCCCode, 3) = 'L01' And @LOS < 6   
        Set @FinalCMG = 998   
--Added on Ticket 9161
      Else If @MCC= '15X' and (@Partition Between '03' and '06') and right(@FinalMCCCode, 3) = 'L01' and (@DDisposition in ('07', '06') or @IsAcuteTo = 1 or @IsAcutefrom = 1 or @LOS > 6) 
      Begin

	  If @Partition = '03'
          	Set @FinalCMG = 627  
	  If @Partition = '04'
          	Set @FinalCMG = 630  
	  If @Partition = '05'
          	Set @FinalCMG = 636  
	  If @Partition = '06'
          	Set @FinalCMG = 643  
      End

    Else If @MCC = '15X' and (@Partition = '06') and ((@FinalCMG = '646' or (@FinalCMG is null and @MRDxCMG = '646')) or 
	(@FinalCMG = '647' or (@FinalCMG is null and @MRDxCMG = '647')) or (@FinalCMG = '648' or (@FinalCMG is null and @MRDxCMG = '648')))
    Begin   
        Set @FinalCMG = Null   
        set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProcAll + @DiagTyped0 + @DiagTyped3 + '))    
        AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
        SortOrder = 4 ORDER BY SortOrder' 
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
        If @FinalCMG is Null   
	Begin
	        set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
	        AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
	        SortOrder > 4 ORDER BY SortOrder' 
	        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
	        If @FinalCMG is Null   
	            Set @FinalCMG = 648   
	End
    end   
    Else If @MCC = '14X' and (@Partition = '02')-- and right(@FinalMCCCode, 3) = 'L01'   
    Begin   
        set @FinalCMGTemp = @FinalCMG   
        Set @FinalCMG = Null   
        set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002 WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
        AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
        SortOrder = 1 ORDER BY SortOrder'   
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
           
        If @FinalCMG is Null   
            Set @FinalCMG = @FinalCMGTemp   
        Else  
        Begin  
           set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
           SortOrder > 1 ORDER BY SortOrder'   
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
      
           If @FinalCMG is Null   
               Set @FinalCMG = @FinalCMGTemp   
           If @FinalCMG = '601'   
               Set @FinalCMG = '603'   
           Else If @FinalCMG = '602'   
           Begin   
               set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
               AND MCCCode = ''MC14XS02MOL03'''   
               exec sp_executesql @sql, N'@count int output', @Count output   
               If isnull(@Count, 0) > 0   
                   Set @FinalCMG = @FinalCMG - 1   
           End   
    End  
    end   
    Else If @MCC = '14X' and (@Partition = '02') and right(@FinalMCCCode, 3) <> 'L01' and SUBSTRING(@FinalMCCCode, 5, 2) <>  'XM'   
        Set @FinalCMG = 999   
    Else If @MCC = '14X' and (@FinalCMG = '608' or @FinalCMG = '609')   
    Begin   
        If @FinalCMG = '608'   
            Set @FinalCMG = '610'   
        Else If @FinalCMG = '609'   
        Begin   
            set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProcAll +  '))    
            AND MCCCode = ''MC14XM01MOL04'''   
            exec sp_executesql @sql, N'@count int output', @Count output   
            If isnull(@Count, 0) > 0   
                Set @FinalCMG = @FinalCMG - 1   
        End   
    End   
    Else If @MCC = '14X' and (@FinalCMG in ('620', '621'))   
    Begin   
        If @FinalCMG = '621'   
        Begin   
            set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagnosisAll + '))    
            AND MCCCode = ''MC14XM06PRL10'''   
            exec sp_executesql @sql, N'@count int output', @Count output   
            If isnull(@Count, 0) > 0   
                Set @FinalCMG = @FinalCMG - 1   
        End   
    end   
    Else If @MCC = '24X'   
    Begin   
	If len(@DiagTyped1 + @DiagTyped2) > 0   
        Begin   
            set @FinalCMGTemp = @FinalCMG   
            Set @FinalCMG = Null   
            Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
            WHERE DiagProcCode in (' + @DiagnosisAll + ') AND (MCC = ''' + @MCC + ''')    
            AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
            exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
            If isnull(@FinalCMG, '') = ''   
                Set @FinalCMG = '868'   
        End   
        Else  
        Begin   
            Set @FinalCMG = '999'   
            Set @FinalMCCCode = 'MC99XM01MD'   
            Set @MCC = '99'   
        End   
    End   
    Else if @MCC = '21X' and (@Partition in ('05', '06'))   
    Begin   
        set @FinalCMGTemp = @FinalCMG   
        Set @FinalCMG = Null   
        set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
        AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
        If @FinalCMG is Null   
            Set @FinalCMG = @FinalCMGTemp   
        If @FinalCMG in ('176', '178', '181')   
            Set @FinalCMG = '183'   
        Else If @FinalCMG in ('177', '179', '182')   
        Begin   
            set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
            AND MCCCode = ''MC21XS' + @Partition + 'NPL02'''   
            exec sp_executesql @sql, N'@count int output', @Count output   
            If isnull(@Count, 0) > 0   
                Set @FinalCMG = @FinalCMG - 1   
        End   
    end   
    Else If @MCC = '25X' and SUBSTRING(@Branch, 6, 1) = 'S' and SUBSTRING(@Branch, 7, 2) = '05' and @FinalCMG in ('351', '350') 
    Begin
	Declare @MC25Proc as VarChar(15) 
	Declare @MC25Count as int   
        If @FinalCMG = 350   
	Begin 
            set @SQL = 'SELECT @MC25Count = count(*) FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @ProceduresAll + '))    
            AND MCCCode = ''MC25XS05PRL03'''   
            exec sp_executesql @sql, N'@MC25Count int output', @MC25Count output   
		If @MC25Count = 1 
		Begin
			set @SQL = 'SELECT  @MC25Proc = diagproccode FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @ProceduresAll + '))    
			AND MCCCode = ''MC25XS05PRL03'''   
			exec sp_executesql @sql, N'@MC25Proc varchar(15) output', @MC25Proc output                   

	               If len(replace(@ProceduresAll, '''' + @MC25Proc + '''', '')) < (len(@ProceduresAll) - len(@MC25Proc) - 3)
				Set @MC25Count = 2 
		End
	End 
 
        If isnull(@MC25Count, 0) < 2   
            Set @FinalCMG = 351   
    End   
 
    if len(@FinalMCCCode) > 10   
        Set @Branch = left(isnull(@FinalMCCCode, ''), 10)   
    
    If @FinalCMG is null   
    Begin   
        If @BranchCMG is null   
            Set @FinalCMG = @MRDxCMG   
        Else   
            Set @FinalCMG = @BranchCMG   
        If @FinalCMG is null 
             Set @FinalCMG = '999'   
    End   

      --Ticket 9330
      If @MCC is null
	set @MCC = '99'
  
    if len(@FinalMCCCode) > 10   
        Set @Branch = left(isnull(@FinalMCCCode, ''), 10)  

    Declare @MedSurgInd as VarChar(1) 
    SELECT @MedSurg = cmgmcctype, @MedSurgInd = RIWInd FROM CMG_Etc_2001T WHERE (cmgcode = @FinalCMG) and (ciagegroup = @AgeGroup)    
    Set @PlexA = 0   
    Set @PlexB = 0   
    Set @PlexC = 0   
    Set @PlexD = 0   
    Set @PlexP = 0   
    Set @PlexCMCC = 0   
    If exists (SELECT * FROM CMG_Etc_2001T WHERE ((cmgcode = @FinalCMG) AND (cicpxlvl = 9) and (ciagegroup = @AgeGroup)) or @MedSurg = '9') 
        set @Complexity = 9   
    Set @DiagTypeAll = replace(@DiagTypeAll, @DiagMostResposible + '|', 'XXXXX|')   
    
    Set @SQL = 'SELECT HomeMCC, COUNT(GrLevel) AS CountLevel, GrLevel, Diagnosis FROM CMG_Complexity_2001T   
    WHERE DiagTypeCombine in (' + @DiagTypeAll + ')   
    and (MCC = LEFT(''' + @MCC + ''',2)) AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''') GROUP BY HomeMCC, GrLevel, diagnosis Order by GrLevel'   
    exec (@SQL)   
    if @Complexity is null and @@RowCount > 0   
    Begin   
        Set @SQL = 'Declare cur_Complexity cursor for SELECT HomeMCC, COUNT(GrLevel) AS CountLevel, GrLevel, Diagnosis FROM CMG_Complexity_2001T   
        WHERE DiagTypeCombine in (' + @DiagTypeAll + ')   
        and (MCC = LEFT(''' + @MCC + ''',2)) AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''') GROUP BY HomeMCC, GrLevel, diagnosis Order by GrLevel   
        Open cur_Complexity'   
        exec (@SQL) 
        fetch next from cur_Complexity   
        into @PlexHomeMcc, @PlexCount, @PlexLevel, @PlexDiagnosis   
        while @@fetch_status = 0   
        begin   
            If not exists(SELECT * FROM dbo.CMG_PlxException2001 WHERE (MCCEx = LEFT(@MCC,2)) AND (CMGEx = @FinalCMG) AND (DiagnosisEx = @PlexDiagnosis))   
            Begin   
                If @PlexLevel = 'A'   
                    Set @PlexA = @PlexA + @PlexCount   
                Else If @PlexLevel = 'B'   
                    Set @PlexB = @PlexB + @PlexCount   
                Else If @PlexLevel = 'C'   
                Begin   
                    Set @PlexC = @PlexC + @PlexCount   
                    If @PlexHomeMcc <> Left(@MCC,2)   
                        Set @PlexCMCC = 1   
                End   
                Else If @PlexLevel = 'D'   
                    Set @PlexD = @PlexD + @PlexCount   
                Else If @PlexLevel = 'P'   
                    Set @PlexP = @PlexP + @PlexCount   
            End   
            fetch next from cur_Complexity into @PlexHomeMcc, @PlexCount, @PlexLevel, @PlexDiagnosis   
        end   
        Close cur_Complexity   
        Deallocate cur_Complexity   
       
        If @PlexA > 0 or @PlexB > 1 or (@PlexB = 1 and @PlexC > 0 and @PlexCMCC = 1)   
            Set @Complexity = 4   
        Else If @PlexB > 0 or (@PlexC > 1 and @PlexCMCC = 1) or (@PlexC > 10 and @PlexCMCC = 0)   
            Set @Complexity = 3   
        Else If @PlexD > 0 or @PlexP > 0 or (@PlexC = 1 and @PlexCMCC = 1)    
            or (@PlexC > 0 and @PlexC < 11 and @PlexCMCC = 0)   
            Set @Complexity = 2   
        Else   
            Set @Complexity = 1   
    End   

    If isnull(@Complexity, '') = ''           Set @Complexity = 1   
    
    Set @MCC = Replace(@MCC, 'X', '')   
    Set @ComplexityLevel = @Complexity   
    SELECT Top 1 @CmgDesc = cmgdesc, @CmgTrim = ciagtrim, @CmgELOS = ciagelos, @CmgPDRA = ciagpdra, @CmgPDWGT = ciagpdwgt, @CmgRIW = ciagriw   
    FROM dbo.CMG_Etc_2001T WHERE (cmgcode = @FinalCMG) AND (cicpxlvl = @ComplexityLevel) AND (ciagegroup = @AgeGroup) --AND (cmgmcctype = @MedSurg)   
--print @CmgDesc 
--print @CmgTrim 
--print @CmgELOS 
--print @CmgPDRA 
 
 --New 2002/09/30 
    If @MedSurg = 9 
   Set @MedSurg = 1   
    If @FinalCMG in ('910', '912', '998', '999') and @LOS < cast(@CMGELOS as decimal(7,4))   
        Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
    else if @DDisposition = '07' and @LOS <= @CMGTrim and @LOS <= 10   
    Begin   
        Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer    
            WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr is null and dxyear = 2001)   
        Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
    End   
    else if @DDisposition = '07' and @LOS <= @CMGTrim and @LOS > 10   
    Begin 
        Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
            WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr is null and dxyear = 2001)   
        Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
    End   
    Else If @DDisposition = '06' and @LOS <= cast(@CMGELOS as decimal(7,4))   
        Set @CMGRIW = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,4))) as decimal(7,4))   
    Else If @DDisposition = '06' and @LOS > cast(@CMGELOS as decimal(7,4)) and @LOS < @CMGTrim   
        Set @CMGRIW = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@CmgELOS as decimal(7,4))) as decimal(7,4))   
    Else If @IsAcuteTo = 1 and @LOS <= 10 and @LOS <= @CMGTrim   
    Begin   
        Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
            WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='O' and dxyear = 2001)   
        Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
    End   
    Else If @IsAcuteTo = 1 and @LOS > 10 and @LOS <= @CMGTrim   
    Begin   
        Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
            WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='O' and dxyear = 2001)   
        Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
    End   
    Else If @IsAcuteFrom = 1 and @LOS <= 10 and @LOS <= @CMGTrim   
    Begin   
        Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
            WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='I' and dxyear = 2001)   
        Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
    End   
    Else If @IsAcuteFrom = 1 and @LOS > 10 and @LOS <= @CMGTrim   
    Begin   
        Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
            WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='I' and dxyear = 2001)   
        Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
    End   
    Else If @LOS > @CMGTrim   
        Set @CMGRIW = cast(cast(@CMGRIW as decimal(7,4)) + (cast(@CmgPDRA as decimal(7,4)) * cast((cast(@LOS as decimal(7,2)) - cast(@CmgELOS as decimal(7,4))) as decimal(7,4))) as decimal(7,4))   
    if @CmgRIW is not null   
    Begin   
        Select @RIW$ = CostPerRiw from H_InstitutionProfile where code = @InstNumber   
        if isnull(@RIW$, '0') = '0' or @RIW$ = ''   
            set @RIW$ = '0'   
        Set @CMGRIW$ = cast(@CmgRIW as decimal(7,4)) * cast(@RIW$ as decimal(6,2))   
        if @LOS - @CMGTrim > 0   
        Begin   
            Set @CMGMOH = left(@CMGRIW + (((@LOS - @CMGTrim) * cast(@CmgPDWGT as Decimal(4,4))) + (((@CMGTrim - cast(@CMGELOS as decimal(4,2))) * cast(@CmgPDWGT as Decimal(4,4)))) * .2), 10)   
            Set @CMGMOH$ = cast(@CmgMOH as decimal(7,4)) * cast(@RIW$ as decimal(6,2))   
        end   
        Else   
        Begin   
            Set @CMGMOH = @CMGRIW   
            Set @CMGMOH$ = @CMGRIW$   
        end   
        Set @CMGMOH = cast(@CMGMOH as decimal(8,4))   
        Set @CMGRIW$ = cast(@CMGRIW$ as decimal(10,2))   
        Set @CMGMOH$ = cast(@CMGMOH$ as decimal(10,2))   
    End   
   
    If @DDisposition = '07'   
        Set @AcuteQuartile = 'D'   
    Else If @DDisposition = '06'   
        Set @AcuteQuartile = 'S'   
    Else If @IsAcuteFrom = 1 or @IsAcuteTo = 1 --or @DDisposition = '01' ticket 5711  
        Set @AcuteQuartile = 'T'   
    Else If @LOS > @CMGTrim   
        Set @AcuteQuartile = 'O'   
    Else If @LOS > cast(@CMGELOS as decimal(7,4))   
        Set @AcuteQuartile = 'B'   
    Else   
        Set @AcuteQuartile = 'I'   
  
    If @MedSurgInd = '2' 
	Set @MedOrSurg = 'M' 
    Else 
	Set @MedOrSurg = 'S' 
    
    If isnull(@AbstractID, 0) > 0   
    Begin   
        Delete ab_CMG where Abstractid = @Abstractid and CMG_Year = 2001 and OccurrenceNumber = 1   
        If IsNull(@FinalCMG, '') <> ''   
        Begin   
            Set @DiagMostResposible = (select top 1 code from ICD_DiagFile10 where cihivalue = @DiagMostResposible)   
            INSERT INTO [dbo].[AB_CMG] ([AbstractID], [OccurrenceNumber], [CMG_Year], [ICD_Type], [Diagnosis_Code],   
            [Diagnosis_Type], [CMG], [Complexity], [MCC], [AcuteQuartile], [CMG_RIW], [MOH_RIW],   
            [RIW_Dollar], [MOH_Dollar], [CMG_ELOS], [CMG_Trim], [CMG_Description], [MCC_Surg]) VALUES    
            (@AbstractID, 1, 2001, 'T', @DiagMostResposible, 11, @FinalCMG, @ComplexityLevel, Left(@MCC, 2), @AcuteQuartile, @CmgRIW, @CmgMOH,    
            cast(@CmgRIW$ as money), cast(@CmgMOH$ as money), @CmgELOS, @CMGTrim, @CMGDesc, @MedOrSurg)   
        End   
    
    End   
    set nocount off    
--    print datediff(ms, @SDate, getdate())   
    Return 0




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE                 PROCEDURE [P_CMG2002_9]    
     @Age as Int,    
     @AgeCode as int,
     @LOS as int,    
     @AcuteLOS as int,    
     @ICDType as VarChar(2),    
     @Gender as VarChar(1),    
     @Weight as int,    
     @DDisposition as VarChar(2),    
     @InstNumber as int,    
     @InstTo as int,    
     @InstFrom as int,    
     @DiagMostResposible as VarChar(10),   
     @DiagnosisAll as VarChar(500),   
     @DiagTypeAll as VarChar(500),   
     @DiagTyped1 as VarChar(500),   
     @DiagTyped2 as VarChar(500),   
     @DiagTyped0 as VarChar(500),   
     @DiagTyped3 as VarChar(500),   
     @ProceduresAll as VarChar(500),   
     @Procedure1 as VarChar(10),   
     @FinalCMG as VarChar(3) output,    
     @ComplexityLevel as Int output,    
     @MCC as VarChar(3) output,    
     @AcuteQuartile as VarChar(10) output,    
     @CmgRIW as VarChar(10) output,    
     @CmgMOH as VarChar(10) output,    
     @CmgRIW$ as VarChar(20) output,    
     @CmgMOH$ as VarChar(20) output,    
     @CmgELOS as VarChar(10) output,    
     @CmgTrim as VarChar(10) output,    
     @CmgDesc as VarChar(60) output,    
     @MedOrSurg as VarChar(1) output, 
     @AbstractID as int = Null,
      @Occurance as int = 1,	--Ticket 9011 Placeholder for VB6 not used otherwise in this proc
      @ExpiryDate as varchar(10) = NULL, --Ticket 9011 Placeholder for VB6 not used otherwise in this proc
--Ticket 9373
      @AgeGroup as int,
      @Plx4 as VarChar(1),
	  @FlagRecord as VarChar(1) = 'N'
  AS     
     Declare @MRDxCMG VarChar(8)    
     Declare @Branch VarChar(10)    
     Declare @BranchTemp VarChar(10)    
     Declare @BranchCMG VarChar(3)    
     Declare @Partition as VarChar(2)    
     Declare @FinalSubBranch as VarChar(2)    
     Declare @FinalMCCCode as VarChar(14)    
     Declare @CmgALOS as VarChar(10)    
     Declare @CmgPDRA as VarChar(10)    
     Declare @CmgPDWGT as VarChar(10)    
     Declare @Cat1 as int    
     Declare @Cat2 as int    
     Declare @PlexDiagnosis as VarChar(6)    
     Declare @PlexHomeMcc as VarChar(2)    
     Declare @PlexCount as int    
     Declare @PlexLevel as VarChar(1)    
     Declare @PlexA as int    
     Declare @PlexB as int    
     Declare @PlexC as int    
     Declare @PlexD as int    
     Declare @PlexP as int    
     Declare @Complexity as int    
     Declare @PlexCMCC as int    
     Declare @MedSurg as int     
     Declare @RIW$ as VarChar(10)    
     Declare @CMGProc as Varchar(10)    
     Declare @FinalMCCCodeTemp as VarChar(14)    
     Declare @FinalCMGTemp as VarChar(14)    
     Declare @RIWDeath as VarChar(10)    
     Declare @HospProv as VarChar(2)    
     Declare @IsAcuteTo as bit    
     Declare @IsAcuteFrom as bit    
     Declare @SQL as NVarChar(3000)    
     Declare @count as int    
     Declare @AgeNumber as int    
     Declare @DUsed as VarChar(10)    
 
     Set @IsAcuteTo = 0    
     Set @IsAcuteFrom = 0    
     If @AgeCode = 0  
   Set @Age = 0  
     else if @AgeCode = 1  
   Set @Age = 1  
     else if @AgeCode = 2 and @Age < 13  
   Set @Age = 1  
     else if @AgeCode = 2 and @Age > 12  
   Set @Age = 2  
     else if @AgeCode = 3  
          Set @Age = @Age  
  
     If @Gender = 'M'     
         Set @Gender = '1'    
     Else If @Gender = 'F'    
         Set @Gender = '2'    
 
     Set @HospProv = (SELECT top 1 dbo.LU_Province.CIHIValue FROM dbo.H_HospitalProfile LEFT OUTER JOIN    
                        dbo.LU_Province ON dbo.H_HospitalProfile.ProvinceNumber = dbo.LU_Province.Code)    
    
     If @Instto is not null and @HospProv = '5'    
     Begin  
         Declare @InstToV as VarChar(4)  
         select @InstToV = cihivalue from LU_Institution_9 where code = @InstTo   
         if exists (SELECT * FROM dbo.LLU_CMG_InstAcuteON2 WHERE (Cihivalue = @InstToV))    
             set @IsAcuteTo = 1    
     End    
     Else If @Instto is not null    
     Begin    
         if exists (SELECT Top 1 * FROM dbo.LU_Institution_9 WHERE (Code = @InstTo) and LEFT(RIGHT(CIHIValue, 4), 1) = '0')    
              set @IsAcuteTo = 1    
     End    
     If @Instfrom is not null and @HospProv = '5'    
     Begin    
         Declare @InstfromV as VarChar(4)  
         select @InstfromV = cihivalue from LU_Institution_9 where code = @Instfrom   
         if exists (SELECT * FROM dbo.LLU_CMG_InstAcuteON2 WHERE (Cihivalue = @Instfromv))    
             set @IsAcuteFrom = 1    
     End    
     Else If @Instfrom is not null    
     Begin    
         if exists (SELECT Top 1 * FROM dbo.LU_Institution_9 WHERE (Code = @Instfrom) and LEFT(RIGHT(CIHIValue, 4), 1) = '0')    
             set @IsAcuteFrom = 1    
     End    
      
     If rtrim(@DiagTypeAll) = ''  
         Set @DiagTypeAll = '''XXX'''    
  
     Declare @AdmitCat as VarChar(2) 
     If isnull(@DDisposition, ' ') = ' ' and @Weight > 0 and @Abstractid > 0
     Begin
   Set @AdmitCat = ''
   set @AdmitCat = (SELECT dbo.LU_EntryCode.CIHIValue FROM dbo.AB_Abstract LEFT OUTER JOIN dbo.LU_EntryCode 
   ON dbo.AB_Abstract.EntryCode = dbo.LU_EntryCode.Code where dbo.AB_Abstract.abstractid = @Abstractid)
   If Isnull(@AdmitCat, '') <> 'S'
           Set @AdmitCat = ''
     End
     Else
   Set @AdmitCat = 'S'
  
  /*Search main cmg table for Category(MCC) on Most responsible Diagnosis */     
     If (@Weight = 0 and isnull(@AgeCode, 0) <> 1) or (@Weight <> 0 and isnull(@AgeCode, 0) > 1)    
         SELECT Top 1 @MCC = [MCC], @MRDxCMG = [rtCMG], @BranchTemp = [MCCCode]  FROM CMG_Main    
         WHERE ([ProcDiagCode]= @DiagMostResposible) AND ([ICDType] = @ICDType) AND ([Priority] = 3) AND (Gender = @Gender Or Gender = 3)    
     Else if @Weight > 0 and isnull(@DDisposition, ' ') = ' ' and @AdmitCat = 'S' 
     Begin  
         set @MCC = '15X'    
         Set @FinalCMG = '997'    
         Set @CmgDesc = 'Stillbirth'   
     End    
     Else if @Weight < 200 
     Begin
        Set @MCC = '99'
        Set @FinalCMG = '999'
     End
     Else if @Weight < 750 AND @Weight >= 200
     Begin    
         set @MCC = '15X'    
         Set @FinalCMG = '625'    
     End    
     Else if @Weight < 1000    
     Begin    
         set @MCC = '15X'    
         Set @MRDxCMG = '626'    
     End    
     Else if @Weight < 1500    
     Begin    
         set @MCC = '15X'    
         Set @MRDxCMG = '628'    
         Set @BranchTemp = 'MC15XM03MD'    
     End    
     Else if @Weight < 2000    
     Begin    
         set @MCC = '15X'    
         Set @MRDxCMG = '632'    
         Set @BranchTemp = 'MC15XM04MD'    
     End    
     Else if @Weight < 2500    
     Begin    
         set @MCC = '15X'    
         Set @MRDxCMG = '640'    
         Set @BranchTemp = 'MC15XM05MD'    
     End    
     Else if @Weight > 2499 AND @Weight <= 9000
     Begin    
         set @MCC = '15X'    
         Set @MRDxCMG = '648'    
         Set @BranchTemp = 'MC15XM06MD'    
     End    
     Else if @Weight > 8999 
     Begin
         Set @MCC = '99'
         Set @FinalCMG = '999'
     End
    
  /*If you don't get a match and it is a 5 digit diag codee, search main cmg table for Category(MCC)    
      on first four numbers of most responsible Diagnosis */     
     Declare @TypeZero as VarChar(10)  
     IF @MCC is null and Len(@DiagMostResposible) > 4    
     BEGIN    
         SELECT Top 1 @MCC = [MCC], @MRDxCMG = [rtCMG], @BranchTemp = [MCCCode]  FROM CMG_Main    
         WHERE ([ProcDiagCode]= left(@DiagMostResposible,4)) AND ([ICDType] = @ICDType) AND ([Priority] = 3) AND (Gender = @Gender Or Gender = 3)    
         Set @DiagMostResposible = left(@DiagMostResposible,4)    
     END    
    
     If (@BranchTemp = 'MC19XM01MD' or @BranchTemp = 'MC19XM02MD' or @BranchTemp = 'MC19XM05MD') and @DDisposition = 'D' and @LOS < 6    
     Begin    
         Set @FinalCMG = @MRDxCMG + 1    
         Set @Branch = @BranchTemp    
     End    
     Else If (@BranchTemp = 'MC19XM01MD' or @BranchTemp = 'MC19XM02MD' or @BranchTemp = 'MC19XM05MD') and @LOS < 6 and @Instfrom = 0 and @InstTo = 0    
     Begin     
         Set @FinalCMG = @MRDxCMG + 1    
         Set @Branch = @BranchTemp    
     End    
    
     If @ProceduresAll = '' 
           Set @ProceduresAll = '''XXX'''    
     Declare @DiagMProcAll as VarChar(2000)    
     Declare @DiagMProc as VarChar(2000)    
     Set @DiagMProcAll = ''    
     If @DiagMostResposible <> ''    
     Begin    
         set @DiagMProcAll = '''' + @DiagMostResposible + ''', '     
         set @DiagMProc = '''' + @DiagMostResposible + ''', '     
     End    
    
     Set @DiagMProcAll = replace(@DiagMProcAll, ', ,',  ', ')    
      
     If @DiagnosisAll <> ''    
         Set @DiagMProcAll = @DiagMProcAll + @DiagnosisAll + ', '    
     If @ProceduresAll <> ''    
     Begin    
         Set @DiagMProcAll = @DiagMProcAll + @ProceduresAll    
         Set @DiagMProc = @DiagMProc + @ProceduresAll    
     End    
     If right(@DiagMProcAll, 2) = ', '    
         Set @DiagMProcAll = Left(@DiagMProcAll, len(@DiagMProcAll) - 2)    
     If right(@DiagMProc, 2) = ', '    
         Set @DiagMProc = Left(@DiagMProc, len(@DiagMProc) - 2)    
    
     Set @DiagMProcAll = replace(@DiagMProcAll, ', ,',  '')    
     Set @DiagnosisAll = replace(@DiagnosisAll, ', ,',  '')    
     If right(@DiagMProcAll, 1) <> ''''    
         Set @DiagMProcAll = @DiagMProcAll + ''''    
  --New 2002/09/24  
     set @DiagnosisAll = replace(@DiagMProcAll, @ProceduresAll, '')  
     If right(@DiagnosisAll, 2) = ', '    
         Set @DiagnosisAll = Left(@DiagnosisAll, len(@DiagnosisAll) - 2)    
     If right(@DiagnosisAll, 1) <> ''''    
         Set @DiagnosisAll = @DiagnosisAll + ''''    
    
     if isnull(@DiagnosisAll, '') = ''     
         Set @DiagnosisAll = '''XXXX'''  
    
  /*Search main cmg table for Partition or branch on procedures */       
     If @FinalCMG is NULL    
     Begin    
         set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = rtCMG, @CMGProc = ProcDiagCode FROM CMG_Main     
         WHERE ProcDiagCode in (' + @ProceduresAll + ')     
         AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND Priority < 3 ORDER BY SortOrder'    
         exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', @Branch output, @BranchCMG Output, @CMGProc Output    
      
         Set @Partition = SUBSTRING(@Branch, 7, 2)    
         If isnull(@Branch, '0') = '0' and @MCC = '18X' and isnull(@Procedure1, '0') <> '0'    
         begin    
             Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = rtCMG, @CMGProc = ProcDiagCode FROM CMG_Main     
             WHERE ProcDiagCode in (' + @ProceduresAll + ')     
             AND (ICDType = ''' + @ICDType + ''') and translatefrom like ''appdh%'''    
             exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', @Branch output, @BranchCMG Output, @CMGProc Output               If isnull(@Branch, '0') <> '0'    
             begin    
                 Set @Branch = 'MC18XS02PR'    
                 Set @BranchCMG = '750'    
             end    
         end    
         Else If isnull(@Branch, '0') = '0' and @MCC = '17A' and isnull(@Procedure1, '0') <> '0'    
         begin    
             Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = rtCMG, @CMGProc = ProcDiagCode FROM CMG_Main     
             WHERE ProcDiagCode in (' + @ProceduresAll + ')     
             AND (ICDType = ''' + @ICDType + ''') and translatefrom like ''appdh%'''    
             exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', @Branch output, @BranchCMG Output, @CMGProc Output    
             If isnull(@Branch, '0') <> '0'    
             begin    
                 Set @Branch = 'MC17AS03PR'    
                 Set @BranchCMG = '728'    
             end    
         end    
         Else If isnull(@Branch, '0') = '0' and @MCC = '17B' and isnull(@Procedure1, '0') <> '0'    
         begin    
             Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = rtCMG, @CMGProc = ProcDiagCode FROM CMG_Main     
             WHERE ProcDiagCode in (' + @ProceduresAll + ')     
             AND (ICDType = ''' + @ICDType + ''') and translatefrom like ''appdh%'''    
             exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', @Branch output, @BranchCMG Output, @CMGProc Output    
             If isnull(@Branch, '0') <> '0'    
             begin    
                 Set @FinalCMG = '734'    
                 Set @BranchCMG = '734'    
             end    
         end    
         Else if @MCC = '05A' and (@Partition = '06' or @Partition = '07') and SUBSTRING(@Branch, 5, 2) = 'AS'    
         Begin  
             SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main     
             WHERE ProcDiagCode = (@DiagMostResposible) AND (ICDType = @ICDType) AND MCC = @MCC AND (Partition = @Partition) AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= 'AS' ORDER BY SortOrder    
             If @FinalCMG is null    
             Begin    
                 If @BranchCMG is null    
                     Set @FinalCMG = @MRDxCMG    
                 Else    
                     Set @FinalCMG = @BranchCMG    
             End    
         End    
         else If isnull(@Branch, '0') = '0'    
             Set @Branch = @BranchTemp    
         Set @Partition = SUBSTRING(@Branch, 7, 2)    
         Set @FinalSubBranch = SUBSTRING(@Branch, 5, 2)   
     End    
  /* Extract Branch Procedure code out of procedure string and then     
     look for sub levels with both diagnosis other and remaining    
     procedures. */    
  --According to Shona 2002/09/20 I don't need to do this except for complexity and only then for diagnosis.  
     If @MCC = '15X'    
     Begin    
  
         Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
         WHERE ProcDiagCode in (' + @DiagMProcAll + ') AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''')     
         AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2) = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'    
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
     End    
     Else If @MCC = '13X'    
     Begin    
         Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
         WHERE ProcDiagCode in (' + @DiagMProc + ') AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''')     
         AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2) = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'    
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
     End    
     Else If @MCC = '24X'    
         Set @FinalCMG = @MRDxCMG    
     Else If @FinalCMG is null and SUBSTRING(@Branch, 6, 1) = 'S'    
     Begin    
         Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
         WHERE ProcDiagCode in (' + @ProceduresAll + ') AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''')     
         AND (Partition = ''' + @Partition + ''') and SUBSTRING(MCCCode, 6, 1) = ''S'' AND Priority = 4 ORDER BY SortOrder'    
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
     End    
     Else If @FinalCMG is null    
     Begin    
         Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
         WHERE ProcDiagCode in (' + @DiagMProcAll + ') AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''')     
         AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2) = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'    
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
     End    
    
     If @MCC = '05A' and (@Partition Between '03' and '15') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02'    
     Begin    
         set @FinalCMGTemp = @FinalCMG    
         Set @FinalCMG = Null    
         Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
         WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))    
         AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and SortOrder > 6 ORDER BY SortOrder'    
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
         If @FinalCMG is Null    
             Set @FinalCMG = @FinalCMGTemp    
     End    
     --New 2002/09/20  
     Else If (@MCC = '05A' and (@Partition Between '19' and '21')) or (@MCC = '04X' and (@Partition Between '09' and '11')) or (@MCC = '01X' and (@Partition Between '09' and '11'))  
      or (@MCC = '06X' and (@Partition Between '19' and '21')) or (@MCC = '08X' and (@Partition Between '27' and '29')) or (@MCC = '11X' and (@Partition Between '17' and '19'))  
     Begin    
         set @FinalCMGTemp = @FinalCMG    
         Set @FinalCMG = Null    
         Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
         WHERE ((ProcDiagCode) in (''' + @DiagMostResposible + '''))    
         AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 ORDER BY SortOrder'    
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
    
         If @FinalCMG is Null    
             Set @FinalCMG = @FinalCMGTemp    
     End    
     Else If @MCC = '05A' and (@Partition Between '03' and '15') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) <> 'L02'    
         Set @FinalCMG = Null    
     Else If (@MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02' AND (@LOS >= 4)) or     
         ((@MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02') and (@DDisposition in ('S', 'D') or @IsAcuteTo = 1 or @IsAcutefrom = 1))    
     Begin    
         set @FinalCMGTemp = @FinalCMG    
         Set @FinalCMG = Null    
         set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))     
         AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and     
         SortOrder > 2 ORDER BY SortOrder'    
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
         If @FinalCMG is Null    
             Set @FinalCMG = @FinalCMGTemp    
         else if @Partition = '01'    
             Set @FinalCMG = @FinalCMG - 4    
         else     
             Set @FinalCMG = @FinalCMG - 2    
     end    
     Else If @MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02' And @LOS < 4    
         Set @FinalCMG = '218'    
     Else if @MCC = '05A' and (@Partition = '03' or @Partition = '04' or @Partition = '05')    
     Begin    
         set @FinalCMGTemp = @FinalCMG    
         Set @FinalCMG = Null    
         set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))     
         AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' ORDER BY SortOrder'    
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
             
         If @FinalCMG is Null    
             Set @FinalCMG = @FinalCMGTemp    
         If @FinalCMG in ('176', '178', '181')    
             Set @FinalCMG = '183'    
         Else If @FinalCMG in ('177', '179', '182')    
         Begin    
             set @SQL = 'SELECT @Count = count(*) FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))     
             AND (ICDType = ''' + @ICDType + ''') AND MCCCode = ''MC05AS' + @Partition + 'NPL02'''    
             exec sp_executesql @sql, N'@count int output', @Count output    
             If isnull(@Count, 0) > 0    
                 Set @FinalCMG = @FinalCMG - 1    
         End    
     end    
     Else if @MCC = '05A' and @Partition = '10' and (@FinalCMG = '181' or @FinalCMG = '182')    
     Begin    
         set @SQL = 'SELECT @Count = count(*) FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))     
         AND (ICDType = ''' + @ICDType + ''') AND MCCCode = ''MC15AS10NPL01'''    
         exec sp_executesql @sql, N'@count int output', @Count output    
         If isnull(@Count, 0) = 0    
             Set @FinalCMG = 194    
     End    
     --New 2002/09/19  
     Else If @MCC = '06X' and (@Partition = '12')  
     Begin    
         set @FinalCMGTemp = @FinalCMG    
         Set @FinalCMG = Null    
         Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
         WHERE ((ProcDiagCode) in (''' + @DiagMostResposible + '''))    
         AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
         If @FinalCMG is Null    
             Set @FinalCMG = @FinalCMGTemp    
     End    
     --New 2002/09/24  
     Else If @MCC = '08X' and (@Partition in ('04', '05', '07')) and @FinalCMG = '350'  
     Begin    
         set @FinalCMG = NULL  
         Declare @MC08Count as int    
         Set @MC08Count = charindex(@ProceduresAll, @CMGProc, charindex(@ProceduresAll, @CMGProc) + 1)    
         If isnull(@MC08Count, 0) <> 0    
            Set @FinalCMG = 350    
         Else  
         Begin  
            Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
            WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))    
            AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SortOrder > 1 ORDER BY SortOrder'    
            exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
         End  
         If @FinalCMG is Null    
             Set @FinalCMG = @BranchCMG   
     End    
     --New 2002/09/19  
     Else If @MCC = '09X'  
     Begin    
         set @FinalCMGTemp = @FinalCMG    
         Set @FinalCMG = Null    
         Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
         WHERE ((ProcDiagCode) in (' + @DiagnosisAll + '))    
         AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
         If @FinalCMG is Null    
             Set @FinalCMG = @FinalCMGTemp    
     End    
     --New 2002/09/25  
     Else If @MCC = '19X' and (@FinalCMG not in ('771', '778', '767'))  
     Begin    
         set @FinalCMGTemp = @FinalCMG   
         Set @FinalCMG = Null   
         Declare @LenDiag as int
         Declare @Diag19X as NVarChar(200)
         set @LenDiag = len(@DiagnosisAll) - len(@DiagMostResposible) - 4
         If @LenDiag < 0
         Begin
           Set @LenDiag = 0
           Set @Diag19X = ''''''
         End
         Else
           Set @Diag19X = right(@DiagnosisAll, @LenDiag)
  
         Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
         WHERE ((ProcDiagCode) in (' + @Diag19X + '))    
         AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
         If @FinalCMG is Null    
         Begin  
            Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
            WHERE ((ProcDiagCode) in (''' + @DiagMostResposible + '''))    
            AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 1 ORDER BY SortOrder'    
            exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
         End  
     End    
     Else If @MCC = '11X' and (@Partition = '01') and right(@FinalMCCCode, 3) = 'L01' and @LOS < 3 and @DDisposition = 'D'    
         Set @FinalCMG = '999'    
     Else if @MCC = '13X' and @FinalMCCCode like 'MC13XS04%'    
     Begin    
         If @FinalMCCCode = 'MC13XS04PRL02'    
         Begin    
             set @FinalCMGTemp = @FinalCMG    
             Set @FinalCMG = Null    
             set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProc + '))     
             AND (ICDType = ''' + @ICDType + ''')  AND MCCCode in (''MC13XS04MDL03'', ''MC13XS04PRL04'') ORDER BY SortOrder'    
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
      
             If @FinalCMG is Null    
                 Set @FinalCMG = '579'    
         End    
         Else If @FinalMCCCode = 'MC13XS04MDL01'    
         Begin    
             set @FinalCMGTemp = @FinalCMG    
             Set @FinalCMG = Null    
             set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProc + '))     
             AND (ICDType = ''' + @ICDType + ''')  AND MCCCode = ''MC13XS04PRL02'''    
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
                 
             If @FinalCMG is Null    
                 Set @FinalCMG = @FinalCMGTemp    
         End    
         If @FinalMCCCode = 'MC13XS04MDL03'    
         Begin    
             set @FinalCMGTemp = @FinalCMG    
             Set @FinalCMG = Null    
             set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProc + '))     
             AND (ICDType = ''' + @ICDType + ''')  AND MCCCode = ''MC13XS04PRL04'''    
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
                 
             If @FinalCMG is Null    
                 Set @FinalCMG = @FinalCMGTemp    
         End    
         Else If @FinalMCCCode = 'MC13XS04PRL04'    
             Set @FinalCMG = '579'    
     end    
     Else If @MCC = '14X' and (@Partition = '05') And (@LOS >= 3 or @IsAcuteTo = 1 or @IsAcuteFrom = 1)    
         Set @FinalCMG = '599'    
     Else If @MCC = '15X' and (@Partition Between '03' and '06') and right(@FinalMCCCode, 3) = 'L01' And @LOS < 6    
         Set @FinalCMG = 998    
     Else If @MCC = '15X' and (@Partition = '06') and ((@FinalCMG = '646' or (@FinalCMG is null and @MRDxCMG = '646')) or 
   (@FinalCMG = '647' or (@FinalCMG is null and @MRDxCMG = '647')) or (@FinalCMG = '648' or (@FinalCMG is null and @MRDxCMG = '648')))
     Begin    
         set @FinalCMGTemp = @FinalCMG    
         Set @FinalCMG = Null    
         set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProcAll + @DiagTyped0 + @DiagTyped3 + '))     
         AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and     
         SortOrder > 4 ORDER BY SortOrder'    
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
         If @FinalCMG is Null    
             Set @FinalCMG = @FinalCMGTemp    
      
         If @FinalCMG = '647'    
         Begin    
             set @SQL = 'SELECT @Count = count(*) FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))     
             AND (ICDType = ''' + @ICDType + ''') AND MCCCode = ''MC15XM06MOL05'''    
             exec sp_executesql @sql, N'@count int output', @Count output    
             If isnull(@Count, 0) > 0    
                 Set @FinalCMG = @FinalCMG - 1    
         End    
     end    
     Else If @MCC = '14X' and (@Partition = '02')-- and right(@FinalMCCCode, 3) = 'L01' commented 2002/09/10   
     Begin    
         set @FinalCMGTemp = @FinalCMG    
         Set @FinalCMG = Null    
     
         set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagnosisAll + '))     
         AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and    
         SortOrder = 1 ORDER BY SortOrder'    
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
     
         If @FinalCMG is Null   
             Set @FinalCMG = @FinalCMGTemp    
         Else   
         Begin   
            set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagnosisAll + '))     
            AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= ''' + @FinalSubBranch + ''' and     
            SortOrder > 1 ORDER BY SortOrder'    
            exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
                
            If @FinalCMG is Null    
                Set @FinalCMG = @FinalCMGTemp    
            If @FinalCMG = '601'    
                Set @FinalCMG = '603'    
            Else If @FinalCMG = '602'    
            Begin    
                set @SQL = 'SELECT @Count = count(*) FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagMProcAll + '))     
                AND (ICDType = ''' + @ICDType + ''') AND MCCCode = ''MC14XS02MOL03'''    
                exec sp_executesql @sql, N'@count int output', @Count output    
                If isnull(@Count, 0) > 0    
                    Set @FinalCMG = @FinalCMG - 1    
            End    
     End   
     end    
     Else If @MCC = '14X' and (@Partition = '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'XM' and right(@FinalMCCCode, 3) <> 'L01'    
         Set @FinalCMG = 999    
     Else If @MCC = '14X' and (@FinalCMG = '608' or @FinalCMG = '609')    
     Begin    
         If @FinalCMG = '608'   
              Set @FinalCMG = '610'    
         Else If @FinalCMG = '609'    
         Begin    
             set @SQL = 'SELECT @Count = count(*) FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagnosisAll + '))     
             AND (ICDType = ''' + @ICDType + ''') AND MCCCode = ''MC14XM01MOL04'''    
             exec sp_executesql @sql, N'@count int output', @Count output    
             If isnull(@Count, 0) > 0    
                 Set @FinalCMG = @FinalCMG - 1    
         End    
     End    
     Else If @MCC = '14X' and (@FinalCMG = '621')    
     Begin    
         If @FinalCMG = '621'    
         Begin    
             set @SQL = 'SELECT @Count = count(*) FROM CMG_Main WHERE ((ProcDiagCode) in (' + @DiagnosisAll + '))     
             AND (ICDType = ''' + @ICDType + ''') AND MCCCode = ''MC14XM06PRL10'''    
             exec sp_executesql @sql, N'@count int output', @Count output    
             If isnull(@Count, 0) > 0    
                 Set @FinalCMG = @FinalCMG - 1    
         End    
     end    
     Else If @MCC = '24X'    
     Begin    
         If len(@DiagTyped1 + @DiagTyped2) > 0   
         Begin    
             set @FinalCMGTemp = @FinalCMG    
             Set @FinalCMG = Null    
             Set @SQL = 'SELECT Top 1 @FinalCMG = rtCMG, @FinalMCCCode = MCCCode, @DUsed = ProcDiagCode FROM CMG_Main    
             WHERE ProcDiagCode in (''' + @DiagnosisAll + ''') AND (ICDType = ''' + @ICDType + ''') AND (MCC = ''' + @MCC + ''')     
             AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SUBSTRING(MCCCode, 5, 2) = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'    
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output, @DUsed VarChar(10) output', @FinalCMG output, @FinalMCCCode Output, @DUsed Output    
             If isnull(@FinalCMG, '') = ''    
                 Set @FinalCMG = '868'    
         End    
         Else If isnull(@FinalCMG, '') = ''    
         Begin    
             Set @FinalCMG = '999'    
             Set @FinalMCCCode = 'MC99XM01MD'    
             Set @MCC = '99'    
         End    
     End    
     Else If @MCC = '25X' and SUBSTRING(@Branch, 6, 1) = 'S' and SUBSTRING(@Branch, 7, 2) = '04' and @FinalCMG in ('351', '350') --New 2002/09/26 Moved from above and this line  
     Begin    
         Declare @MC25Count as int    
         If @FinalCMG = 350    
             Set @MC25Count = charindex(@ProceduresAll, @CMGProc, charindex(@ProceduresAll, @CMGProc) + 1)    
         If isnull(@MC25Count, 0) = 0    
             Set @FinalCMG = 351    
     End    
     If @FinalCMG is null    
     Begin    
         If @BranchCMG is null    
             Set @FinalCMG = @MRDxCMG    
         Else    
             Set @FinalCMG = @BranchCMG    
     End    
     If isnull(@FinalCMG, '') = ''    
         Begin    
             Set @FinalCMG = '999'    
             Set @FinalMCCCode = 'MC99XM01MD'    
             Set @MCC = '99'    
         End    
  /* Calculate Complexity*/    
     if len(@FinalMCCCode) > 10    
         Set @Branch = left(isnull(@FinalMCCCode, ''), 10)    
 
     Declare @MedSurgInd as VarChar(1) 
     SELECT @MedSurg = cmgmcctype, @MedSurgInd = RIWInd FROM CMG_Etc_2001T WHERE (cmgcode = @FinalCMG) and (ciagegroup = @AgeGroup)    
     Set @PlexA = 0    
     Set @PlexB = 0    
     Set @PlexC = 0    
     Set @PlexD = 0    
     Set @PlexP = 0    
     Set @PlexCMCC = 0    
     If exists (SELECT * FROM CMG_Etc_2001T WHERE (cmgcode = @FinalCMG) AND (cicpxlvl = 9) and (ciagegroup = @AgeGroup)) or @MedSurg = '9'  
         set @Complexity = 9    
   
     If @ICDType = 'C' And patindex('%9672%', @ProceduresAll) > 0 
     Set  @Complexity = 4 
   
     if isnull(@DUsed, '0') = '0'  
          Set @DUsed = 'XXXX'  
  --   Set @DiagTypeAll = replace(@DiagTypeAll, left(@DUsed, 4), ' ')    
     Set @DiagTypeAll = replace(@DiagTypeAll, left(@DiagMostResposible, 4) + '|', 'XXXX|')   
     Set @DiagTypeAll = replace(@DiagTypeAll, @DiagMostResposible + '|', 'XXXXX|')   

     Set @SQL = 'SELECT HomeMCC, COUNT(GrLevel) AS CountLevel, GrLevel FROM dbo.CMG_Complexity    
     WHERE DiagTypeCombine in (' + @DiagTypeAll + ')    
     AND (MCC = Left(''' + @MCC + ''',2)) AND (ICDType = ''' + @ICDType + ''') AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''')    
     GROUP BY HomeMCC, GrLevel Order by GrLevel'    
     exec (@SQL)    
      
     if @Complexity is null and @@RowCount > 0    
     Begin    
         Set @SQL = 'Declare cur_Complexity cursor for     
         SELECT HomeMCC, COUNT(GrLevel) AS CountLevel, GrLevel, Diagnosis FROM dbo.CMG_Complexity    
         WHERE DiagTypeCombine in (' + @DiagTypeAll + ')    
         AND (MCC = Left(''' + @MCC + ''',2)) AND (ICDType = ''' + @ICDType + ''') AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''')    
         GROUP BY HomeMCC, GrLevel, diagnosis Order by GrLevel    
         Open cur_Complexity'    
         Exec (@SQL)    
         fetch next from cur_Complexity    
         into @PlexHomeMcc, @PlexCount, @PlexLevel, @PlexDiagnosis    
         while @@fetch_status = 0    
         begin    
             If not exists(SELECT * FROM dbo.CMG_PlxException WHERE (MCCEx = LEFT(@MCC,2)) AND (CMGEx = @FinalCMG) AND (DiagnosisEx = @PlexDiagnosis) AND ICDType = @ICDType)    
             Begin    
                If @PlexLevel = 'A'     
                    Set @PlexA = @PlexA + @PlexCount    
                Else If @PlexLevel = 'B'    
                    Set @PlexB = @PlexB + @PlexCount    
                Else If @PlexLevel = 'C'    
                Begin    
                    Set @PlexC = @PlexC + @PlexCount    
                    If @PlexHomeMcc <> Left(@MCC,2)    
                        Set @PlexCMCC = 1    
                End                     Else If @PlexLevel = 'D'    
                    Set @PlexD = @PlexD + @PlexCount    
                Else If @PlexLevel = 'P'    
                    Set @PlexP = @PlexP + @PlexCount    
       End                   
            fetch next from cur_Complexity    
            into @PlexHomeMcc, @PlexCount, @PlexLevel, @PlexDiagnosis    
         end    
         Close cur_Complexity    
         Deallocate cur_Complexity    
    
         If @PlexA > 0 or @PlexB > 1 or (@PlexB = 1 and @PlexC > 0 and @PlexCMCC = 1)    
             Set @Complexity = 4    
         Else If @PlexB > 0 or (@PlexC > 1 and @PlexCMCC = 1) or (@PlexC > 10 and @PlexCMCC = 0)    
             Set @Complexity = 3    
         Else If @PlexD > 0 or @PlexP > 0 or (@PlexC = 1 and @PlexCMCC = 1) or (@PlexC > 0 and @PlexC < 11 and @PlexCMCC = 0)  
             Set @Complexity = 2    
         Else    
             Set @Complexity = 1    
     End    
     If isnull(@Complexity, '') = ''    
         Set @Complexity = 1    
      
     Set @MCC = Replace(@MCC, 'X', '')    
     Set @ComplexityLevel = @Complexity    
  /*Get the rest of the stuff */    
     SELECT Top 1 @CmgDesc = cmgdesc, @CmgTrim = ciagtrim, @CmgELOS = ciagelos, @CmgPDRA = ciagpdra, @CmgPDWGT = ciagpdwgt, @CmgRIW = ciagriw    
     FROM dbo.CMG_Etc_2002T WHERE (cmgcode = @FinalCMG) AND (cicpxlvl = @ComplexityLevel) AND (ciagegroup = @AgeGroup)    
  --New 2002/09/30 
     If @MedSurg = 9 
     Set @MedSurg = 1 
  /* If @LOS < @CMGELOS    
         set @RIW = @LOS * */   /*Get RIW$ Value*/    
             If @FinalCMG in ('910', '912', '998', '999') and @LOS < cast(@CMGELOS as decimal(7,4))    
                     Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))    
             else if @DDisposition = ' ' and @LOS <= @CMGTrim and @LOS <= 10    
             Begin    
                 Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer     
                     WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr is null and dxyear = 2002)    
                 Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))    
             End    
             else if @DDisposition = ' ' and @LOS <= @CMGTrim and @LOS > 10    
             Begin    
                 Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer    
                     WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr is null and dxyear = 2002)    
                 Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))    
             End    
             Else If @DDisposition = 'S' and @LOS <= cast(@CMGELOS as decimal(7,4))    
                 Set @CMGRIW = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,4))) as decimal(7,4))    
             Else If @DDisposition = 'S' and @LOS > cast(@CMGELOS as decimal(7,4)) and @LOS < @CMGTrim    
                 Set @CMGRIW = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@CmgELOS as decimal(7,4))) as decimal(7,4))    
             Else If @IsAcuteTo = 1 and @LOS <= 10 and @LOS <= @CMGTrim    
             Begin    
                 Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer    
                     WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='O' and dxyear = 2002)    
                 Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))    
             End    
             Else If @IsAcuteTo = 1 and @LOS > 10 and @LOS <= @CMGTrim    
             Begin    
                 Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
                 WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='O' and dxyear = 2002)    
                 Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))    
             End    
             Else If @IsAcutefrom = 1 and @LOS <= 10 and @LOS <= @CMGTrim    
             Begin    
                 Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer    
                     WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='I' and dxyear = 2002)    
                 Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))    
             End    
             Else If @IsAcutefrom = 1 and @LOS > 10 and @LOS <= @CMGTrim  
             Begin    
                 Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer    
                     WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='I' and dxyear = 2002)    
                 Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))    
             End    
             Else If @LOS > @CMGTrim    
                 Set @CMGRIW = cast(cast(@CMGRIW as decimal(7,4)) + (cast(@CmgPDRA as decimal(7,4)) * cast((cast(@LOS as decimal(7,2)) - cast(@CmgELOS as decimal(7,4))) as decimal(7,4))) as decimal(7,4))    

     Declare @CMGNon as int
     Select @CMGNon = CMGNonValue from CMG_NonBool where CMGNonYear = 2002
     if @CmgRIW is not null and isnull(@CMGNon, 0) = 0
     Begin   
         Select @RIW$ = CostPerRiw from H_InstitutionProfile where code = @InstNumber   
         if isnull(@RIW$, '0') = '0' or @RIW$ = ''   
             set @RIW$ = '0'   
         Set @CMGRIW$ = cast(@CmgRIW as decimal(7,4)) * cast(@RIW$ as decimal(6,2))   
         if @LOS - @CMGTrim > 0   
         Begin   
             Set @CMGMOH = left(@CMGRIW + (((@LOS - @CMGTrim) * cast(@CmgPDWGT as Decimal(7,4))) + (((cast(@CMGTrim as int) - cast(@CMGELOS as decimal(4,2))) * cast(@CmgPDWGT as Decimal(7,4)))) * .2), 10)   
             Set @CMGMOH$ = cast(@CmgMOH as decimal(7,4)) * cast(@RIW$ as decimal(6,2))   
         end   
         Else   
         Begin   
             Set @CMGMOH = @CMGRIW   
             Set @CMGMOH$ = @CMGRIW$   
         end   
         Set @CMGMOH = cast(@CMGMOH as decimal(8,4))   
         Set @CMGRIW$ = cast(@CMGRIW$ as decimal(10,2))   
         Set @CMGMOH$ = cast(@CMGMOH$ as decimal(10,2))
     End
     else if @CmgRIW is not null and (@CMGNon + (select code from H_HospitalProfile)) = 33101
     Begin
        Declare @MedSurgIndHold as VarChar(1)
        If @Complexity = 9
        Begin
           Set @MedSurgIndHold = @MedSurgInd
           Set @MedSurgInd = 9
        End
        Declare @CmgNonELOS as VarChar(10)   
        Declare @CmgNonTrim as VarChar(10)

        SELECT Top 1 @CmgDesc = cmgdesc, @CmgNonTrim = ciagtrim, @CmgNonELOS = ciagelos, @CmgPDRA = ciagpdra, @CmgPDWGT = ciagpdwgt, @CMGMOH = ciagriw   
        FROM dbo.CMG_ETC_2002_Non WHERE (cmgcode = @FinalCMG) AND (ciagegroup = @AgeGroup) and (ICDType = '9') --AND (cmgmcctype = @MedSurg)   

        If @MedSurg = 9 
           Set @MedSurg = 1   
        If @FinalCMG in ('910', '912', '998', '999') and @LOS < cast(@CmgNonELOS as decimal(7,4))   
            Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
        else if @DDisposition = '07' and @LOS <= @CmgNonTrim and @LOS <= 10   
        Begin   
            Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non    
                WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (ICDType = 'T') and isnull(cmgxfr, '') = '' and dxyear = 2002)   
            Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
        End   
        else if @DDisposition = '07' and @LOS <= @CmgNonTrim and @LOS > 10   
        Begin 
            Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non  
                WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (ICDType = 'T') and isnull(cmgxfr, '') = '' and dxyear = 2002)   
            Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
        End   
        Else If @DDisposition = '06' and @LOS <= cast(@CmgNonELOS as decimal(7,4))   
            Set @CMGMOH = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,4))) as decimal(7,4))   
        Else If @DDisposition = '06' and @LOS > cast(@CmgNonELOS as decimal(7,4)) and @LOS < @CmgNonTrim   
            Set @CMGMOH = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@CmgNonELOS as decimal(7,4))) as decimal(7,4))   
        Else If @IsAcuteTo = 1 and @LOS <= 10 and @LOS <= @CmgNonTrim   
        Begin   
            Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
                WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (ICDType = 'T') and cmgxfr ='O' and dxyear = 2002)   
            Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
        End   
        Else If @IsAcuteTo = 1 and @LOS > 10 and @LOS <= @CmgNonTrim   
        Begin   
            Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
                WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (ICDType = 'T') and cmgxfr ='O' and dxyear = 2002)   
            Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
        End   
        Else If @IsAcuteFrom = 1 and @LOS <= 10 and @LOS <= @CmgNonTrim   
        Begin   
            Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
                WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (ICDType = 'T') and cmgxfr ='I' and dxyear = 2002)   
            Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
        End   
        Else If @IsAcuteFrom = 1 and @LOS > 10 and @LOS <= @CmgNonTrim   
        Begin   
            Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
                WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (ICDType = 'T') and cmgxfr ='I' and dxyear = 2002)   
            Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
        End   
        Else If @LOS > @CmgNonTrim 
            Set @CMGMOH = cast(cast(@CMGMOH as decimal(7,4)) + (cast(@CmgPDRA as decimal(7,4)) * cast((cast(@LOS as decimal(7,2)) - cast(@CmgNonELOS as decimal(7,4))) as decimal(7,4))) as decimal(7,4))   

        If @MedSurgInd = 9
           Set @MedSurgInd = @MedSurgIndHold
     End   
  
     If @FinalCMG = '997'    
         Set @AcuteQuartile = 'I'    
     Else If @DDisposition = ' '    
         Set @AcuteQuartile = 'D'    
     Else If @DDisposition = 'S'    
         Set @AcuteQuartile = 'S'    
     Else If @IsAcuteFrom = 1 or @IsAcuteTo = 1    
         Set @AcuteQuartile = 'T'    
     Else If @LOS > @CMGTrim    
         Set @AcuteQuartile = 'O'    
     Else If @LOS > cast(@CMGELOS as decimal(7,4))    
         Set @AcuteQuartile = 'B'    
     Else    
         Set @AcuteQuartile = 'I'    
      
     If @MedSurg = '3'
   Set @MedOrSurg = 'M'
     Else
   Set @MedOrSurg = 'S'
    
     If isnull(@AbstractID, 0) > 0    
     Begin    
         Delete ab_CMG where Abstractid = @Abstractid and CMG_Year = 2002 and OccurrenceNumber = 1    
         If IsNull(@FinalCMG, '') <> ''    
         Begin    
             If @ICDType = 'C'    
                 Set @DiagMostResposible = (select top 1 code from ICD_DiagFile9cm where cihivalue = @DiagMostResposible)    
             Else    
                 Set @DiagMostResposible = (select top 1 code from ICD_DiagFile9 where cihivalue = @DiagMostResposible)      
             INSERT INTO [dbo].[AB_CMG] ([AbstractID], [OccurrenceNumber], [CMG_Year], [ICD_Type], [Diagnosis_Code],                  [Diagnosis_Type], [CMG], [Complexity], [MCC], [AcuteQuartile], [CMG_RIW], [MOH_RIW],    
             [RIW_Dollar], [MOH_Dollar], [CMG_ELOS], [CMG_Trim], [CMG_Description], [MCC_Surg]) VALUES                   (@AbstractID, 1, 2002, @ICDType, @DiagMostResposible, 11, @FinalCMG, @ComplexityLevel, Left(@MCC, 2), @AcuteQuartile, @CmgRIW, @CmgMOH,     
             cast(@CmgRIW$ as money), cast(@CmgMOH$ as money), @CmgELOS, @CMGTrim, @CMGDesc, @MedOrSurg)    
         End    
     End    
      
     Return 0



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE      PROCEDURE [P_CMG2002_T]   
     @Age as Int,   
     @AgeCode as int, 
     @LOS as int,   
     @AcuteLOS as int,   
     @ICDType as VarChar(2),   
     @Gender as VarChar(1),   
     @Weight as int,   
     @DDisposition as VarChar(2),   
     @InstNumber as int,   
     @InstTo as int,   
     @InstFrom as int,   
     @DiagMostResposible as VarChar(10),   
     @DiagnosisAll as VarChar(500),   
     @DiagTypeAll as VarChar(500),   
     @DiagTyped1 as VarChar(500),   
     @DiagTyped2 as VarChar(500),   
     @DiagTyped0 as VarChar(500),   
     @DiagTyped3 as VarChar(500),   
     @ProceduresAll as VarChar(1000),   
     @Procedure1 as VarChar(10),   
     @FinalCMG as VarChar(3) output,   
     @ComplexityLevel as Int output,   
     @MCC as VarChar(3) output,   
     @AcuteQuartile as VarChar(10) output,   
     @CmgRIW as VarChar(10) output,   
     @CmgMOH as VarChar(10) output,   
     @CmgRIW$ as VarChar(20) output,   
     @CmgMOH$ as VarChar(20) output,   
     @CmgELOS as VarChar(10) output,   
     @CmgTrim as VarChar(10) output,   
     @CmgDesc as VarChar(60) output,   
     @MedOrSurg as VarChar(1) output,  
     @AbstractID as Int,
     @Occurance as int = 1,	--Ticket 9011 Placeholder for VB6 not used otherwise in this proc
     @ExpiryDate as varchar(10) = NULL, --Ticket 9011 Placeholder for VB6 not used otherwise in this proc
--Ticket 9373
      @AgeGroup as int,
      @Plx4 as VarChar(1),
	  @FlagRecord as VarChar(1) = 'N'
  AS    
     Declare @MRDxCMG VarChar(8)   
     Declare @Branch VarChar(10)   
     Declare @BranchTemp VarChar(10)   
     Declare @BranchCMG VarChar(3)   
     Declare @IBranchCMG VarChar(3)   
     Declare @Partition as VarChar(2)   
     Declare @FinalSubBranch as VarChar(1)   
     Declare @FinalMCCCode as VarChar(14)   
     Declare @CmgALOS as VarChar(10)   
     Declare @CmgPDRA as VarChar(10)   
     Declare @CmgPDWGT as VarChar(10)   
     Declare @Cat1 as int   
     Declare @Cat2 as int   
     Declare @PlexHomeMcc as VarChar(2)   
     Declare @PlexCount as int   
     Declare @PlexLevel as VarChar(1)   
     Declare @PlexDiagnosis as VarChar(6)   
     Declare @PlexA as int   
     Declare @PlexB as int   
     Declare @PlexC as int   
     Declare @PlexD as int   
     Declare @PlexP as int   
     Declare @Complexity as int   
     Declare @PlexCMCC as int   
     Declare @MedSurg as int     
     Declare @RIW$ as VarChar(10)   
     Declare @CMGProc as Varchar(12)   
     Declare @FinalMCCCodeTemp as VarChar(14)   
     Declare @FinalCMGTemp as VarChar(14)   
     Declare @RIWDeath as VarChar(10)   
     Declare @HospProv as VarChar(2)   
     Declare @IsAcuteTo as bit   
     Declare @IsAcuteFrom as bit   
     Declare @SQL as NVarChar(3000)   
     Declare @count as int   
     Declare @AgeNumber as int   
     Declare @SDate as datetime   
     Declare @NonAcuteQuartile as VarChar(1)
  set @SDate = getdate()   
     Set Nocount on
     Set @IsAcuteTo = 0   
     Set @IsAcuteFrom = 0   
     
    If @AgeCode = 1 and @Age > 28 
    Set @AgeCode = 3 
  
     If @Gender = 'M'   
         Set @Gender = '1'   
     Else If @Gender = 'F'   
         Set @Gender = '2'   
     If isnull(@DiagMostResposible, '0') = '0'   
         Set @DiagMostResposible = ''   
     
     if exists (SELECT * FROM LU_Institution_10 WHERE code = @InstTo and InstCareType = 'A')   
 	set @IsAcuteTo = 1  
     if exists (SELECT * FROM LU_Institution_10 WHERE code = @InstFrom and InstCareType = 'A')   
 	set @IsAcuteFrom = 1  
     
     If rtrim(@DiagTypeAll) = ''   
         Set @DiagTypeAll = '''XXX'''   
     If @ProceduresAll = ''   
         Set @ProceduresAll = '''XXX'''   
     
     Declare @DiagMProcAll as VarChar(2000)   
     Declare @DiagMProc as VarChar(2000)   
     Set @DiagMProcAll = ''   
     If @DiagMostResposible <> ''   
     Begin   
         set @DiagMProcAll = '''' + @DiagMostResposible + ''', '              set @DiagMProc = '''' + @DiagMostResposible + ''', '    
     End   
     Set @DiagMProcAll = replace(@DiagMProcAll, ', ,',  ', ')   
     Set @DiagTypeAll = replace(@DiagTypeAll, ', ,',  ', ')   
     
     If @DiagnosisAll <> ''   
         Set @DiagMProcAll = @DiagMProcAll + @DiagnosisAll + ', '   
 
     If @ProceduresAll <> ''   
     Begin   
         Set @DiagMProcAll = @DiagMProcAll + @ProceduresAll   
         Set @DiagMProc = @DiagMProc + @ProceduresAll   
     End   
     If right(@DiagMProcAll, 2) = ', '   
         Set @DiagMProcAll = Left(@DiagMProcAll, len(@DiagMProcAll) - 2)   
     If right(@DiagMProc, 2) = ', '   
         Set @DiagMProc = Left(@DiagMProc, len(@DiagMProc) - 2)   
     Set @DiagMProcAll = replace(@DiagMProcAll, ', ,',  '')   
   
     If right(@DiagMProcAll, 1) <> ''''   
         Set @DiagMProcAll = @DiagMProcAll + ''''   
     If isnull(@DiagnosisAll, '') = '' 
         Set @DiagnosisAll = '''XXX''' 
 
     If (@Weight = 0 and isnull(@AgeCode, 0) <> 1) or (@Weight <> 0 and isnull(@AgeCode, 0) > 1)   
         SELECT Top 1 @MCC = [MCC], @MRDxCMG = [CMG], @BranchTemp = [MCCCode]  FROM CMG_Main2002   
         WHERE ([DiagProcCode]= @DiagMostResposible) AND ([Priority] = 3) AND (Gender = @Gender Or Gender = 3)   
     Else if @DDisposition = '09'   
     Begin   
         set @MCC = '99'
         Set @FinalCMG = '997'
         Set @CmgDesc = 'Stillbirth'
     End   
     Else if @Weight < 200 
     Begin
	Set @MCC = '99'
	Set @FinalCMG = '999'
     End
     Else if @Weight < 750 AND @Weight >= 200
     Begin   
         set @MCC = '15X'   
         Set @FinalCMG = '625'   
     End   
     Else if @Weight < 1000   
     Begin   
         set @MCC = '15X'   
         Set @MRDxCMG = '626'   
     End   
     Else if @Weight < 1500   
     Begin   
         set @MCC = '15X'   
         Set @MRDxCMG = '628'   
         Set @BranchTemp = 'MC15XM03MD'   
     End   
     Else if @Weight < 2000   
     Begin   
         set @MCC = '15X'   
         Set @MRDxCMG = '632'   
         Set @BranchTemp = 'MC15XM04MD'   
     End   
     Else if @Weight < 2500   
     Begin   
         set @MCC = '15X'   
         Set @MRDxCMG = '640'   
         Set @BranchTemp = 'MC15XM05MD'   
     End   
     Else if @Weight > 2499 AND @Weight < 9000
     Begin   
         set @MCC = '15X'   
         Set @MRDxCMG = '648'   
         Set @BranchTemp = 'MC15XM06MD'   
     End   
     Else if @Weight > 8999 
     Begin
         Set @MCC = '99'
         Set @FinalCMG = '999'
     End
     If (@BranchTemp in ('MC19XM01MD', 'MC19XM02MD', 'MC19XM05MD') and @LOS < 6 and (@DDisposition = '05' or (@IsAcuteTo = 0 or @IsAcuteFrom = 0)) and @DDisposition not in ('06', '07')
     and (@IsAcuteTo = 0 and @IsAcuteFrom = 0)) 
     Begin   

          Set @FinalCMG = @MRDxCMG + 1   
          Set @Branch = @BranchTemp   
     End   
     If left(@DiagMostResposible, 3) = 'Z53' 
     Begin 
 	   Set @FinalCMG = @MRDxCMG  
 	   Set @FinalMCCCode = @BranchTemp         
     End 
 
     If @DDisposition = '08' 
     Begin 
 	   set @FinalCMG = 996 
     End 
  
     If @FinalCMG is NULL   
     Begin   
         Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2002    
         WHERE DiagProcCode in (' + @ProceduresAll + ') AND MCC = ''' + @MCC + ''' AND Priority < 3 ORDER BY SortOrder'   
         exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
 		@Branch output, @BranchCMG Output, @CMGProc Output
         Set @Partition = SUBSTRING(@Branch, 7, 2)   
         If isnull(@Branch, '0') = '0' and @MCC = '18X' and isnull(@Procedure1, '0') <> '0'   
         begin   
             Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2002    
             WHERE DiagProcCode in (' + @ProceduresAll + ')  and translatefrom like ''appdh%'' ORDER BY SortOrder'   
             exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
 		@Branch output, @BranchCMG Output, @CMGProc Output
             If isnull(@Branch, '0') <> '0'   
             begin   
                 Set @Branch = 'MC18XS02PR'   
                 Set @BranchCMG = '750'   
             end   
         end   
         Else If isnull(@Branch, '0') = '0' and @MCC = '17A' and isnull(@Procedure1, '0') <> '0'   
         begin   
             Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2002    
             WHERE DiagProcCode in (' + @ProceduresAll + ') and translatefrom like ''appdh%'' ORDER BY SortOrder'   
             exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output',
 		@Branch output, @BranchCMG Output, @CMGProc Output
  
             If isnull(@Branch, '0') <> '0'   
             begin   
 	           Set @Branch = Null 
 	           Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2002    
 	           WHERE DiagProcCode in (' + @DiagMProcAll + ') AND MCCCode = ''MC17AS03MDL01'' ORDER BY SortOrder'   
 	           exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
 			@Branch output, @BranchCMG Output, @CMGProc Output
 	 
 	           If isnull(@Branch, '0') = '0'   
 	           begin   
 	                   Set @FinalMCCCode = 'MC17AS03PR'   
 	                   Set @FinalCMG = '728'   
 	           End 
             end   
         end   
         Else If isnull(@Branch, '0') = '0' and @MCC = '17B' and isnull(@Procedure1, '0') <> '0'   
         begin   
             Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2002    
             WHERE DiagProcCode in (' + @ProceduresAll + ') and translatefrom like ''appdh%'' ORDER BY SortOrder'   
             exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
 		@Branch output, @BranchCMG Output, @CMGProc Output
             If isnull(@Branch, '0') <> '0'   
             begin   
                 Set @FinalCMG = '734'   
                 Set @BranchCMG = '734'   
             end   
         end   
         Else if @MCC = '05A' and (@Partition = '06' or @Partition = '07') and SUBSTRING(@Branch, 5, 2) = 'AS'   
         Begin   
             SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002    
             WHERE DiagProcCode = (@DiagMostResposible) AND MCC = @MCC AND (Partition = @Partition) AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= 'AS' ORDER BY SortOrder   
             If @FinalCMG is null   
             Begin   
                 If @BranchCMG is null   
                     Set @FinalCMG = @MRDxCMG   
                 Else   
                     Set @FinalCMG = @BranchCMG   
             End   
         End   
         else If isnull(@Branch, '0') = '0'   
             Set @Branch = @BranchTemp   
         Set @Partition = SUBSTRING(@Branch, 7, 2)   
 	if isnull(@FinalSubBranch, '') = ''
 	Begin
             Set @SQL = 'SELECT Top 1 @FinalSubBranch = MedicalSurgical FROM CMG_Main2002   WHERE MCCCode = ''' + @Branch + ''''   
             exec sp_executesql @sql, N'@FinalSubBranch VarChar(1) output', @FinalSubBranch output
 	    if isnull(@FinalSubBranch, '') = ''
 		Set @FinalSubBranch = '2'
 	end
     End   
 
     If @MCC = '15X'   
     Begin   
         Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
         WHERE DiagProcCode in (' + @DiagMProcAll + ') AND (MCC = ''' + @MCC + ''')    
         AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output         End   
     Else If @MCC = '13X'   
     Begin   
         Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
         WHERE DiagProcCode in (' + @DiagMProc + ') AND (MCC = ''' + @MCC + ''')    
         AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
     End   
      Else If @MCC = '24X'   
      Begin
         Declare @MCC24X as Varchar(10)
         If CHARINDEX(',', @DiagnosisAll) > 0
           set @MCC24X = left(@DiagnosisAll, CHARINDEX(',', @DiagnosisAll) - 1 )
	 Else if Len(@DiagnosisAll) > 0
           set @MCC24X = @DiagnosisAll

         Set @FinalCMG = Null
         If CHARINDEX(@MCC24X, @DiagTyped1 + ' ' + @DiagTyped2) > 0
         Begin
           Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002    
           WHERE DiagProcCode in (' + @MCC24X + ') AND MCC = ''' + @MCC + '''     
           AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
         End

         If @FinalCMG is Null and CHARINDEX(@MCC24X, @DiagTyped1 + ' ' + @DiagTyped2) > 0
		Set @FinalCMG = '868'
	 Else If CHARINDEX(@MCC24X, @DiagTyped1 + ' ' + @DiagTyped2) = 0
         Begin   
           Set @FinalCMG = '999'   
           Set @FinalMCCCode = 'MC99XM01MD'   
           Set @MCC = '99'   
         End   
      End
     Else If @FinalCMG is null and @BranchCMG is not null and @MCC not in ('05A', '08X', '10X') 
     Begin 
 	Declare @ProcTemp as VarChar(15) 
         set @FinalCMGTemp = @BranchCMG   
 	Set @ProcTemp = @CMGProc 
 	Set @BranchTemp = @BranchCMG 
         Set @BranchCMG = Null   
  
         Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2002    
         WHERE DiagProcCode in (' + @ProceduresAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
         AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
         exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', @Branch output, @BranchCMG Output, @CMGProc Output   
 	If @BranchCMG is null 
 
 		Begin 
 	           Set @FinalCMG = @FinalCMGTemp 
 	           Set @FinalMCCCode = @BranchTemp 
 	           Set @CMGProc = @ProcTemp 
 		End 
 	Else 
 		Begin 
 	           Set @FinalCMG = @BranchCMG 
 	           Set @FinalMCCCode = @Branch 
 		End 
     End 
     Else If @FinalCMG is null   
 	Begin   
		If  @mcc = '23X' and @ProceduresAll = '''XXX'''
	   		Set @SQL = ''
		Else
 	        Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002    
 	        WHERE DiagProcCode in (' + @DiagMProcAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
 	        AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
 	        exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
 	End   

    If @MCC = '05A' and (@Partition Between '03' and '15') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02'   
     Begin   
 	 declare @Diag05 as VarChar(1000) 
         set @FinalCMGTemp = @FinalCMG   
         Set @FinalCMG = Null   
    	 set @Diag05 = replace(@DiagMProcAll, replace(replace(Replace(substring(@DiagTypeAll, charindex('|3', @DiagTypeAll) -5, 6), '|', ''), ' ', ''), '''', ''), 'xxx') 

         Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
         WHERE (DiagProcCode) in (' + @Diag05 + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
         AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch +  ''' and SortOrder > 6 ORDER BY SortOrder'   
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
         If @FinalCMG is Null   
             Set @FinalCMG = @FinalCMGTemp  
     End   
     --New 2002/09/20  
     Else If (@MCC = '05A' and (@Partition Between '19' and '21')) or (@MCC = '04X' and (@Partition Between '09' and '11')) or (@MCC = '01X' and (@Partition Between '09' and '11'))  
      or (@MCC = '06X' and (@Partition Between '19' and '21')) or (@MCC = '08X' and (@Partition Between '27' and '29')) or (@MCC = '11X' and (@Partition Between '17' and '19'))  
      or (@MCC = '05B' and (@Partition Between '12' and '14')) 
     Begin    
         set @FinalCMGTemp = @FinalCMG    
         Set @FinalCMG = Null    
         Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
         WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
         AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 ORDER BY SortOrder'    
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
    
         If @FinalCMG is Null and isnull(@FinalCMGTemp, '0')  = '902' 
 	Begin 
            Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002     
            WHERE DiagProcCode in (' + @ProceduresAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
            AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
            exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
 	End 
 	Else If @FinalCMG is Null 
             Set @FinalCMG = @FinalCMGTemp    
     End    
     Else If @MCC = '05A' and (@Partition Between '03' and '15') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) <> 'L02'   
         Set @FinalCMG = Null   
     Else If (@MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02' AND (@LOS >= 4)) or    
         ((@MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02') and (@DDisposition in ('07', '06') or @IsAcuteTo = 1 or @IsAcutefrom = 1))   
     Begin   
         set @FinalCMGTemp = @FinalCMG   
         Set @FinalCMG = Null   
         Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002    
         WHERE (DiagProcCode) in (' + @DiagMProcAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
         AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' and SortOrder > 2 ORDER BY SortOrder'   
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
         If @FinalCMG is Null   
             Set @FinalCMG = @FinalCMGTemp   
         else if @Partition = '01'   
             Set @FinalCMG = @FinalCMG - 4   
         else   
             Set @FinalCMG = @FinalCMG - 2   
     end   
     Else If @MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02' And @LOS < 4   
         Set @FinalCMG = '218'   
     Else if @MCC = '05A' and (@Partition = '03' or @Partition = '04' or @Partition = '05')   
     Begin   
         set @FinalCMGTemp = @FinalCMG   
         Set @FinalCMG = Null   
         set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
         AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
            
         If @FinalCMG is Null   
             Set @FinalCMG = @FinalCMGTemp   
         If @FinalCMG in ('176', '178', '181')   
             Set @FinalCMG = '183'   
         Else If @FinalCMG in ('177', '179', '182')   
         Begin   
             set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
             AND MCCCode = ''MC05AS' + @Partition + 'NPL02'''   
             exec sp_executesql @sql, N'@count int output', @Count output   
             If isnull(@Count, 0) > 0   
                 Set @FinalCMG = @FinalCMG - 1   
         End   
     end   
     Else if @MCC = '05A' and @Partition = '10' and (@FinalCMG = '181' or @FinalCMG = '182')   
      Begin  
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   
	If @FinalCMGTemp = '182'
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND sortorder = 2 AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
	else
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND sortorder = 1 AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   

          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
             
          If @FinalCMG is Null and @FinalCMGTemp = '182'
              Set @FinalCMG = '182' 
          else If @FinalCMG is Null and @FinalCMGTemp = '181'
              Set @FinalCMG = '194'   
      End   
     --New 2002/09/19  
     Else If @MCC = '06X' and (@Partition = '12')  
     Begin    
         set @FinalCMGTemp = @FinalCMG    
         Set @FinalCMG = Null    
         Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
         WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
         If @FinalCMG is Null    
             Set @FinalCMG = @FinalCMGTemp    
     End    
     --New 2002/09/24  
     Else If @MCC = '08X' and (@Partition in ('04', '05', '07')) and @FinalCMG = '350'  
     Begin    
         set @FinalCMG = NULL  
         Declare @MC08Count as int    
         set @SQL = 'SELECT @MC08Count = count(*) FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @ProceduresAll + '))    
         AND MCCCode = ''MC08XS' + @Partition + 'PRL01''' 
         exec sp_executesql @sql, N'@MC08Count int output', @MC08Count output   
  
         If isnull(@MC08Count, 0) > 1 and len(@ProceduresAll) > 30 
            Set @FinalCMG = 350    
         Else  
         Begin  
            Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
            WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SortOrder > 1 ORDER BY SortOrder'    
            exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
         End  
  
         If @FinalCMG is Null    
             Set @FinalCMG = @BranchCMG   
     End    
     Else If @MCC = '08X' and (@Partition between '10' and '25') and SUBSTRING(@Branch, 6, 1) = 'S' 
     Begin    
         set @FinalCMGTemp = @FinalCMG    
         Set @FinalCMG = Null    
         Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
         WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
         If @FinalCMG is Null    
             Set @FinalCMG = @FinalCMGTemp    
     End    
     --New 2002/09/19  
     Else If @MCC = '09X'  
     Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = @FinalCMGTemp    

	  If @FinalCMG = '438'
	  Begin
	          set @FinalCMGTemp = @FinalCMG    
	          Set @FinalCMG = Null    
	
	          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
	          WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
	           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
	          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = '437'    
	  End
	  --Ticket 10302
	  If @FinalCMG = '427'
	  Begin
	          set @FinalCMGTemp = @FinalCMG    
	          Set @FinalCMG = Null    
	
	          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
	          WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
	           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
	          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = '425'    
	  End
     End    
     Else If @MCC = '10X' and @Partition = '01' and SUBSTRING(@FinalMCCCode, 5, 2) = 'XS' 
     Begin    
         set @FinalCMGTemp = @FinalCMG    
         Set @FinalCMG = Null    
         Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
         WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
         If @FinalCMG is Null    
             Set @FinalCMG = @FinalCMGTemp    
     End    
     --New 2002/09/25  
     Else If @MCC = '19X' and (@FinalCMG not in ('771', '778', '767')) and @FinalCMG is not null       Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Declare @LenDiag as int 
          Declare @Diag19X as NVarChar(200) 
          set @LenDiag = len(@DiagMProcAll) - len(@DiagMostResposible) - 4 
          If @LenDiag < 0 
          Begin 
             Set @LenDiag = 0 
             Set @Diag19X = '''''' 
          End 
          Else 
             Set @Diag19X = right(@DiagMProcAll, @LenDiag) 
          set @Diag19X = replace(@Diag19X, replace(replace(Replace(substring(@DiagTypeAll, charindex('|3', @DiagTypeAll) -5, 6), '|', ''), ' ', ''), '''', ''), 'xxx') 
     If right(@Diag19X, 1) = ',' 
           set @Diag19X = left(@Diag19X, len(@Diag19X)-1)
     If right(@Diag19X, 2) = ', ' 
           set @Diag19X = left(@Diag19X, len(@Diag19X)-2)

     If right(@Diag19X, 1) <> '''' 
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
             WHERE ((DiagProcCode) in (' + @Diag19X + '''))    
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
     Else
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
             WHERE ((DiagProcCode) in (' + @Diag19X + '))    
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    

          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
          Begin  
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002   
             WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
              AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 1 ORDER BY SortOrder'    
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          End  
     End         
  Else If @MCC = '11X' and (@Partition = '01') and right(@FinalMCCCode, 3) = 'L01' 
      Begin	
	If @LOS > 2 or @DDisposition in ('06','07') or @isAcuteTo = 1 or @isAcuteFrom = 1
		Set @FinalCMG = '520'	
	Else if @LOS < 3 AND @isAcuteTo = 0 and @isAcuteFrom = 0
		Set @FinalCMG = '999'	
      End 
     Else if @MCC = '13X' and @FinalMCCCode like 'MC13XS04%'   
     Begin   
         If @FinalMCCCode = 'MC13XS04PRL02'   
         Begin   
             set @FinalCMGTemp = @FinalCMG   
             Set @FinalCMG = Null   
             set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProc + '))    
             AND MCCCode in (''MC13XS04MDL03'', ''MC13XS04PRL04'') ORDER BY SortOrder'   
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
     
             If @FinalCMG is Null   
                 Set @FinalCMG = '579'   
         End   
         Else If @FinalMCCCode = 'MC13XS04MDL01'   
         Begin   
             set @FinalCMGTemp = @FinalCMG   
             Set @FinalCMG = Null   
             set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProc + '))    
             AND MCCCode = ''MC13XS04PRL02'''   
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
  
             If @FinalCMG is Null   
                 Set @FinalCMG = @FinalCMGTemp   
         End   
         If @FinalMCCCode = 'MC13XS04MDL03'   
         Begin   
             set @FinalCMGTemp = @FinalCMG   
             Set @FinalCMG = Null   
             set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProc + '))    
             AND MCCCode = ''MC13XS04PRL04'''   
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
                
             If @FinalCMG is Null   
                 Set @FinalCMG = @FinalCMGTemp   
         End   
         Else If @FinalMCCCode = 'MC13XS04PRL04'   
             Set @FinalCMG = '579'   
     end   
     Else If (@MCC = '14X' and (@Partition = '05')) And (@LOS >= 3 or @IsAcuteTo = 1 or @IsAcuteTo = 1) 
         Set @FinalCMG = '599'   
     Else If @MCC = '14X' and (@Partition = '01') and @FinalSubBranch = 1 and ((@FinalCMG = '612' or (@FinalCMG is null and @MRDxCMG = '612')))
     Begin   
         Set @FinalCMG = Null   
         set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002 WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
         AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
         SortOrder = 1 ORDER BY SortOrder' 
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
         If @FinalCMG is Null   
             Set @FinalCMG = 600        end   
     Else If @MCC = '15X' and (@Partition Between '03' and '06') and right(@FinalMCCCode, 3) = 'L01' And @LOS < 6   
         Set @FinalCMG = 998   
--Added on Ticket 9161
      Else If @MCC= '15X' and (@Partition Between '03' and '06') and right(@FinalMCCCode, 3) = 'L01' and (@DDisposition in ('07', '06') or @IsAcuteTo = 1 or @IsAcutefrom = 1 or @LOS > 6) 
      Begin

	  If @Partition = '03'
          	Set @FinalCMG = 627  
	  If @Partition = '04'
          	Set @FinalCMG = 630  
	  If @Partition = '05'
          	Set @FinalCMG = 636  
	  If @Partition = '06'
          	Set @FinalCMG = 643  
      End
     Else If @MCC = '15X' and (@Partition in ('06', '05')) and ((@FinalCMG = '646' or (@FinalCMG is null and @MRDxCMG = '646')) or 
      (@FinalCMG = '647' or (@FinalCMG is null and @MRDxCMG = '647')) or (@FinalCMG = '648' or (@FinalCMG is null and @MRDxCMG = '648'))
      or (@FinalCMG = '639' or (@FinalCMG is null and @MRDxCMG = '639'))or (@FinalCMG = '640' or (@FinalCMG is null and @MRDxCMG = '640')))
      Begin   
          Set @FinalCMG = Null   
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE (((DiagProcCode) in (' + @DiagMProcAll  + ')) or
	  ((DiagProcCode) in (''''' + @DiagTyped0 + @DiagTyped3 + ')) and isnull(translatefrom, '''') = '''')
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
          SortOrder = 4 ORDER BY SortOrder' 
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
          If @FinalCMG is Null   
          Begin
           set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
           SortOrder > 4 ORDER BY SortOrder' 
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
           If @FinalCMG is Null and @MRDxCMG in ('646', '647', '648')
               Set @FinalCMG = 648   
           Else If @FinalCMG is Null and @MRDxCMG in ('639', '640')
               Set @FinalCMG = 640   
      	  End
     end 
     Else If @MCC = '14X' and (@Partition = '02')-- and right(@FinalMCCCode, 3) = 'L01'   
     Begin   
         set @FinalCMGTemp = @FinalCMG   
         Set @FinalCMG = Null   
         set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002 WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
         AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
         SortOrder = 1 ORDER BY SortOrder'   
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
         
         If @FinalCMG is Null   
             Set @FinalCMG = @FinalCMGTemp   
         Else  
         Begin  
--2004/04/07 Delete Typed 3
            set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
            AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
            SortOrder > 1 ORDER BY SortOrder'   
            exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
        
            If @FinalCMG is Null   
                Set @FinalCMG = @FinalCMGTemp   
            If @FinalCMG = '601'   
                Set @FinalCMG = '603'   
            Else If @FinalCMG in ('602', '604')
            Begin   
                set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProcAll + @DiagTyped3 + '))    
                AND MCCCode = ''MC14XS02MOL03'''   
                exec sp_executesql @sql, N'@count int output', @Count output   
                If isnull(@Count, 0) > 0   
                    Set @FinalCMG = @FinalCMG - 1   
            End   
     End  
     end   
     Else If @MCC = '14X' and (@Partition = '02') and right(@FinalMCCCode, 3) <> 'L01' and SUBSTRING(@FinalMCCCode, 5, 2) <>  'XM'   
         Set @FinalCMG = 999   
     Else If @MCC = '14X' and (@FinalCMG Between '608' and '611' or (@FinalCMG is null and @MRDxCMG Between '608' and '611'))--(@FinalCMG = '608' or @FinalCMG = '609')   
     Begin   
         If @FinalCMG = '608'   
             Set @FinalCMG = '610'   
         Else 
         Begin   
             set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProcAll + @DiagTyped3 +  '))    
             AND MCCCode = ''MC14XM01MOL04'''  
             exec sp_executesql @sql, N'@count int output', @Count output  
             If isnull(@Count, 0) > 0 and @FinalCMG is not null
                 Set @FinalCMG = @FinalCMG - 1   
             Else If isnull(@Count, 0) > 0 and @FinalCMG is null
                 Set @FinalCMG = @MRDxCMG - 1   
         End   
     End   
     Else If @MCC = '14X' and (@FinalCMG in ('620', '621'))   
     Begin   
         If @FinalCMG = '621'   
         Begin   
             set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagnosisAll + '))    
             AND MCCCode = ''MC14XM06PRL10'''   
             exec sp_executesql @sql, N'@count int output', @Count output   
             If isnull(@Count, 0) > 0   
                 Set @FinalCMG = @FinalCMG - 1   
         End   
     end         Else if @MCC = '21X' and (@Partition in ('05', '06'))   
     Begin   
         set @FinalCMGTemp = @FinalCMG   
         Set @FinalCMG = Null   
         set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
         AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
         exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
         If @FinalCMG is Null   
             Set @FinalCMG = @FinalCMGTemp   
         If @FinalCMG in ('176', '178', '181')   
             Set @FinalCMG = '183'   
         Else If @FinalCMG in ('177', '179', '182')   
         Begin   
             set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
             AND MCCCode = ''MC21XS' + @Partition + 'NPL02'''   
             exec sp_executesql @sql, N'@count int output', @Count output   
             If isnull(@Count, 0) > 0   
                 Set @FinalCMG = @FinalCMG - 1   
         End   
     end   
      Else if @MCC = '22X' and (@Partition in ('01', '02')) --Ticket 9698
      Begin   
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   

          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   

          If @FinalCMG is Null 
              Set @FinalCMG = @FinalCMGTemp  
      end 
      Else If @MCC = '25X' and SUBSTRING(@Branch, 6, 1) = 'S' and SUBSTRING(@Branch, 7, 2) = '05' and @FinalCMG in ('351', '350') 
      Begin
      Declare @MC25Proc as VarChar(15) 
      Declare @MC25Count as int   
      If @FinalCMG = 350   
      Begin 
              set @SQL = 'SELECT @MC25Count = count(*) FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @ProceduresAll + '))    
              AND MCCCode = ''MC25XS05PRL03'''   
              exec sp_executesql @sql, N'@MC25Count int output', @MC25Count output   
           If @MC25Count = 1 
           Begin
                   set @SQL = 'SELECT  @MC25Proc = diagproccode FROM CMG_Main2002 WHERE ((DiagProcCode) in (' + @ProceduresAll + '))    
                   AND MCCCode = ''MC25XS05PRL03'''   
                   exec sp_executesql @sql, N'@MC25Proc varchar(15) output', @MC25Proc output                   
  
                  If len(replace(@ProceduresAll, '''' + @MC25Proc + '''', '')) < (len(@ProceduresAll) - len(@MC25Proc) - 3)
                           Set @MC25Count = 2 
      	   End
      End 
   
          If isnull(@MC25Count, 0) < 2   
              Set @FinalCMG = 351   
      End   
  
     if len(@FinalMCCCode) > 10   
         Set @Branch = left(isnull(@FinalMCCCode, ''), 10)   

     If @FinalCMG is null   
     Begin   
         If @BranchCMG is null   
             Set @FinalCMG = @MRDxCMG   
         Else   
             Set @FinalCMG = @BranchCMG   
         If @FinalCMG is null 
              Set @FinalCMG = '999'   
     End   

      --Ticket 9330
      If @MCC is null
	set @MCC = '99'
 
     if len(@FinalMCCCode) > 10   
         Set @Branch = left(isnull(@FinalMCCCode, ''), 10)  

      Declare @MedSurgInd as VarChar(1) 
      Declare @MedSurgNon as VarChar(1) 
     SELECT @MedSurgNon = cmgmcctype, @MedSurg = cmgmcctype, @MedSurgInd = RIWInd FROM CMG_Etc_2002T WHERE (cmgcode = @FinalCMG) and (ciagegroup = @AgeGroup)    
     Set @PlexA = 0   
     Set @PlexB = 0   
     Set @PlexC = 0   
     Set @PlexD = 0   
     Set @PlexP = 0   
     Set @PlexCMCC = 0   
      If exists (SELECT * FROM CMG_Etc_2002T WHERE ((cmgcode = @FinalCMG) AND (cicpxlvl = 9) and (ciagegroup = @AgeGroup)) or @MedSurg = '9') 
         set @Complexity = 9   
     Set @DiagTypeAll = replace(@DiagTypeAll, @DiagMostResposible + '|', 'XXXXX|')   

     --If there are duplicate diagnosis with the same type, take type 1
     Declare @DupDiagComplex as Varchar(20)
     set @SQL = 'SELECT top 1 @DupDiagComplex = diagnosis FROM CMG_Plx2002   
         WHERE DiagTypeCombine in (' + @DiagTypeAll + ')
 	AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''') 
 	And Diagnosis not in (SELECT DiagnosisEx FROM dbo.CMG_PlxException2001 WHERE (MCCEx = LEFT(''' + @MCC + ''',2)) AND (CMGEx = ''' + @FinalCMG + '''))
 	group by diagnosis having Count(diagnosis) > 1'   
     exec sp_executesql @sql, N'@DupDiagComplex VarChar(20) output', @DupDiagComplex output 

     If isnull(@DupDiagComplex, '') <> ''
    	Set @DiagTypeAll = replace(@DiagTypeAll, @DupDiagComplex + '|2', 'XXXXX|2')   

      if @Plx4 = 'Y' and isnull(@Complexity, '') <> '9'
	set @Complexity = 4  
     If isnull(@AbstractID, 0) > 0 and CHARINDEX ('1GZ31CAND',   @ProceduresAll ) > 0 and @Complexity is null
     Begin   
 	if exists (SELECT dbo.AB_Intervention.AbstractID FROM dbo.AB_Intervention LEFT OUTER JOIN
 		dbo.ICD_ProcFile10 ON dbo.AB_Intervention.IntervCode = dbo.ICD_ProcFile10.Code LEFT OUTER JOIN
 		dbo.LU_IntervAttExtent ON dbo.AB_Intervention.IntervAttribExtent = dbo.LU_IntervAttExtent.Code
 		WHERE (dbo.LU_IntervAttExtent.CIHIValue IN ('EX')) AND (dbo.ICD_ProcFile10.CIHIValue  in ('1GZ31CAND', '1GZ31CRND')) AND (dbo.AB_Intervention.AbstractID = @AbstractID))
 	set @Complexity = 4  
     End
 
    	Create TABLE #PlxTemp (PlCount int, Plex varchar(1))
 --Plex Levels
 	set @SQL = 'SELECT count(*) as PlCount, substring(Plexity, cast(LEFT(''' + @MCC + ''',2) as int), 1) as Plex FROM CMG_Plx2002   
         WHERE DiagTypeCombine in (' + @DiagTypeAll + ')
 	AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''') 
 	And Diagnosis not in (SELECT DiagnosisEx FROM dbo.CMG_PlxException2001 WHERE (MCCEx = LEFT(''' + @MCC + ''',2)) AND (CMGEx = ''' + @FinalCMG + '''))
 	group by substring(Plexity, cast(LEFT(''' + @MCC + ''',2) as int), 1)'   

 	Insert into #PlxTemp Exec (@SQL)
 
     if @Complexity is null and @@Rowcount > 0   
     Begin  
 --Level C Not Home Plex
 	set @SQL = 'SELECT @PlexCMCC = count(*) FROM CMG_Plx2002   
         WHERE DiagTypeCombine in (' + @DiagTypeAll + ') and substring(Plexity, cast(LEFT(''' + @MCC + ''',2) as int), 1) = ''C'' 
 	and HomeMCC <> LEFT(''' + @MCC + ''',2)
 	AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''') 
 	And Diagnosis not in (SELECT DiagnosisEx FROM dbo.CMG_PlxException2001 WHERE (MCCEx = LEFT(''' + @MCC + ''',2)) AND (CMGEx = ''' + @FinalCMG + '''))'   
 	exec sp_executesql @sql, N'@PlexCMCC VarChar(1) output', @PlexCMCC output   
 	Set @PlexA = isnull((select PlCount from #PlxTemp where Plex = 'A'), 0)
 	Set @PlexB = isnull((select PlCount from #PlxTemp where Plex = 'B'), 0)
 	Set @PlexC = isnull((select PlCount from #PlxTemp where Plex = 'C'), 0)
 	Set @PlexD = isnull((select PlCount from #PlxTemp where Plex = 'D'), 0)
 	Set @PlexP = isnull((select PlCount from #PlxTemp where Plex = 'P'), 0)
 	If @PlexCMCC > 1
 		Set @PlexCMCC = 1
 
         If @PlexA > 0 or @PlexB > 1 or (@PlexB = 1 and @PlexC > 0 and @PlexCMCC = 1)   
             Set @Complexity = 4   
         Else If @PlexB > 0 or (@PlexC > 1 and @PlexCMCC = 1) or (@PlexC > 10 and @PlexCMCC = 0)   
             Set @Complexity = 3   
         Else If @PlexD > 0 or @PlexP > 0 or (@PlexC = 1 and @PlexCMCC = 1)    
             or (@PlexC > 0 and @PlexC < 11 and @PlexCMCC = 0)   
             Set @Complexity = 2   
         Else   
             Set @Complexity = 1   
     End   
 
     If isnull(@Complexity, '') = ''
            Set @Complexity = 1   
     
     Set @MCC = Replace(@MCC, 'X', '')   
     Set @ComplexityLevel = @Complexity   

     SELECT Top 1 @CmgDesc = cmgdesc, @CmgTrim = ciagtrim, @CmgELOS = ciagelos, @CmgPDRA = ciagpdra, @CmgPDWGT = ciagpdwgt, @CmgRIW = ciagriw   
     FROM dbo.CMG_Etc_2002T WHERE (cmgcode = @FinalCMG) AND (cicpxlvl = @ComplexityLevel) AND (ciagegroup = @AgeGroup) --AND (cmgmcctype = @MedSurg)   
 --print @CmgDesc 
 --print @CmgTrim 
 --print @CmgELOS 
 --print @CmgPDRA 
 
  --New 2002/09/30 
     If @MedSurg = 9 
 	Set @MedSurg = 1   
     If @FinalCMG in ('910', '912', '998', '999') and @LOS < cast(@CMGELOS as decimal(7,4))   
         Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
     Else If @FinalCMG in ('910', '912', '998', '999') and @LOS >= cast(@CMGELOS as decimal(7,4))   
         Set @CMGRIW = @CmgRIW
     else if @DDisposition = '07' and @LOS <= @CMGTrim and @LOS <= 10   
     Begin   
         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer    
              WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr is null and dxyear = 2002)   
         Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
     End   
     else if @DDisposition = '07' and @LOS <= @CMGTrim and @LOS > 10   
     Begin 
         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
             WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr is null and dxyear = 2002)   
         Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))         End   
     Else If @DDisposition = '06' and @LOS <= cast(@CMGELOS as decimal(7,4))   
         Set @CMGRIW = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,4))) as decimal(7,4))   
     Else If @DDisposition = '06' and @LOS > cast(@CMGELOS as decimal(7,4)) and @LOS <= @CMGTrim   
         Set @CMGRIW = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@CmgELOS as decimal(7,4))) as decimal(7,4))   
     Else If @IsAcuteTo = 1 and @LOS <= 10 and @LOS <= @CMGTrim   
     Begin   
         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
             WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='O' and dxyear = 2002)   
         Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
     End   
     Else If @IsAcuteTo = 1 and @LOS > 10 and @LOS <= @CMGTrim   
     Begin   
         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
             WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='O' and dxyear = 2002)   
         Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
     End   
     Else If @IsAcuteFrom = 1 and @LOS <= 10 and @LOS <= @CMGTrim   
     Begin   
         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
             WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='I' and dxyear = 2002)   
         Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
     End   
     Else If @IsAcuteFrom = 1 and @LOS > 10 and @LOS <= @CMGTrim   
     Begin   
         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
             WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='I' and dxyear = 2002)   
         Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
     End   
     Else If @LOS > @CMGTrim   
         Set @CMGRIW = cast(cast(@CMGRIW as decimal(7,4)) + (cast(@CmgPDRA as decimal(7,4)) * cast((cast(@LOS as decimal(7,2)) - cast(@CmgELOS as decimal(7,4))) as decimal(9,4))) as decimal(9,4))   
     Declare @CMGNon as int
     Select @CMGNon = CMGNonValue from CMG_NonBool where CMGNonYear = 2002
     if @CmgRIW is not null and isnull(@CMGNon, 0) = 0
     Begin
         Select @RIW$ = CostPerRiw from H_InstitutionProfile where code = @InstNumber   
         if isnull(@RIW$, '0') = '0' or @RIW$ = ''   
             set @RIW$ = '0'   
         Set @CMGRIW$ = cast(@CmgRIW as decimal(7,4)) * cast(@RIW$ as decimal(6,2))   
         if @LOS - @CMGTrim > 0   
         Begin   
             Set @CMGMOH = left(@CMGRIW + (((@LOS - @CMGTrim) * cast(@CmgPDWGT as Decimal(7,4))) + (((cast(@CMGTrim as int) - cast(@CMGELOS as decimal(4,2))) * cast(@CmgPDWGT as Decimal(7,4)))) * .2), 10)   
             Set @CMGMOH$ = cast(@CmgMOH as decimal(9,4)) * cast(@RIW$ as decimal(6,2))   
         end   
         Else   
         Begin   
             Set @CMGMOH = @CMGRIW   
             Set @CMGMOH$ = @CMGRIW$   
         end   
         Set @CMGMOH = cast(@CMGMOH as decimal(8,4))   
         Set @CMGRIW$ = cast(@CMGRIW$ as decimal(10,2))   
         Set @CMGMOH$ = cast(@CMGMOH$ as decimal(10,2)) 
     End 
--If they have rights to non complex grouper do this
     else if @CmgRIW is not null and exists(select code from H_HospitalProfile where code + @CMGNon = 33101) --PR - 00945
     Begin
          Select @RIW$ = CostPerRiw from H_InstitutionProfile where code = @InstNumber   
          if isnull(@RIW$, '0') = '0' or @RIW$ = ''   
              set @RIW$ = '0'   
          Set @CMGRIW$ = cast(@CmgRIW as decimal(7,4)) * cast(@RIW$ as decimal(6,2))   
	     Declare @MedSurgIndHold as VarChar(1)
	     If @Complexity = 9
	     Begin
		Set @MedSurgIndHold = @MedSurgInd
		Set @MedSurgInd = 9
	     End
	     Declare @CmgNonELOS as VarChar(10)   
	     Declare @CmgNonTrim as VarChar(10)

	     SELECT Top 1 @CmgDesc = cmgdesc, @CmgNonTrim = ciagtrim, @CmgNonELOS = ciagelos, @CmgPDRA = ciagpdra, @CmgPDWGT = ciagpdwgt, @CMGMOH = ciagriw   
	     FROM dbo.CMG_ETC_2002_Non WHERE (cmgcode = @FinalCMG) AND (ciagegroup = @AgeGroup) and (ICDType = 'T') --AND (cmgmcctype = @MedSurg)   

	     If @MedSurg = 9 
	 	Set @MedSurg = 1   
	     If @FinalCMG in ('910', '912', '998', '999') and @LOS < cast(@CmgNonELOS as decimal(7,4))   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     else if @DDisposition = '07' and @LOS <= @CmgNonTrim and @LOS <= 10   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non    
	             WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and isnull(cmgxfr, '') = '' and dxyear = 2002)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     else if @DDisposition = '07' and @LOS <= @CmgNonTrim and @LOS > 10   
	     Begin 
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non  
	             WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and isnull(cmgxfr, '') = '' and dxyear = 2002)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @DDisposition = '06' and @LOS <= cast(@CmgNonELOS as decimal(7,4))   
	         Set @CMGMOH = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,4))) as decimal(7,4))   
	     Else If @DDisposition = '06' and @LOS > cast(@CmgNonELOS as decimal(7,4)) and @LOS < @CmgNonTrim   
	         Set @CMGMOH = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@CmgNonELOS as decimal(7,4))) as decimal(7,4))   
	     Else If @IsAcuteFrom = 1 and @LOS <= 10 and @LOS <= @CmgNonTrim   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
	             WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and cmgxfr ='I' and dxyear = 2002)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @IsAcuteFrom = 1 and @LOS > 10 and @LOS <= @CmgNonTrim   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
	             WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and cmgxfr ='I' and dxyear = 2002)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @IsAcuteTo = 1 and @LOS <= 10 and @LOS <= @CmgNonTrim   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
	             WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and cmgxfr ='O' and dxyear = 2002)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @IsAcuteTo = 1 and @LOS > 10 and @LOS <= @CmgNonTrim   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
	             WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and cmgxfr ='O' and dxyear = 2002)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @LOS > @CmgNonTrim 
	         Set @CMGMOH = cast(cast(@CMGMOH as decimal(7,4)) + (cast(@CmgPDRA as decimal(7,4)) * cast((cast(@LOS as decimal(7,2)) - cast(@CmgNonELOS as decimal(7,4))) as decimal(9,4))) as decimal(9,4))   

	     If @MedSurgInd = 9
		Set @MedSurgInd = @MedSurgIndHold
	      If @DDisposition = '07'   
	          Set @NonAcuteQuartile = 'D'   
	      Else If @DDisposition = '06'   
	          Set @NonAcuteQuartile = 'S'   
	      Else If @IsAcuteFrom = 1 or @IsAcuteTo = 1 --or @DDisposition = '01' ticket 5711  
	          Set @NonAcuteQuartile = 'T'   
	      Else If @LOS > @CmgNonTrim   
	          Set @NonAcuteQuartile = 'O'   
	      Else If @LOS > cast(@CmgNonELOS as decimal(7,4))   
	          Set @NonAcuteQuartile = 'B'   
	      Else   
	          Set @NonAcuteQuartile = 'I'  
          Set @CMGMOH$ = cast(@CmgMOH as decimal(9,4)) * cast(@RIW$ as decimal(6,2))   
          Set @CMGMOH = cast(@CMGMOH as decimal(8,4))   
          Set @CMGRIW$ = cast(@CMGRIW$ as decimal(10,2))   
          Set @CMGMOH$ = cast(@CMGMOH$ as decimal(10,2))   
     End   
    
     If @DDisposition = '07'   
         Set @AcuteQuartile = 'D'   
     Else If @DDisposition = '06'   
         Set @AcuteQuartile = 'S'   
     Else If @IsAcuteFrom = 1 or @IsAcuteTo = 1 --or @DDisposition = '01' ticket 5711  
         Set @AcuteQuartile = 'T'   
     Else If @LOS > @CMGTrim   
         Set @AcuteQuartile = 'O'   
     Else If @LOS > cast(@CMGELOS as decimal(7,4))   
         Set @AcuteQuartile = 'B'   
     Else   
         Set @AcuteQuartile = 'I'   
   
     If @MedSurgInd = '2' 
 	Set @MedOrSurg = 'M' 
     Else 
 	Set @MedOrSurg = 'S' 
     
     If isnull(@AbstractID, 0) > 0   
     Begin   
         Delete ab_CMG where Abstractid = @Abstractid and CMG_Year = 2002 and OccurrenceNumber = 1   
         If IsNull(@FinalCMG, '') <> '' and isnull(@DiagMostResposible, '') <> '' 
         Begin   
             Set @DiagMostResposible = (select top 1 code from ICD_DiagFile10 where cihivalue = @DiagMostResposible)   
             INSERT INTO [dbo].[AB_CMG] ([AbstractID], [OccurrenceNumber], [CMG_Year], [ICD_Type], [Diagnosis_Code],   
             [Diagnosis_Type], [CMG], [Complexity], [MCC], [AcuteQuartile], [CMG_RIW], [MOH_RIW],   
             [RIW_Dollar], [MOH_Dollar], [CMG_ELOS], [CMG_Trim], [CMG_Description], [MCC_Surg], MOHQuartile) VALUES    
             (@AbstractID, 1, 2002, 'T', @DiagMostResposible, 11, @FinalCMG, @ComplexityLevel, rtrim(Left(@MCC, 3)), @AcuteQuartile, @CmgRIW, @CmgMOH,    
             cast(@CmgRIW$ as money), cast(@CmgMOH$ as money), @CmgELOS, @CMGTrim, @CMGDesc, @MedOrSurg,@NonAcuteQuartile)   
              Update ab_CMG set CMGModelType = ModelType, CMGTenthPercent = TenthPercent, CMGTwentyFifthPercent = TwentyFifthPercent, CMGFiftiethPercent = FiftiethPercent
              FROM dbo.AB_CMG LEFT OUTER JOIN
              dbo.CMG_Etc_2002T ON dbo.AB_CMG.Complexity = dbo.CMG_Etc_2002T.cicpxlvl AND dbo.AB_CMG.CMG = dbo.CMG_Etc_2002T.cmgcode
              WHERE abstractid = @AbstractID and CMG_Year = 2002 and ciagegroup = @AgeGroup
         End   
     
     End   
     set nocount off    
 --    print datediff(ms, @SDate, getdate())   
     Return 0


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE      PROCEDURE [P_CMG2003_T]   
      @Age as Int,   
      @AgeCode as int, 
      @LOS as int,   
      @AcuteLOS as int,   
      @ICDType as VarChar(2),   
      @Gender as VarChar(1),   
      @Weight as int,   
      @DDisposition as VarChar(2),   
      @InstNumber as int,   
      @InstTo as int,   
      @InstFrom as int,   
      @DiagMostResposible as VarChar(10),   
      @DiagnosisAll as VarChar(500),   
      @DiagTypeAll as VarChar(500),   
      @DiagTyped1 as VarChar(500),   
      @DiagTyped2 as VarChar(500),   
      @DiagTyped0 as VarChar(500),   
      @DiagTyped3 as VarChar(500),   
      @ProceduresAll as VarChar(1000),   
      @Procedure1 as VarChar(10),   
      @FinalCMG as VarChar(3) output,   
      @ComplexityLevel as Int output,   
      @MCC as VarChar(3) output,   
      @AcuteQuartile as VarChar(10) output,   
      @CmgRIW as VarChar(10) output,   
      @CmgMOH as VarChar(10) output,   
      @CmgRIW$ as VarChar(20) output,   
      @CmgMOH$ as VarChar(20) output,   
      @CmgELOS as VarChar(10) output,   
      @CmgTrim as VarChar(10) output,   
      @CmgDesc as VarChar(60) output,   
      @MedOrSurg as VarChar(1) output,  
      @AbstractID as Int,

 --Ticket 9011
      @Occurance as int = 1,
      @ExpiryDate as varchar(10) = NULL,
--Ticket 9373
      @AgeGroup as int,
      @Plx4 as VarChar(1),
	  @FlagRecord as VarChar(1) = 'N'
   AS    
      Declare @MRDxCMG VarChar(8)   
      Declare @Branch VarChar(10)   
      Declare @BranchTemp VarChar(10)   
      Declare @BranchCMG VarChar(3)   
      Declare @IBranchCMG VarChar(3)   
      Declare @Partition as VarChar(2)   
      Declare @FinalSubBranch as VarChar(1)   
      Declare @FinalMCCCode as VarChar(14)   
      Declare @CmgALOS as VarChar(10)   
      Declare @CmgPDRA as VarChar(10)   
      Declare @CmgPDWGT as VarChar(10)   
      Declare @Cat1 as int   
      Declare @Cat2 as int   
      Declare @PlexHomeMcc as VarChar(2)   
      Declare @PlexCount as int   
      Declare @PlexLevel as VarChar(1)   
      Declare @PlexDiagnosis as VarChar(6)   
      Declare @PlexA as int   
      Declare @PlexB as int   
      Declare @PlexC as int   
      Declare @PlexD as int   
      Declare @PlexP as int   
      Declare @Complexity as int   
      Declare @PlexCMCC as int   
      Declare @MedSurg as int   
      Declare @RIW$ as VarChar(10)   
      Declare @CMGProc as Varchar(12)   
      Declare @FinalMCCCodeTemp as VarChar(14)   
      Declare @FinalCMGTemp as VarChar(14)   
      Declare @RIWDeath as VarChar(10)   
      Declare @HospProv as VarChar(2)   
      Declare @IsAcuteTo as bit   
      Declare @IsAcuteFrom as bit   
      Declare @SQL as NVarChar(3000)   
      Declare @count as int   
      Declare @AgeNumber as int   
      Declare @SDate as datetime   
      Declare @NonAcuteQuartile as VarChar(1)
   set @SDate = getdate()   
      Set Nocount on
      Set @IsAcuteTo = 0   
      Set @IsAcuteFrom = 0   
   
     If @AgeCode = 1 and @Age > 28 
     Set @AgeCode = 3 
    
      If @Gender = 'M'   
          Set @Gender = '1'   
      Else If @Gender = 'F'   
          Set @Gender = '2'   
      If isnull(@DiagMostResposible, '0') = '0'   
          Set @DiagMostResposible = ''   
      
      if exists (SELECT * FROM LU_Institution_10 WHERE code = @InstTo and InstCareType = 'A')   
   set @IsAcuteTo = 1  
      if exists (SELECT * FROM LU_Institution_10 WHERE code = @InstFrom and InstCareType = 'A')   
   set @IsAcuteFrom = 1  
      
      If rtrim(@DiagTypeAll) = ''   
          Set @DiagTypeAll = '''XXX'''   
      If @ProceduresAll = ''   
          Set @ProceduresAll = '''XXX'''   
      
      Declare @DiagMProcAll as VarChar(2000)   
      Declare @DiagMProc as VarChar(2000)   
      Set @DiagMProcAll = ''   
      If @DiagMostResposible <> ''   
      Begin   
          set @DiagMProcAll = '''' + @DiagMostResposible + ''', '    
          set @DiagMProc = '''' + @DiagMostResposible + ''', '    
      End   
      Set @DiagMProcAll = replace(@DiagMProcAll, ', ,',  ', ')   
      Set @DiagTypeAll = replace(@DiagTypeAll, ', ,',  ', ')   
      
      If @DiagnosisAll <> ''   
          Set @DiagMProcAll = @DiagMProcAll + @DiagnosisAll + ', '   
  
      If @ProceduresAll <> ''   
      Begin   
          Set @DiagMProcAll = @DiagMProcAll + @ProceduresAll   
          Set @DiagMProc = @DiagMProc + @ProceduresAll   
      End   
      If right(@DiagMProcAll, 2) = ', '   
          Set @DiagMProcAll = Left(@DiagMProcAll, len(@DiagMProcAll) - 2)   
      If right(@DiagMProc, 2) = ', '   
          Set @DiagMProc = Left(@DiagMProc, len(@DiagMProc) - 2)   
      Set @DiagMProcAll = replace(@DiagMProcAll, ', ,',  '')   
    
      If right(@DiagMProcAll, 1) <> ''''   
          Set @DiagMProcAll = @DiagMProcAll + ''''   
      If isnull(@DiagnosisAll, '') = '' 
          Set @DiagnosisAll = '''XXX''' 
  
   --TICKET 8965
	If @DDisposition = '08'  
	  set @MCC = '99X'         
	Else if @DDisposition = '09'   
	Begin   
	  set @MCC = '99'
	  Set @FinalCMG = '997'
	  Set @CmgDesc = 'Stillbirth'
	End 
	Else If (@Weight = 0 and isnull(@AgeCode, 0) <> 1) or (@Weight <> 0 and isnull(@AgeCode, 0) > 1) 	
          SELECT Top 1 @MCC = [MCC], @MRDxCMG = [CMG], @BranchTemp = [MCCCode]  FROM CMG_Main2003   
          WHERE ([DiagProcCode]= @DiagMostResposible) AND ([Priority] = 3) AND (Gender = @Gender Or Gender = 3)   
  
	Else if @Weight < 200 
	Begin
	Set @MCC = '99'
	Set @FinalCMG = '999'
	End
             Else if @Weight < 750 AND @Weight >= 200
	Begin   
	  set @MCC = '15X'   
	  Set @FinalCMG = '625'   
	End   
	Else if @Weight < 1000   
	Begin   
	  set @MCC = '15X'   
	  Set @MRDxCMG = '626'   
	End   
	Else if @Weight < 1500   
	Begin   
	  set @MCC = '15X'   
	  Set @MRDxCMG = '628'   
	  Set @BranchTemp = 'MC15XM03MD'   
	End   
	Else if @Weight < 2000   
	Begin   
	  set @MCC = '15X'   
	  Set @MRDxCMG = '632'   
	  Set @BranchTemp = 'MC15XM04MD'   
	End   
	Else if @Weight < 2500   
	Begin   
	  set @MCC = '15X'   
	  Set @MRDxCMG = '640'   
	  Set @BranchTemp = 'MC15XM05MD'   
	End   
	Else if @Weight > 2499 AND @Weight < 9000
	Begin   
	  set @MCC = '15X'   
	  Set @MRDxCMG = '648'   
	  Set @BranchTemp = 'MC15XM06MD'   
	End
	Else if @Weight > 8999
	Begin
	Set @MCC = '99'
	Set @FinalCMG = '999'
	End
      If (@BranchTemp in ('MC19XM01MD', 'MC19XM02MD', 'MC19XM05MD') and @LOS < 6 and (@DDisposition = '05' or (@IsAcuteTo = 0 or @IsAcuteFrom = 0)) and @DDisposition not in ('06', '07')
   and (@IsAcuteTo = 0 and @IsAcuteFrom = 0)) 
      Begin   

          Set @FinalCMG = @MRDxCMG + 1   
          Set @Branch = @BranchTemp   
      End   
      If left(@DiagMostResposible, 3) = 'Z53' and (@MCC <> '23' and len(@ProceduresAll) = 0)--modified 2006/02/27
      Begin 
      Set @FinalCMG = @MRDxCMG  
      Set @FinalMCCCode = @BranchTemp         
      End 
  
      If @DDisposition = '08' 
      Begin 
      set @FinalCMG = 996 
      End 
   
      If @FinalCMG is NULL   
      Begin   
          Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
          WHERE DiagProcCode in (' + @ProceduresAll + ') AND MCC = ''' + @MCC + ''' AND Priority < 3 ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
           @Branch output, @BranchCMG Output, @CMGProc Output
          Set @Partition = SUBSTRING(@Branch, 7, 2)   
          If isnull(@Branch, '0') = '0' and @MCC = '18X' and isnull(@Procedure1, '0') <> '0'   
          begin   
              Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
              WHERE DiagProcCode in (' + @ProceduresAll + ')  and translatefrom like ''appdh%'' ORDER BY SortOrder'   
              exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
           @Branch output, @BranchCMG Output, @CMGProc Output
              If isnull(@Branch, '0') <> '0'   
              begin   
                  Set @Branch = 'MC18XS02PR'   
                  Set @BranchCMG = '750'   
              end   
          end   
          Else If isnull(@Branch, '0') = '0' and @MCC = '17A' and isnull(@Procedure1, '0') <> '0'   
          begin   
              Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
              WHERE DiagProcCode in (' + @ProceduresAll + ') and translatefrom like ''appdh%'' ORDER BY SortOrder'   
              exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output',
           @Branch output, @BranchCMG Output, @CMGProc Output
   
              If isnull(@Branch, '0') <> '0'   
              begin   
              Set @Branch = Null 
              Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
              WHERE DiagProcCode in (' + @DiagMProcAll + ') AND MCCCode = ''MC17AS03MDL01'' ORDER BY SortOrder'   
              exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
                   @Branch output, @BranchCMG Output, @CMGProc Output
    
              If isnull(@Branch, '0') = '0'   
              begin   
                      Set @FinalMCCCode = 'MC17AS03PR'   
                      Set @FinalCMG = '728'   
              End 
              end   
          end   
          Else If isnull(@Branch, '0') = '0' and @MCC = '17B' and isnull(@Procedure1, '0') <> '0'   
          begin   
              Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
              WHERE DiagProcCode in (' + @ProceduresAll + ') and translatefrom like ''appdh%'' ORDER BY SortOrder'   
              exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
           @Branch output, @BranchCMG Output, @CMGProc Output
              If isnull(@Branch, '0') <> '0'   
              begin   
                  Set @FinalCMG = '734'   
                  Set @BranchCMG = '734'   
              end   
          end   
          Else if @MCC = '05A' and (@Partition = '06' or @Partition = '07') and SUBSTRING(@Branch, 5, 2) = 'AS'   
          Begin   
              SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003    
              WHERE DiagProcCode = (@DiagMostResposible) AND MCC = @MCC AND (Partition = @Partition) AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= 'AS' ORDER BY SortOrder   
              If @FinalCMG is null   
              Begin   
                  If @BranchCMG is null   
                      Set @FinalCMG = @MRDxCMG   
                  Else   
                      Set @FinalCMG = @BranchCMG   
              End   
          End   
          else If isnull(@Branch, '0') = '0'   
              Set @Branch = @BranchTemp   
          Set @Partition = SUBSTRING(@Branch, 7, 2)   
   if isnull(@FinalSubBranch, '') = ''
   Begin
              Set @SQL = 'SELECT Top 1 @FinalSubBranch = MedicalSurgical FROM CMG_Main2003   WHERE MCCCode = ''' + @Branch + ''''   
              exec sp_executesql @sql, N'@FinalSubBranch VarChar(1) output', @FinalSubBranch output
       if isnull(@FinalSubBranch, '') = ''
           Set @FinalSubBranch = '2'
   end
      End   

      If @MCC = '15X'   
      Begin   
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE DiagProcCode in (' + @DiagMProcAll + ') AND (MCC = ''' + @MCC + ''')    
          AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
      End   
      Else If @MCC = '13X'   
      Begin   
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE DiagProcCode in (' + @DiagMProc + ') AND (MCC = ''' + @MCC + ''')    
          AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
      End   
      Else If @MCC = '24X'   
      Begin
         Declare @MCC24X as Varchar(10)
         If CHARINDEX(',', @DiagnosisAll) > 0
           set @MCC24X = left(@DiagnosisAll, CHARINDEX(',', @DiagnosisAll) - 1 )
	 Else if Len(@DiagnosisAll) > 0
           set @MCC24X = @DiagnosisAll

         Set @FinalCMG = Null
         If CHARINDEX(@MCC24X, @DiagTyped1 + ' ' + @DiagTyped2) > 0
         Begin
           Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002    
           WHERE DiagProcCode in (' + @MCC24X + ') AND MCC = ''' + @MCC + '''     
           AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
         End

         If @FinalCMG is Null and CHARINDEX(@MCC24X, @DiagTyped1 + ' ' + @DiagTyped2) > 0
		Set @FinalCMG = '868'
	 Else If CHARINDEX(@MCC24X, @DiagTyped1 + ' ' + @DiagTyped2) = 0
         Begin   
           Set @FinalCMG = '999'   
           Set @FinalMCCCode = 'MC99XM01MD'   
           Set @MCC = '99'   
         End   
      End
      Else If @FinalCMG is null and @BranchCMG is not null and @MCC not in ('05A', '08X', '10X') 
      Begin 
          Declare @ProcTemp as VarChar(15) 
          set @FinalCMGTemp = @BranchCMG   
          Set @ProcTemp = @CMGProc 
          Set @BranchTemp = @BranchCMG 
          Set @BranchCMG = Null   
   
          Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
          WHERE DiagProcCode in (' + @ProceduresAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
          AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', @Branch output, @BranchCMG Output, @CMGProc Output   
          If @BranchCMG is null 
           Begin 
              Set @FinalCMG = @FinalCMGTemp 
              Set @FinalMCCCode = @BranchTemp 
              Set @CMGProc = @ProcTemp 
           End 
          Else 
           Begin 
              Set @FinalCMG = @BranchCMG 
              Set @FinalMCCCode = @Branch 
           End 
      End 
--2004/04/02 
      Else If @FinalCMG is null
      Begin   
	If  @mcc = '23X' and @ProceduresAll = '''XXX'''
	   Set @SQL = ''
	Else
           Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003    
           WHERE DiagProcCode in (' + @DiagMProcAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
           AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
      End   

    If @MCC = '05A' and (@Partition Between '03' and '15') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02'   
      Begin   
          declare @Diag05 as VarChar(1000) 
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   
   
          set @Diag05 = replace(@DiagMProcAll, replace(replace(Replace(substring(@DiagTypeAll, charindex('|3', @DiagTypeAll) -5, 6), '|', ''), ' ', ''), '''', ''), 'xxx') 
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE (DiagProcCode) in (' + @Diag05 + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
          AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch +  ''' and SortOrder > 6 ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
      
          If @FinalCMG is Null   
              Set @FinalCMG = @FinalCMGTemp   
      End   
      --New 2002/09/20  
      Else If (@MCC = '05A' and (@Partition Between '19' and '21')) or (@MCC = '04X' and (@Partition Between '09' and '11')) or (@MCC = '01X' and (@Partition Between '09' and '11'))  
       or (@MCC = '06X' and (@Partition Between '19' and '21')) or (@MCC = '08X' and (@Partition Between '27' and '29')) or (@MCC = '11X' and (@Partition Between '17' and '19'))  
       or (@MCC = '05B' and (@Partition Between '12' and '14')) 
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 ORDER BY SortOrder'    
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
     
          If @FinalCMG is Null and isnull(@FinalCMGTemp, '0')  = '902' 
   Begin 
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003    
  
             WHERE DiagProcCode in (' + @ProceduresAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
             AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
   End 
   Else If @FinalCMG is Null 
              Set @FinalCMG = @FinalCMGTemp    
      End    
      Else If @MCC = '05A' and (@Partition Between '03' and '15') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) <> 'L02'   
          Set @FinalCMG = Null   
      Else If (@MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02' AND (@LOS >= 4)) or    
          ((@MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02') and (@DDisposition in ('07', '06') or @IsAcuteTo = 1 or @IsAcutefrom = 1))   
      Begin   
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003    
          WHERE (DiagProcCode) in (' + @DiagMProcAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
          AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' and SortOrder > 2 ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
          If @FinalCMG is Null   
              Set @FinalCMG = @FinalCMGTemp   
          else if @Partition = '01'   
              Set @FinalCMG = @FinalCMG - 4   
          else   
              Set @FinalCMG = @FinalCMG - 2   
      end   
      Else If @MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02' And @LOS < 4   
          Set @FinalCMG = '218'   
      Else if @MCC = '05A' and (@Partition = '03' or @Partition = '04' or @Partition = '05')   
      Begin   
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
             
          If @FinalCMG is Null   
              Set @FinalCMG = @FinalCMGTemp   
          If @FinalCMG in ('176', '178', '181')   
              Set @FinalCMG = '183'   
          Else If @FinalCMG in ('177', '179', '182')   
          Begin   
              set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
              AND MCCCode = ''MC05AS' + @Partition + 'NPL02'''   
              exec sp_executesql @sql, N'@count int output', @Count output   
              If isnull(@Count, 0) > 0   
                  Set @FinalCMG = @FinalCMG - 1   
          End   
      end   
      Else if @MCC = '05A' and @Partition = '10' and (@FinalCMG = '181' or @FinalCMG = '182')   
      Begin  
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   
	If @FinalCMGTemp = '182'
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND sortorder = 2 AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
	else
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND sortorder = 1 AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   

          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
             
          If @FinalCMG is Null and @FinalCMGTemp = '182'
              Set @FinalCMG = '182' 
          else If @FinalCMG is Null and @FinalCMGTemp = '181'
              Set @FinalCMG = '194'   
      End   
      --New 2002/09/19  
      Else If @MCC = '06X' and (@Partition = '12')  
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = @FinalCMGTemp    
      End    
      --New 2002/09/24  
      Else If ((@MCC = '08X' and (@Partition in ('04', '05', '07'))) or (@MCC = '21X' and (@Partition in ('08', '10'))) or 
           (@MCC = '23X' and (@Partition in ('02', '04')))) and @FinalCMG = '350'  
      Begin    
          set @FinalCMG = NULL  
          Declare @MC08Count as int    
          set @SQL = 'SELECT @MC08Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @ProceduresAll + '))    
          AND MCCCode = ''MC' + left(@mcc, 2) + 'XS' + @Partition + 'PRL01''' 
          exec sp_executesql @sql, N'@MC08Count int output', @MC08Count output   
   
          If isnull(@MC08Count, 0) > 1 and len(@ProceduresAll) > 30 
             Set @FinalCMG = 350    
          Else  
          Begin  
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
             WHERE ((DiagProcCode) in (' + @DiagMProcAll + ')) 
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SortOrder > 1 ORDER BY SortOrder'    
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          End  
   
          If @FinalCMG is Null    
     Begin
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
             WHERE ((DiagProcCode) in (' + @DiagMProcAll + ')) 
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 2 ORDER BY SortOrder'    
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
     End
      End    
      Else If @MCC = '08X' and (@Partition between '10' and '25') and SUBSTRING(@Branch, 6, 1) = 'S' 
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = @FinalCMGTemp    
      End    
      --New 2002/09/19  
      Else If @MCC = '09X'  
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = @FinalCMGTemp    

	  If @FinalCMG = '438'
	  Begin
	          set @FinalCMGTemp = @FinalCMG    
	          Set @FinalCMG = Null    
	
	          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
	          WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
	           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
	          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = '437'    
	  End
	  --Ticket 10302
	  If @FinalCMG = '427'
	  Begin
	          set @FinalCMGTemp = @FinalCMG    
	          Set @FinalCMG = Null    
	
	          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
	          WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
	           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
	          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = '425'    
	  End
      End    
      Else If @MCC = '10X' and @Partition = '01' and SUBSTRING(@FinalMCCCode, 5, 2) = 'XS' 
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = @FinalCMGTemp    
      End    
      --New 2002/09/25  
      Else If @MCC = '19X' and (@FinalCMG not in ('771', '778', '767')) and @FinalCMG is not null 
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Declare @LenDiag as int 
          Declare @Diag19X as NVarChar(200) 
          set @LenDiag = len(@DiagMProcAll) - len(@DiagMostResposible) - 4 
          If @LenDiag < 0 
          Begin 
             Set @LenDiag = 0 
             Set @Diag19X = '''''' 
          End 
          Else 
             Set @Diag19X = right(@DiagMProcAll, @LenDiag) 
          set @Diag19X = replace(@Diag19X, replace(replace(Replace(substring(@DiagTypeAll, charindex('|3', @DiagTypeAll) -5, 6), '|', ''), ' ', ''), '''', ''), 'xxx') 
     If right(@Diag19X, 1) = ',' 
           set @Diag19X = left(@Diag19X, len(@Diag19X)-1)
     If right(@Diag19X, 2) = ', ' 
           set @Diag19X = left(@Diag19X, len(@Diag19X)-2)

     If right(@Diag19X, 1) <> '''' 
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
             WHERE ((DiagProcCode) in (' + @Diag19X + '''))    
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
     Else
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
             WHERE ((DiagProcCode) in (' + @Diag19X + '))    
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    

          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
          Begin  
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
             WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
              AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 1 ORDER BY SortOrder'    
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          End  
      End   
      Else If @MCC = '11X' and (@Partition = '01') and right(@FinalMCCCode, 3) = 'L01' 
      Begin	
	If @LOS > 2 or @DDisposition in ('06','07') or @isAcuteTo = 1 or @isAcuteFrom = 1
		Set @FinalCMG = '520'	
	Else if @LOS < 3 AND @isAcuteTo = 0 and @isAcuteFrom = 0
		Set @FinalCMG = '999'	
      End
      Else if @MCC = '13X' and @FinalMCCCode like 'MC13XS04%'   
      Begin   
          If @FinalMCCCode = 'MC13XS04PRL02'   
          Begin   
              set @FinalCMGTemp = @FinalCMG   
              Set @FinalCMG = Null   
              set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProc + '))    
              AND MCCCode in (''MC13XS04MDL03'', ''MC13XS04PRL04'') ORDER BY SortOrder'   
              exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
      
              If @FinalCMG is Null   
                  Set @FinalCMG = '579'   
          End   
          Else If @FinalMCCCode = 'MC13XS04MDL01'   
          Begin   
              set @FinalCMGTemp = @FinalCMG   
              Set @FinalCMG = Null   
              set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProc + '))    
              AND MCCCode = ''MC13XS04PRL02'''   
              exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
   
              If @FinalCMG is Null   
                  Set @FinalCMG = @FinalCMGTemp   
          End   
          If @FinalMCCCode = 'MC13XS04MDL03'   
          Begin   
              set @FinalCMGTemp = @FinalCMG   
              Set @FinalCMG = Null   
              set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProc + '))    
              AND MCCCode = ''MC13XS04PRL04'''   
              exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
                 
              If @FinalCMG is Null   
                  Set @FinalCMG = @FinalCMGTemp   
          End   
          Else If @FinalMCCCode = 'MC13XS04PRL04'   
              Set @FinalCMG = '579'   
      end   
      Else If (@MCC = '14X' and (@Partition = '05')) And (@LOS >= 3 or @IsAcuteTo = 1 or @IsAcuteFrom = 1) 
          Set @FinalCMG = '599'   
      Else If @MCC = '14X' and (@Partition = '01') and @FinalSubBranch = 1 and ((@FinalCMG = '612' or (@FinalCMG is null and @MRDxCMG = '612')))
      Begin   
          Set @FinalCMG = Null   
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
          SortOrder = 1 ORDER BY SortOrder' 
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
          If @FinalCMG is Null   
              Set @FinalCMG = 600   
      end   
      Else If @MCC = '15X' and (@Partition Between '03' and '06') and right(@FinalMCCCode, 3) = 'L01' And @LOS < 6   
          Set @FinalCMG = 998   
--Added on Ticket 9161
      Else If @MCC= '15X' and (@Partition Between '03' and '06') and right(@FinalMCCCode, 3) = 'L01' and (@DDisposition in ('07', '06') or @IsAcuteTo = 1 or @IsAcutefrom = 1 or @LOS > 6) 
      Begin

	  If @Partition = '03'
          	Set @FinalCMG = 627  
	  If @Partition = '04'
          	Set @FinalCMG = 630  
	  If @Partition = '05'
          	Set @FinalCMG = 636  
	  If @Partition = '06'
          	Set @FinalCMG = 643  
      End
      Else If @MCC = '15X' and (@Partition in ('06', '05')) and ((@FinalCMG = '646' or (@FinalCMG is null and @MRDxCMG = '646')) or 
      (@FinalCMG = '647' or (@FinalCMG is null and @MRDxCMG = '647')) or (@FinalCMG = '648' or (@FinalCMG is null and @MRDxCMG = '648'))
      or (@FinalCMG = '639' or (@FinalCMG is null and @MRDxCMG = '639'))or (@FinalCMG = '640' or (@FinalCMG is null and @MRDxCMG = '640')))
      Begin   
          Set @FinalCMG = Null   
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE (((DiagProcCode) in (' + @DiagMProcAll  + ')) or
	  ((DiagProcCode) in (''''' + @DiagTyped0 + @DiagTyped3 + ')) and isnull(translatefrom, '''') = '''')
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
          SortOrder = 4 ORDER BY SortOrder' 
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
          If @FinalCMG is Null   
          Begin
           set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
           SortOrder > 4 ORDER BY SortOrder' 
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
           If @FinalCMG is Null and @MRDxCMG in ('646', '647', '648')
               Set @FinalCMG = 648   
           Else If @FinalCMG is Null and @MRDxCMG in ('639', '640')
               Set @FinalCMG = 640   
      	  End
      end 
--2004/04/02 -+ @DiagTyped3  
      Else If @MCC = '14X' and (@Partition = '02')-- and right(@FinalMCCCode, 3) = 'L01'   
      Begin   
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
          SortOrder = 1 ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
             
          If @FinalCMG is Null   
              Set @FinalCMG = @FinalCMGTemp   
          Else  
          Begin  
             set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
             SortOrder > 1 ORDER BY SortOrder'   
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
  
             If @FinalCMG is Null   
                 Set @FinalCMG = @FinalCMGTemp   
             If @FinalCMG = '601'   
                 Set @FinalCMG = '603'   
             Else If @FinalCMG in ('602', '604')
             Begin   
                 set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + @DiagTyped3 + '))    
                 AND MCCCode = ''MC14XS02MOL03'''   
                 exec sp_executesql @sql, N'@count int output', @Count output   
                 If isnull(@Count, 0) > 0   
                     Set @FinalCMG = @FinalCMG - 1   
             End   
      End  
      end   
      Else If @MCC = '14X' and (@Partition = '02') and right(@FinalMCCCode, 3) <> 'L01' and SUBSTRING(@FinalMCCCode, 5, 2) <>  'XM'   
          Set @FinalCMG = 999   
     Else If @MCC = '14X' and (@FinalCMG Between '608' and '611' or (@FinalCMG is null and @MRDxCMG Between '608' and '611'))--(@FinalCMG = '608' or @FinalCMG = '609')   
     Begin   
         If @FinalCMG = '608'   
             Set @FinalCMG = '610'   
         Else 
         Begin   
             set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + @DiagTyped3 +  '))    
             AND MCCCode = ''MC14XM01MOL04'''  
             exec sp_executesql @sql, N'@count int output', @Count output  
             If isnull(@Count, 0) > 0 and @FinalCMG is not null
                 Set @FinalCMG = @FinalCMG - 1   
             Else If isnull(@Count, 0) > 0 and @FinalCMG is null
                 Set @FinalCMG = @MRDxCMG - 1   
         End   
     End   
      Else If @MCC = '14X' and (@FinalCMG in ('620', '621'))   
      Begin   
          If @FinalCMG = '621'   
          Begin   
              set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagnosisAll + '))    
              AND MCCCode = ''MC14XM06PRL10'''   
              exec sp_executesql @sql, N'@count int output', @Count output   
              If isnull(@Count, 0) > 0   
                  Set @FinalCMG = @FinalCMG - 1   
          End   
      end   
      Else if @MCC = '21X' and (@Partition in ('05', '06'))   
      Begin   
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   

          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   

          If @FinalCMG is Null 
              Set @FinalCMG = @FinalCMGTemp  
          If @FinalCMG in ('176', '178', '181')   
              Set @FinalCMG = '183'   
          Else If @FinalCMG in ('177', '179', '182')   
          Begin  
              set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
              AND MCCCode = ''MC21XS' + @Partition + 'NPL02'''   
              exec sp_executesql @sql, N'@count int output', @Count output   
              If isnull(@Count, 0) > 0   
                  Set @FinalCMG = @FinalCMG - 1   
          End   
      end   
      Else if @MCC = '22X' and (@Partition in ('01', '02')) --Ticket 9698
      Begin   
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   

          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   

          If @FinalCMG is Null 
              Set @FinalCMG = @FinalCMGTemp  
      end 
      Else If @MCC = '25X' and SUBSTRING(@Branch, 6, 1) = 'S' and SUBSTRING(@Branch, 7, 2) = '05' and @FinalCMG in ('351', '350') 
      Begin
   	Declare @MC25Proc as VarChar(15) 
   	Declare @MC25Count as int   
          If @FinalCMG = 350   
  	Begin 
              set @SQL = 'SELECT @MC25Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @ProceduresAll + '))    
              AND MCCCode = ''MC25XS05PRL03'''   
              exec sp_executesql @sql, N'@MC25Count int output', @MC25Count output   
           If @MC25Count = 1 
           Begin
                   set @SQL = 'SELECT  @MC25Proc = diagproccode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @ProceduresAll + '))    
                   AND MCCCode = ''MC25XS05PRL03'''   
                   exec sp_executesql @sql, N'@MC25Proc varchar(15) output', @MC25Proc output                   
  
                  If len(replace(@ProceduresAll, '''' + @MC25Proc + '''', '')) < (len(@ProceduresAll) - len(@MC25Proc) - 3)
                           Set @MC25Count = 2 
           End
   End 
   
          If isnull(@MC25Count, 0) < 2   
              Set @FinalCMG = 351   
      End   

      if len(@FinalMCCCode) > 10   
          Set @Branch = left(isnull(@FinalMCCCode, ''), 10)   

      If @FinalCMG is null   
      Begin   
          If @BranchCMG is null   
              Set @FinalCMG = @MRDxCMG   
          Else   
              Set @FinalCMG = @BranchCMG   
          If @FinalCMG is null 
               Set @FinalCMG = '999'   
      End   

      --Ticket 9330
      If @MCC is null
	set @MCC = '99'
  
      if len(@FinalMCCCode) > 10   
          Set @Branch = left(isnull(@FinalMCCCode, ''), 10)  

      Declare @MedSurgInd as VarChar(1) 
      Declare @MedSurgNon as VarChar(1) 
      SELECT @MedSurgNon = cmgmcctype, @MedSurg = cmgmcctype, @MedSurgInd = RIWInd FROM CMG_Etc_2003T WHERE (cmgcode = @FinalCMG) and (ciagegroup = @AgeGroup)    

      Set @PlexA = 0   
      Set @PlexB = 0   
      Set @PlexC = 0   
      Set @PlexD = 0   
      Set @PlexP = 0   
      Set @PlexCMCC = 0   
      If exists (SELECT * FROM CMG_Etc_2003T WHERE ((cmgcode = @FinalCMG) AND (cicpxlvl = 9) and (ciagegroup = @AgeGroup)) or @MedSurg = '9') 
          set @Complexity = 9   
      Set @DiagTypeAll = replace(@DiagTypeAll, @DiagMostResposible + '|', 'XXXXX|')   

      if @Plx4 = 'Y' and isnull(@Complexity, '') <> '9'
	set @Complexity = 4  
      If isnull(@AbstractID, 0) > 0 and (CHARINDEX ('1GZ31CAND', @ProceduresAll ) > 0 or CHARINDEX ('1GZ31CRND', @ProceduresAll ) > 0)
   and @Complexity is null
      Begin   
	   if exists (SELECT dbo.AB_Intervention.AbstractID FROM dbo.AB_Intervention LEFT OUTER JOIN
           dbo.ICD_ProcFile10 ON dbo.AB_Intervention.IntervCode = dbo.ICD_ProcFile10.Code LEFT OUTER JOIN
           dbo.LU_IntervAttExtent ON dbo.AB_Intervention.IntervAttribExtent = dbo.LU_IntervAttExtent.Code
           WHERE (dbo.LU_IntervAttExtent.CIHIValue IN ('EX')) AND (dbo.ICD_ProcFile10.CIHIValue  in ('1GZ31CAND', '1GZ31CRND')) AND (dbo.AB_Intervention.AbstractID = @AbstractID))
	   set @Complexity = 4  
      End

     --If there are duplicate diagnosis with the same type, take type 1
     Declare @DupDiagComplex as Varchar(20)
     set @SQL = 'SELECT top 1 @DupDiagComplex = diagnosis FROM CMG_Plx2002   
         WHERE DiagTypeCombine in (' + @DiagTypeAll + ')
 	AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''') 
 	And Diagnosis not in (SELECT DiagnosisEx FROM dbo.CMG_PlxException2001 WHERE (MCCEx = LEFT(''' + @MCC + ''',2)) AND (CMGEx = ''' + @FinalCMG + '''))
 	group by diagnosis having Count(diagnosis) > 1'   
     exec sp_executesql @sql, N'@DupDiagComplex VarChar(20) output', @DupDiagComplex output 

     If isnull(@DupDiagComplex, '') <> ''
    	Set @DiagTypeAll = replace(@DiagTypeAll, @DupDiagComplex + '|2', 'XXXXX|2')   
  
           Create TABLE #PlxTemp (PlCount int, Plex varchar(1))
  --Plex Levels
   set @SQL = 'SELECT count(*) as PlCount, substring(Plexity, cast(LEFT(''' + @MCC + ''',2) as int), 1) as Plex FROM CMG_Plx2003   
          WHERE DiagTypeCombine in (' + @DiagTypeAll + ')
   AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''') 
   And Diagnosis not in (SELECT DiagnosisEx FROM dbo.CMG_PlxException2003 WHERE (MCCEx = LEFT(''' + @MCC + ''',2)) AND (CMGEx = ''' + @FinalCMG + '''))
   group by substring(Plexity, cast(LEFT(''' + @MCC + ''',2) as int), 1)'   
   Insert into #PlxTemp Exec (@SQL)
  
      if @Complexity is null and @@Rowcount > 0   
      Begin  
  --Level C Not Home Plex
   set @SQL = 'SELECT @PlexCMCC = count(*) FROM CMG_Plx2003   
        WHERE DiagTypeCombine in (' + @DiagTypeAll + ') and substring(Plexity, cast(LEFT(''' + @MCC + ''',2) as int), 1) = ''C'' 
   and HomeMCC <> LEFT(''' + @MCC + ''',2)
   AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''') 
   And Diagnosis not in (SELECT DiagnosisEx FROM dbo.CMG_PlxException2003 WHERE (MCCEx = LEFT(''' + @MCC + ''',2)) AND (CMGEx = ''' + @FinalCMG + '''))'   
   exec sp_executesql @sql, N'@PlexCMCC VarChar(1) output', @PlexCMCC output   
   Set @PlexA = isnull((select PlCount from #PlxTemp where Plex = 'A'), 0)
   Set @PlexB = isnull((select PlCount from #PlxTemp where Plex = 'B'), 0)
   Set @PlexC = isnull((select PlCount from #PlxTemp where Plex = 'C'), 0)
   Set @PlexD = isnull((select PlCount from #PlxTemp where Plex = 'D'), 0)
   Set @PlexP = isnull((select PlCount from #PlxTemp where Plex = 'P'), 0)
   If @PlexCMCC > 1
           Set @PlexCMCC = 1
  
          If @PlexA > 0 or @PlexB > 1 or (@PlexB = 1 and @PlexC > 0 and @PlexCMCC = 1)   
              Set @Complexity = 4   
          Else If @PlexB > 0 or (@PlexC > 1 and @PlexCMCC = 1) or (@PlexC > 10 and @PlexCMCC = 0)   
              Set @Complexity = 3   
          Else If @PlexD > 0 or @PlexP > 0 or (@PlexC = 1 and @PlexCMCC = 1)    
              or (@PlexC > 0 and @PlexC < 11 and @PlexCMCC = 0)   
              Set @Complexity = 2   
          Else   
              Set @Complexity = 1   
      End   

      If isnull(@Complexity, '') = ''   
          Set @Complexity = 1   
      
      Set @MCC = Replace(@MCC, 'X', '')   
      Set @ComplexityLevel = @Complexity   
      SELECT Top 1 @CmgDesc = cmgdesc, @CmgTrim = ciagtrim, @CmgELOS = ciagelos, @CmgPDRA = ciagpdra, @CmgPDWGT = ciagpdwgt, @CmgRIW = ciagriw   
      FROM dbo.CMG_Etc_2003T WHERE (cmgcode = @FinalCMG) AND (cicpxlvl = @ComplexityLevel) AND (ciagegroup = @AgeGroup) --AND (cmgmcctype = @MedSurg)  
  --print @CmgDesc 
  --print @CmgTrim 
  --print @CmgELOS 
  --print @CmgPDRA 
  
   --New 2002/09/30 
      If @MedSurg = 9 
      Set @MedSurg = 1   
      If @FinalCMG in ('910', '912', '998', '999') and @LOS < cast(@CMGELOS as decimal(7,4))   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      Else If @FinalCMG in ('910', '912', '998', '999') and @LOS >= cast(@CMGELOS as decimal(7,4))   
          Set @CMGRIW = @CmgRIW
      else if @DDisposition = '07' and @LOS <= @CMGTrim and @LOS <= 10   
      Begin   
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer    
              WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr is null and dxyear = 2003)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      else if @DDisposition = '07' and @LOS <= @CMGTrim and @LOS > 10   
      Begin 
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
              WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr is null and dxyear = 2003)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      Else If @DDisposition = '06' and @LOS <= cast(@CMGELOS as decimal(7,4))   
          Set @CMGRIW = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,4))) as decimal(7,4))   
      Else If @DDisposition = '06' and @LOS > cast(@CMGELOS as decimal(7,4)) and @LOS <= @CMGTrim   
          Set @CMGRIW = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@CmgELOS as decimal(7,4))) as decimal(7,4))   
      Else If @IsAcuteTo = 1 and @LOS <= 10 and @LOS <= @CMGTrim   
      Begin   
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
              WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='O' and dxyear = 2003)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      Else If @IsAcuteTo = 1 and @LOS > 10 and @LOS <= @CMGTrim   
      Begin   
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
              WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='O' and dxyear = 2003)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      Else If @IsAcuteFrom = 1 and @LOS <= 10 and @LOS <= @CMGTrim   
      Begin   
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
              WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='I' and dxyear = 2003)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      Else If @IsAcuteFrom = 1 and @LOS > 10 and @LOS <= @CMGTrim   
      Begin   
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
              WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='I' and dxyear = 2003)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      Else If @LOS > @CMGTrim   
          Set @CMGRIW = cast(cast(@CMGRIW as decimal(7,4)) + (cast(@CmgPDRA as decimal(7,4)) * cast((cast(@LOS as decimal(7,2)) - cast(@CmgELOS as decimal(7,4))) as decimal(9,4))) as decimal(9,4))   

      Declare @CMGNon as int
      Select @CMGNon = CMGNonValue from CMG_NonBool where CMGNonYear = 2003
      if @CmgRIW is not null and isnull(@CMGNon, 0) = 0
      Begin  
          Select @RIW$ = CostPerRiw from H_InstitutionProfile where code = @InstNumber   
          if isnull(@RIW$, '0') = '0' or @RIW$ = ''   
              set @RIW$ = '0'   
          Set @CMGRIW$ = cast(@CmgRIW as decimal(7,4)) * cast(@RIW$ as decimal(6,2))   
          if @LOS - @CMGTrim > 0   
          Begin   
              Set @CMGMOH = left(@CMGRIW + (((@LOS - @CMGTrim) * cast(@CmgPDWGT as Decimal(7,4))) + (((cast(@CMGTrim as int) - cast(@CMGELOS as decimal(6,2))) * cast(@CmgPDWGT as Decimal(7,4)))) * .2), 10)   
              Set @CMGMOH$ = cast(@CmgMOH as decimal(9,4)) * cast(@RIW$ as decimal(6,2))   
          end   
          Else   
          Begin   
              Set @CMGMOH = @CMGRIW   
              Set @CMGMOH$ = @CMGRIW$   
          end   
          Set @CMGMOH = cast(@CMGMOH as decimal(8,4))   
          Set @CMGRIW$ = cast(@CMGRIW$ as decimal(10,2))   
          Set @CMGMOH$ = cast(@CMGMOH$ as decimal(10,2))   
      End
--If they have rights to non complex grouper do this
     else if @CmgRIW is not null and exists(select code from H_HospitalProfile where code + @CMGNon = 33101) --PR - 00945
     Begin
		declare @IsAcuteFromNon as bit
		declare @IsAcuteToNon as bit
		set @IsAcuteFromNon = @IsAcuteFrom
		Set @IsAcuteToNon = @IsAcuteTo
		if @IsAcuteFromNon = 0
		Begin
			If exists(select code FROM LU_Institution_10 WHERE code = @InstFrom and CIHIValue in ('53240', '53310', '53459', '53781', '53913'))
				set @IsAcuteFromNon = 1
		End
		If @IsAcuteToNon = 0
		Begin
			If exists(select code FROM LU_Institution_10 WHERE code = @InstTo and CIHIValue in ('53240', '53310', '53459', '53781', '53913'))
				set @IsAcuteToNon = 1
		End

          Select @RIW$ = CostPerRiw from H_InstitutionProfile where code = @InstNumber   
          if isnull(@RIW$, '0') = '0' or @RIW$ = ''   
              set @RIW$ = '0'   
          Set @CMGRIW$ = cast(@CmgRIW as decimal(7,4)) * cast(@RIW$ as decimal(6,2))   
	     Declare @MedSurgIndHold as VarChar(1)
	     If @Complexity = 9
	     Begin
		Set @MedSurgIndHold = @MedSurgInd
		Set @MedSurgInd = 9
	     End
	     Declare @CmgNonELOS as VarChar(10)   
	     Declare @CmgNonTrim as VarChar(10)

	     SELECT Top 1 @CmgNonTrim = ciagtrim, @CmgNonELOS = ciagelos, @CmgPDRA = ciagpdra, @CmgPDWGT = ciagpdwgt, @CMGMOH = ciagriw   
	     FROM dbo.CMG_ETC_2002_Non WHERE (cmgcode = @FinalCMG) AND (ciagegroup = @AgeGroup) and (ICDType = 'T') --AND (cmgmcctype = @MedSurg)   

	     If @MedSurg = 9 
	 	Set @MedSurg = 1   
	     If @FinalCMG in ('910', '912', '998', '999') and @LOS < cast(@CmgNonELOS as decimal(7,4))   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     else if @DDisposition = '07' and @LOS <= @CmgNonTrim and @LOS <= 10   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non    
	             WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and isnull(cmgxfr, '') = '' and dxyear = 2002)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))
    	     End   
	     else if @DDisposition = '07' and @LOS <= @CmgNonTrim and @LOS > 10   
	     Begin 
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non  
	             WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and isnull(cmgxfr, '') = '' and dxyear = 2002)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @DDisposition = '06' and @LOS <= cast(@CmgNonELOS as decimal(7,4))   
	         Set @CMGMOH = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,4))) as decimal(7,4))   
	     Else If @DDisposition = '06' and @LOS > cast(@CmgNonELOS as decimal(7,4)) and @LOS <= @CmgNonTrim   
	         Set @CMGMOH = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@CmgNonELOS as decimal(7,4))) as decimal(7,4))   
	     Else If @IsAcuteFromNon = 1 and @LOS <= 10 and @LOS <= @CmgNonTrim   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
	             WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and cmgxfr ='I' and dxyear = 2002)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @IsAcuteFromNon = 1 and @LOS > 10 and @LOS <= @CmgNonTrim   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
	             WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and cmgxfr ='I' and dxyear = 2002)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End
	     Else If @IsAcuteToNon = 1 and @LOS <= 10 and @LOS <= @CmgNonTrim   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
	             WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and cmgxfr ='O' and dxyear = 2002)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @IsAcuteToNon = 1 and @LOS > 10 and @LOS <= @CmgNonTrim   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
	             WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and cmgxfr ='O' and dxyear = 2002)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @LOS > @CmgNonTrim 
	         Set @CMGMOH = cast(cast(@CMGMOH as decimal(7,4)) + (cast(@CmgPDRA as decimal(7,4)) * cast((cast(@LOS as decimal(7,2)) - cast(@CmgNonELOS as decimal(7,4))) as decimal(9,4))) as decimal(9,4))   
	     
	     If @MedSurgInd = 9
		Set @MedSurgInd = @MedSurgIndHold

	      If @DDisposition = '07'   
	          Set @NonAcuteQuartile = 'D'   
	      Else If @DDisposition = '06'   
	          Set @NonAcuteQuartile = 'S'   
	      Else If @IsAcuteFromNon = 1 or @IsAcuteToNon = 1 --or @DDisposition = '01' ticket 5711  
	          Set @NonAcuteQuartile = 'T'   
	      Else If @LOS > @CmgNonTrim   
	          Set @NonAcuteQuartile = 'O'   
	      Else If @LOS > cast(@CmgNonELOS as decimal(7,4))   
	          Set @NonAcuteQuartile = 'B'   
	      Else   
	          Set @NonAcuteQuartile = 'I'  
          Set @CMGMOH$ = cast(@CmgMOH as decimal(9,4)) * cast(@RIW$ as decimal(6,2))   
          Set @CMGMOH = cast(@CMGMOH as decimal(8,4))   
          Set @CMGRIW$ = cast(@CMGRIW$ as decimal(10,2))   
          Set @CMGMOH$ = cast(@CMGMOH$ as decimal(10,2))   
      End   
     
      If @DDisposition = '07'   
          Set @AcuteQuartile = 'D'   
      Else If @DDisposition = '06'   
          Set @AcuteQuartile = 'S'   
      Else If @IsAcuteFrom = 1 or @IsAcuteTo = 1 --or @DDisposition = '01' ticket 5711  
          Set @AcuteQuartile = 'T'   
      Else If @LOS > @CMGTrim   
          Set @AcuteQuartile = 'O'   
      Else If @LOS > cast(@CMGELOS as decimal(7,4))   
          Set @AcuteQuartile = 'B'   
      Else   
          Set @AcuteQuartile = 'I'   
    
      If @MedSurgInd = '2' 
   Set @MedOrSurg = 'M' 
      Else 
   Set @MedOrSurg = 'S' 

	If isnull(@AbstractID, 0) > 0 and @Occurance = 1
	Begin
		Declare @AUCmg as Varchar(3)
		Declare @AUCplx as VarChar(1)
		Declare @AUMcc as Varchar(3)
		Declare @AUQuartile as VarChar(1)
		Declare @AURiw as VarChar(20)
		Declare @AUAid as Int
		--EN00085
		Declare @GrouperChange as VarChar(1)
		Set @GrouperChange = 'N'
		SELECT @AUAid = Abstractid, @AUCmg = CMG, @AUCplx = Complexity, @AUMcc = MCC, @AUQuartile = AcuteQuartile, @AURiw = CMG_RIW
		FROM AB_CMG where AbstractID = @AbstractID and OccurrenceNumber = 1 and CMG_Year = 2003
		If isnull(@AUAid, 0) > 0
		Begin
			If @AUCmg <> @FinalCMG
			Begin
				Insert into AB_GrouperAudit Values (@AbstractID, 2003, 'CMG', @AUCmg, @FinalCMG, GetDate())
				Set @GrouperChange = 'Y'
			End
			If @AUCplx <> @ComplexityLevel
				Insert into AB_GrouperAudit Values (@AbstractID, 2003, 'Complexity', @AUCplx, @ComplexityLevel, GetDate())
			If left(@AUMcc, 2) <> Left(@MCC, 2)
				Insert into AB_GrouperAudit Values (@AbstractID, 2003, 'MCC', @AUMcc, Left(@MCC, 3), GetDate())
			If @AUQuartile <> @AcuteQuartile
				Insert into AB_GrouperAudit Values (@AbstractID, 2003, 'Quartile', @AUQuartile, @AcuteQuartile, GetDate())
			If @AURiw <> @CmgRIW
			Begin
				Insert into AB_GrouperAudit Values (@AbstractID, 2003, 'RIW', @AURiw, @CmgRIW, GetDate())
				Set @GrouperChange = 'Y'
			End
		End
		If @GrouperChange = 'Y' and @FlagRecord = 'Y'
			Update AB_Abstract set iscorrected = 2 where abstractid = @AbstractID and issubmited = 1 and isdeleted = 2 and iscorrected = 1
				and batchyear = 2003
	End
      
      If isnull(@AbstractID, 0) > 0 
      Begin   
          Delete ab_CMG where Abstractid = @Abstractid and CMG_Year = 2003 and OccurrenceNumber = @Occurance  
          If IsNull(@FinalCMG, '') <> '' and isnull(@DiagMostResposible, '') <> ''
          Begin   
              Set @DiagMostResposible = (select top 1 code from ICD_DiagFile10 where cihivalue = @DiagMostResposible)   
              INSERT INTO [dbo].[AB_CMG] ([AbstractID], [OccurrenceNumber], [CMG_Year], [ICD_Type], [Diagnosis_Code],   
              [Diagnosis_Type], [CMG], [Complexity], [MCC], [AcuteQuartile], [CMG_RIW], [MOH_RIW],   
              [RIW_Dollar], [MOH_Dollar], [CMG_ELOS], [CMG_Trim], [CMG_Description], [MCC_Surg], MOHQuartile, ExpiryDate) VALUES    
              (@AbstractID, @Occurance, 2003, 'T', @DiagMostResposible, 11, @FinalCMG, @ComplexityLevel, rtrim(Left(@MCC, 3)), @AcuteQuartile, @CmgRIW, @CmgMOH,    
              cast(@CmgRIW$ as money), cast(@CmgMOH$ as money), @CmgELOS, @CMGTrim, @CMGDesc, @MedOrSurg,@NonAcuteQuartile, @ExpiryDate)   
              Update ab_CMG set CMGModelType = ModelType, CMGTenthPercent = TenthPercent, CMGTwentyFifthPercent = TwentyFifthPercent, CMGFiftiethPercent = FiftiethPercent
              FROM dbo.AB_CMG LEFT OUTER JOIN
              dbo.CMG_Etc_2003T ON dbo.AB_CMG.Complexity = dbo.CMG_Etc_2003T.cicpxlvl AND dbo.AB_CMG.CMG = dbo.CMG_Etc_2003T.cmgcode
              WHERE abstractid = @AbstractID and CMG_Year = 2003 and ciagegroup = @AgeGroup
          End   
      
      End   
      set nocount off    

  --    print datediff(ms, @SDate, getdate())   
      Return 0



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE                     PROCEDURE [P_CMG2004_T]   
      @Age as Int,   
      @AgeCode as int, 
      @LOS as int,   
      @AcuteLOS as int,   
      @ICDType as VarChar(2),   
      @Gender as VarChar(1),   
      @Weight as int,   
      @DDisposition as VarChar(2),   
      @InstNumber as int,   
      @InstTo as int,   
      @InstFrom as int,   
      @DiagMostResposible as VarChar(10),   
      @DiagnosisAll as VarChar(500),   
      @DiagTypeAll as VarChar(500),   
      @DiagTyped1 as VarChar(500),   
      @DiagTyped2 as VarChar(500),   
      @DiagTyped0 as VarChar(500),   
      @DiagTyped3 as VarChar(500),   
      @ProceduresAll as VarChar(1000),   
      @Procedure1 as VarChar(10),   
      @FinalCMG as VarChar(3) output,   
      @ComplexityLevel as Int output,   
      @MCC as VarChar(3) output,   
      @AcuteQuartile as VarChar(10) output,   
      @CmgRIW as VarChar(10) output,   
      @CmgMOH as VarChar(10) output,   
      @CmgRIW$ as VarChar(20) output,   
      @CmgMOH$ as VarChar(20) output,   
      @CmgELOS as VarChar(10) output,   
      @CmgTrim as VarChar(10) output,   
      @CmgDesc as VarChar(60) output,   
      @MedOrSurg as VarChar(1) output,  
      @AbstractID as Int,

      --Ticket 9011
      @Occurance as int = 1,
      @ExpiryDate as varchar(10) = NULL,
      --Ticket 9373
      @AgeGroup as int,
      @Plx4 as VarChar(1),
	  @FlagRecord as VarChar(1) = 'N'
   AS    
      Declare @MRDxCMG VarChar(8)   
      Declare @Branch VarChar(10)   
      Declare @BranchTemp VarChar(10)   
      Declare @BranchCMG VarChar(3)   
      Declare @IBranchCMG VarChar(3)   
      Declare @Partition as VarChar(2)   
      Declare @FinalSubBranch as VarChar(1)   
      Declare @FinalMCCCode as VarChar(14)   
      Declare @CmgALOS as VarChar(10)   
      Declare @CmgPDRA as VarChar(10)   
      Declare @CmgPDWGT as VarChar(10)   
      Declare @Cat1 as int   
      Declare @Cat2 as int   
      Declare @PlexHomeMcc as VarChar(2)   
      Declare @PlexCount as int   
      Declare @PlexLevel as VarChar(1)   
      Declare @PlexDiagnosis as VarChar(6)   
      Declare @PlexA as int   
      Declare @PlexB as int   
      Declare @PlexC as int   
      Declare @PlexD as int   
      Declare @PlexP as int   
      Declare @Complexity as int   
      Declare @PlexCMCC as int   
      Declare @MedSurg as int      
      Declare @RIW$ as VarChar(10)   
      Declare @CMGProc as Varchar(12)   
      Declare @FinalMCCCodeTemp as VarChar(14)   
      Declare @FinalCMGTemp as VarChar(14)   
      Declare @RIWDeath as VarChar(10)   
      Declare @HospProv as VarChar(2)   
      Declare @IsAcuteTo as bit   
      Declare @IsAcuteFrom as bit   
      Declare @SQL as NVarChar(3000)   
      Declare @count as int   
      Declare @AgeNumber as int   
      Declare @SDate as datetime   
      Declare @NonAcuteQuartile as VarChar(1)
   set @SDate = getdate()   
      Set Nocount on
      Set @IsAcuteTo = 0   
      Set @IsAcuteFrom = 0   
      
     If @AgeCode = 1 and @Age > 28 
     Set @AgeCode = 3 
    
      If @Gender = 'M'   
          Set @Gender = '1'   
      Else If @Gender = 'F'   
          Set @Gender = '2'   
      If isnull(@DiagMostResposible, '0') = '0'   
          Set @DiagMostResposible = ''   
      
      if exists (SELECT * FROM LU_Institution_10 WHERE code = @InstTo and InstCareType = 'A')   
   set @IsAcuteTo = 1  
      if exists (SELECT * FROM LU_Institution_10 WHERE code = @InstFrom and InstCareType = 'A')   
   set @IsAcuteFrom = 1  
      
      If rtrim(@DiagTypeAll) = ''   
          Set @DiagTypeAll = '''XXX'''   
      If @ProceduresAll = ''   
          Set @ProceduresAll = '''XXX'''   
      
      Declare @DiagMProcAll as VarChar(2000)   
      Declare @DiagMProc as VarChar(2000)   
      Set @DiagMProcAll = ''   
      If @DiagMostResposible <> ''   
      Begin   
          set @DiagMProcAll = '''' + @DiagMostResposible + ''', '    
          set @DiagMProc = '''' + @DiagMostResposible + ''', '    
      End   
      Set @DiagMProcAll = replace(@DiagMProcAll, ', ,',  ', ')   
      Set @DiagTypeAll = replace(@DiagTypeAll, ', ,',  ', ')   
      
      If @DiagnosisAll <> ''   
          Set @DiagMProcAll = @DiagMProcAll + @DiagnosisAll + ', '   
  
      If @ProceduresAll <> ''   
      Begin   
          Set @DiagMProcAll = @DiagMProcAll + @ProceduresAll   
          Set @DiagMProc = @DiagMProc + @ProceduresAll   
      End   
      If right(@DiagMProcAll, 2) = ', '   
          Set @DiagMProcAll = Left(@DiagMProcAll, len(@DiagMProcAll) - 2)   
      If right(@DiagMProc, 2) = ', '   
          Set @DiagMProc = Left(@DiagMProc, len(@DiagMProc) - 2)   
      Set @DiagMProcAll = replace(@DiagMProcAll, ', ,',  '')   
    
      If right(@DiagMProcAll, 1) <> ''''   
          Set @DiagMProcAll = @DiagMProcAll + ''''   
      If isnull(@DiagnosisAll, '') = '' 
          Set @DiagnosisAll = '''XXX''' 
  
    --TICKET 8965
	If @DDisposition = '08'  
	  set @MCC = '99X'         
	Else if @DDisposition = '09'   
	Begin   
	  set @MCC = '99'
	  Set @FinalCMG = '997'
	  Set @CmgDesc = 'Stillbirth'
	End 
	Else If (@Weight = 0 and isnull(@AgeCode, 0) <> 1) or (@Weight <> 0 and isnull(@AgeCode, 0) > 1) 	
          SELECT Top 1 @MCC = [MCC], @MRDxCMG = [CMG], @BranchTemp = [MCCCode]  FROM CMG_Main2003   
          WHERE ([DiagProcCode]= @DiagMostResposible) AND ([Priority] = 3) AND (Gender = @Gender Or Gender = 3)   
  
	Else if @Weight < 200 
	Begin
	Set @MCC = '99'
	Set @FinalCMG = '999'
	End
	Else if @Weight < 750 AND @Weight >= 200
	Begin   
	  set @MCC = '15X'   
	  Set @FinalCMG = '625'   
	End   
	Else if @Weight < 1000   
	Begin   
	  set @MCC = '15X'   
	  Set @MRDxCMG = '626'   
	End   
	Else if @Weight < 1500   
	Begin   
	  set @MCC = '15X'   
	  Set @MRDxCMG = '628'   
	  Set @BranchTemp = 'MC15XM03MD'   
	End   
	Else if @Weight < 2000   
	Begin   
	  set @MCC = '15X'   
	  Set @MRDxCMG = '632'   
	  Set @BranchTemp = 'MC15XM04MD'   
	End   
	Else if @Weight < 2500   
	Begin   
	  set @MCC = '15X'   
	  Set @MRDxCMG = '640'   
	  Set @BranchTemp = 'MC15XM05MD'   
	End   
	Else if @Weight > 2499 AND @Weight < 9000
	Begin   
	  set @MCC = '15X'   
	  Set @MRDxCMG = '648'   
	  Set @BranchTemp = 'MC15XM06MD'   
	End
	Else if @Weight > 8999 
	Begin
	Set @MCC = '99'
	Set @FinalCMG = '999'
	End
      If (@BranchTemp in ('MC19XM01MD', 'MC19XM02MD', 'MC19XM05MD') and @LOS < 6 and (@DDisposition = '05' or (@IsAcuteTo = 0 or @IsAcuteFrom = 0)) and @DDisposition not in ('06', '07')
   and (@IsAcuteTo = 0 and @IsAcuteFrom = 0)) 
      Begin   

          Set @FinalCMG = @MRDxCMG + 1   
          Set @Branch = @BranchTemp   
      End   
      If left(@DiagMostResposible, 3) = 'Z53' and (@MCC <> '23' and len(@ProceduresAll) = 0)--modified 2006/02/27
      Begin 
      Set @FinalCMG = @MRDxCMG  
      Set @FinalMCCCode = @BranchTemp         
      End 
  
      If @DDisposition = '08' 
      Begin 
      set @FinalCMG = 996 
      End 
   
      If @FinalCMG is NULL   
      Begin   
          Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
          WHERE DiagProcCode in (' + @ProceduresAll + ') AND MCC = ''' + @MCC + ''' AND Priority < 3 ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
           @Branch output, @BranchCMG Output, @CMGProc Output
          Set @Partition = SUBSTRING(@Branch, 7, 2)   
          If isnull(@Branch, '0') = '0' and @MCC = '18X' and isnull(@Procedure1, '0') <> '0'   
          begin   
              Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
              WHERE DiagProcCode in (' + @ProceduresAll + ')  and translatefrom like ''appdh%'' ORDER BY SortOrder'   
              exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
           @Branch output, @BranchCMG Output, @CMGProc Output
              If isnull(@Branch, '0') <> '0'   
              begin   
                  Set @Branch = 'MC18XS02PR'   
                  Set @BranchCMG = '750'   
              end   
          end   
          Else If isnull(@Branch, '0') = '0' and @MCC = '17A' and isnull(@Procedure1, '0') <> '0'   
          begin   
              Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
              WHERE DiagProcCode in (' + @ProceduresAll + ') and translatefrom like ''appdh%'' ORDER BY SortOrder'   
              exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output',
           @Branch output, @BranchCMG Output, @CMGProc Output
   
              If isnull(@Branch, '0') <> '0'   
              begin   
              Set @Branch = Null 
              Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
              WHERE DiagProcCode in (' + @DiagMProcAll + ') AND MCCCode = ''MC17AS03MDL01'' ORDER BY SortOrder'   
              exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
                   @Branch output, @BranchCMG Output, @CMGProc Output
    
              If isnull(@Branch, '0') = '0'   
              begin   
                      Set @FinalMCCCode = 'MC17AS03PR'   
                      Set @FinalCMG = '728'   
              End 
              end   
          end   
          Else If isnull(@Branch, '0') = '0' and @MCC = '17B' and isnull(@Procedure1, '0') <> '0'   
          begin   
              Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
              WHERE DiagProcCode in (' + @ProceduresAll + ') and translatefrom like ''appdh%'' ORDER BY SortOrder'   
              exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
           @Branch output, @BranchCMG Output, @CMGProc Output
              If isnull(@Branch, '0') <> '0'   
              begin   
                  Set @FinalCMG = '734'   
                  Set @BranchCMG = '734'   
              end   
          end   
          Else if @MCC = '05A' and (@Partition = '06' or @Partition = '07') and SUBSTRING(@Branch, 5, 2) = 'AS'   
          Begin   
              SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003    
              WHERE DiagProcCode = (@DiagMostResposible) AND MCC = @MCC AND (Partition = @Partition) AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= 'AS' ORDER BY SortOrder   
              If @FinalCMG is null   
              Begin   
                  If @BranchCMG is null   
                      Set @FinalCMG = @MRDxCMG   
                  Else   
                      Set @FinalCMG = @BranchCMG   
              End   
          End   
          else If isnull(@Branch, '0') = '0'   
              Set @Branch = @BranchTemp   
          Set @Partition = SUBSTRING(@Branch, 7, 2)   
   if isnull(@FinalSubBranch, '') = ''
   Begin
              Set @SQL = 'SELECT Top 1 @FinalSubBranch = MedicalSurgical FROM CMG_Main2003   WHERE MCCCode = ''' + @Branch + ''''   
              exec sp_executesql @sql, N'@FinalSubBranch VarChar(1) output', @FinalSubBranch output
       if isnull(@FinalSubBranch, '') = ''
           Set @FinalSubBranch = '2'
   end
      End   
  
      If @MCC = '15X'   
      Begin   
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003              WHERE DiagProcCode in (' + @DiagMProcAll + ') AND (MCC = ''' + @MCC + ''')    
          AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
      End   
      Else If @MCC = '13X'   
      Begin   
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE DiagProcCode in (' + @DiagMProc + ') AND (MCC = ''' + @MCC + ''')    
          AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
      End   
      Else If @MCC = '24X'   
      Begin
         Declare @MCC24X as Varchar(10)
         If CHARINDEX(',', @DiagnosisAll) > 0
           set @MCC24X = left(@DiagnosisAll, CHARINDEX(',', @DiagnosisAll) - 1 )
	 Else if Len(@DiagnosisAll) > 0
           set @MCC24X = @DiagnosisAll

         Set @FinalCMG = Null
         If CHARINDEX(@MCC24X, @DiagTyped1 + ' ' + @DiagTyped2) > 0
         Begin
           Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002    
           WHERE DiagProcCode in (' + @MCC24X + ') AND MCC = ''' + @MCC + '''     
           AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
         End

         If @FinalCMG is Null and CHARINDEX(@MCC24X, @DiagTyped1 + ' ' + @DiagTyped2) > 0
		Set @FinalCMG = '868'
	 Else If CHARINDEX(@MCC24X, @DiagTyped1 + ' ' + @DiagTyped2) = 0
         Begin   
           Set @FinalCMG = '999'   
           Set @FinalMCCCode = 'MC99XM01MD'   
           Set @MCC = '99'   
         End   
      End
      Else If @FinalCMG is null and @BranchCMG is not null and @MCC not in ('05A', '08X', '10X') 
      Begin 
   Declare @ProcTemp as VarChar(15) 
          set @FinalCMGTemp = @BranchCMG   
     Set @ProcTemp = @CMGProc 
     Set @BranchTemp = @BranchCMG 
          Set @BranchCMG = Null   
   
          Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
          WHERE DiagProcCode in (' + @ProceduresAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
          AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', @Branch output, @BranchCMG Output, @CMGProc Output   
   If @BranchCMG is null 
           Begin 
              Set @FinalCMG = @FinalCMGTemp 
              Set @FinalMCCCode = @BranchTemp 
              Set @CMGProc = @ProcTemp 
           End 
   Else 
           Begin 
              Set @FinalCMG = @BranchCMG 
              Set @FinalMCCCode = @Branch 
           End 
      End 
      Else If @FinalCMG is null   
      Begin   
	If  @mcc = '23X' and @ProceduresAll = '''XXX'''
	   Set @SQL = ''
	Else
           Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003    
           WHERE DiagProcCode in (' + @DiagMProcAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
           AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
       End   
   
    If @MCC = '05A' and (@Partition Between '03' and '15') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02'   
      Begin   
          declare @Diag05 as VarChar(1000) 
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   
   
          set @Diag05 = replace(@DiagMProcAll, replace(replace(Replace(substring(@DiagTypeAll, charindex('|3', @DiagTypeAll) -5, 6), '|', ''), ' ', ''), '''', ''), 'xxx') 
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE (DiagProcCode) in (' + @Diag05 + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
          AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch +  ''' and SortOrder > 6 ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
      
          If @FinalCMG is Null   
              Set @FinalCMG = @FinalCMGTemp   
      End   
      --New 2002/09/20  
      Else If (@MCC = '05A' and (@Partition Between '19' and '21')) or (@MCC = '04X' and (@Partition Between '09' and '11')) or (@MCC = '01X' and (@Partition Between '09' and '11'))  
       or (@MCC = '06X' and (@Partition Between '19' and '21')) or (@MCC = '08X' and (@Partition Between '27' and '29')) or (@MCC = '11X' and (@Partition Between '17' and '19'))  
       or (@MCC = '05B' and (@Partition Between '12' and '14')) 
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 ORDER BY SortOrder'    
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
     
          If @FinalCMG is Null and isnull(@FinalCMGTemp, '0')  = '902' 
   	Begin 
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003    
  
             WHERE DiagProcCode in (' + @ProceduresAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
             AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
	   End 
	   Else If @FinalCMG is Null 
              Set @FinalCMG = @FinalCMGTemp    
      End    
      Else If @MCC = '05A' and (@Partition Between '03' and '15') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) <> 'L02'   
          Set @FinalCMG = Null   
      Else If (@MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02' AND (@LOS >= 4)) or    
          ((@MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02') and (@DDisposition in ('07', '06') or @IsAcuteTo = 1 or @IsAcutefrom = 1))   
      Begin   
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003    
          WHERE (DiagProcCode) in (' + @DiagMProcAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
          AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' and SortOrder > 2 ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
          If @FinalCMG is Null   
              Set @FinalCMG = @FinalCMGTemp   
          else if @Partition = '01'   
              Set @FinalCMG = @FinalCMG - 4              else   
              Set @FinalCMG = @FinalCMG - 2   
      end   
      Else If @MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02' And @LOS < 4   
          Set @FinalCMG = '218'   
      Else if @MCC = '05A' and (@Partition = '03' or @Partition = '04' or @Partition = '05')   
      Begin   
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
             
          If @FinalCMG is Null   
              Set @FinalCMG = @FinalCMGTemp   
          If @FinalCMG in ('176', '178', '181')   
              Set @FinalCMG = '183'   
          Else If @FinalCMG in ('177', '179', '182')   
          Begin   
              set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
              AND MCCCode = ''MC05AS' + @Partition + 'NPL02'''   
              exec sp_executesql @sql, N'@count int output', @Count output   
              If isnull(@Count, 0) > 0   
                  Set @FinalCMG = @FinalCMG - 1   
          End   
      end   
      Else if @MCC = '05A' and @Partition = '10' and (@FinalCMG = '181' or @FinalCMG = '182')   
      Begin  
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   
	If @FinalCMGTemp = '182'
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND sortorder = 2 AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
	else
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND sortorder = 1 AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   

          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
             
          If @FinalCMG is Null and @FinalCMGTemp = '182'
              Set @FinalCMG = '182' 
          else If @FinalCMG is Null and @FinalCMGTemp = '181'
              Set @FinalCMG = '194'   
      End   
      --New 2002/09/19  
      Else If @MCC = '06X' and (@Partition = '12')  
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = @FinalCMGTemp    
      End    
      --New 2002/09/24  
      Else If ((@MCC = '08X' and (@Partition in ('04', '05', '07'))) or (@MCC = '21X' and (@Partition in ('08', '10'))) or 
           (@MCC = '23X' and (@Partition in ('02', '04')))) and @FinalCMG in ('350', '354')
      Begin    
          set @FinalCMG = NULL  
          Declare @MC08Count as int 
	  set @MC08Count = 0

	Declare @TempProcString as varchar(1000)
	Declare @TempProcString2 as varchar(1000)
	Declare @MultiReplaceCountTemp as int
	
	set @TempProcString = @ProceduresAll
	
	While len(@TempProcString) > 1
	Begin
		set @MultiReplaceCountTemp = 0
		if CHARINDEX ( ',' , @TempProcString, CHARINDEX(', ',@TempProcString)+1  ) > 1
			set @TempProcString2 = substring(@TempProcString,0, CHARINDEX ( ',' , @TempProcString, CHARINDEX(', ',@TempProcString  )+1))
		else
			set @TempProcString2 = @TempProcString

		--Ticket 10639
		If @MCC = '21X'
	          set @SQL = 'SELECT @MultiReplaceCountTemp = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @TempProcString2 + '))    
	          AND MCCCode = ''MC' + left(@mcc, 2) + 'XS' + @Partition + 'PRL03''' 
		Else
	          set @SQL = 'SELECT @MultiReplaceCountTemp = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @TempProcString2 + '))    
	          AND MCCCode = ''MC' + left(@mcc, 2) + 'XS' + @Partition + 'PRL01''' 

	          exec sp_executesql @sql, N'@MultiReplaceCountTemp int output', @MultiReplaceCountTemp output
  		if @MultiReplaceCountTemp > 0
			set @MC08Count = @MC08Count + 1
		set @TempProcString = right(@TempProcString, len(@TempProcString)-len(@TempProcString2))
		if len(@TempProcString) > 4
			set @TempProcString = right(@TempProcString, len(@TempProcString) - 2)
		else
			Set @TempProcString = ''
	End
          If isnull(@MC08Count, 0) > 1 and len(@ProceduresAll) > 30 
             Set @FinalCMG = 350    
          Else  
          Begin  
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
             WHERE ((DiagProcCode) in (' + @DiagMProcAll + ')) 
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SortOrder > 1 ORDER BY SortOrder'    
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          End  
   
          If @FinalCMG is Null    
     Begin
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
             WHERE ((DiagProcCode) in (' + @DiagMProcAll + ')) 
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 2 ORDER BY SortOrder'    
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
     End
      End    
      Else If @MCC = '08X' and (@Partition between '10' and '25') and SUBSTRING(@Branch, 6, 1) = 'S' 
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = @FinalCMGTemp    
      End    
      --New 2002/09/19  
      Else If @MCC = '09X'  
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = @FinalCMGTemp    

	  If @FinalCMG = '438'
	  Begin
	          set @FinalCMGTemp = @FinalCMG    
	          Set @FinalCMG = Null    
	
	          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
	          WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
	           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
	          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = '437'    
	  End
	  --Ticket 10302
	  If @FinalCMG = '427'
	  Begin
	          set @FinalCMGTemp = @FinalCMG    
	          Set @FinalCMG = Null    
	
	          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
	          WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
	           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
	          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = '425'    
	  End
      End    
      Else If @MCC = '10X' and @Partition = '01' and SUBSTRING(@FinalMCCCode, 5, 2) = 'XS' 
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = @FinalCMGTemp    
      End    
      --New 2002/09/25  
      Else If @MCC = '19X' and (@FinalCMG not in ('771', '778', '767')) and @FinalCMG is not null 
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Declare @LenDiag as int 
          Declare @Diag19X as NVarChar(200) 
          set @LenDiag = len(@DiagMProcAll) - len(@DiagMostResposible) - 4 
          If @LenDiag < 0 
          Begin 
             Set @LenDiag = 0 
             Set @Diag19X = '''''' 
          End 
          Else 
             Set @Diag19X = right(@DiagMProcAll, @LenDiag) 
          set @Diag19X = replace(@Diag19X, replace(replace(Replace(substring(@DiagTypeAll, charindex('|3', @DiagTypeAll) -5, 6), '|', ''), ' ', ''), '''', ''), 'xxx') 
     If right(@Diag19X, 1) = ',' 
           set @Diag19X = left(@Diag19X, len(@Diag19X)-1)
     If right(@Diag19X, 2) = ', ' 
           set @Diag19X = left(@Diag19X, len(@Diag19X)-2)

     If right(@Diag19X, 1) <> '''' 
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
             WHERE ((DiagProcCode) in (' + @Diag19X + '''))    
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
     Else
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
             WHERE ((DiagProcCode) in (' + @Diag19X + '))    
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    

          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
          Begin  
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
             WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
              AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 1 ORDER BY SortOrder'    
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          End  
      End   
    Else If @MCC = '11X' and (@Partition = '01') and right(@FinalMCCCode, 3) = 'L01' 
      Begin	
	If @LOS > 2 or @DDisposition in ('06','07') or @isAcuteTo = 1 or @isAcuteFrom = 1
		Set @FinalCMG = '520'	
	Else if @LOS < 3 AND @isAcuteTo = 0 and @isAcuteFrom = 0
		Set @FinalCMG = '999'	
      End  
      Else if @MCC = '13X' and @FinalMCCCode like 'MC13XS04%'   
      Begin   
          If @FinalMCCCode = 'MC13XS04PRL02'   
          Begin   
              set @FinalCMGTemp = @FinalCMG   
              Set @FinalCMG = Null   
              set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProc + '))    
              AND MCCCode in (''MC13XS04MDL03'', ''MC13XS04PRL04'') ORDER BY SortOrder'   
              exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
      
              If @FinalCMG is Null   
                  Set @FinalCMG = '579'   
          End   
          Else If @FinalMCCCode = 'MC13XS04MDL01'   
          Begin   
              set @FinalCMGTemp = @FinalCMG   
              Set @FinalCMG = Null   
              set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProc + '))    
              AND MCCCode = ''MC13XS04PRL02'''   
              exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
   
              If @FinalCMG is Null   
                  Set @FinalCMG = @FinalCMGTemp   
          End   
          If @FinalMCCCode = 'MC13XS04MDL03'   
          Begin   
              set @FinalCMGTemp = @FinalCMG   
              Set @FinalCMG = Null   
              set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProc + '))    
              AND MCCCode = ''MC13XS04PRL04'''   
              exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
                 
              If @FinalCMG is Null   
                  Set @FinalCMG = @FinalCMGTemp   
          End   
          Else If @FinalMCCCode = 'MC13XS04PRL04'   
              Set @FinalCMG = '579'   
      end   
      Else If (@MCC = '14X' and (@Partition = '05')) And (@LOS >= 3 or @IsAcuteTo = 1 or @IsAcuteFrom = 1) 
          Set @FinalCMG = '599'   
      Else If @MCC = '14X' and (@Partition = '01') and @FinalSubBranch = 1 and ((@FinalCMG = '612' or (@FinalCMG is null and @MRDxCMG = '612')))
      Begin   
          Set @FinalCMG = Null   
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
          SortOrder = 1 ORDER BY SortOrder' 
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
          If @FinalCMG is Null   
              Set @FinalCMG = 600   
      end   
      Else If @MCC = '15X' and (@Partition Between '03' and '06') and right(@FinalMCCCode, 3) = 'L01'  And @DDisposition in ('04', '05') And @LOS < 6   
          Set @FinalCMG = 998   
--Added on Ticket 9161
      Else If @MCC= '15X' and (@Partition Between '03' and '06') and right(@FinalMCCCode, 3) = 'L01' and (@DDisposition in ('07', '06') or @IsAcuteTo = 1 or @IsAcutefrom = 1 or @LOS > 6) 
      Begin

	  If @Partition = '03'
          	Set @FinalCMG = 627  
	  If @Partition = '04'
          	Set @FinalCMG = 630  
	  If @Partition = '05'
          	Set @FinalCMG = 636  
	  If @Partition = '06'
          	Set @FinalCMG = 643  
      End
      Else If @MCC = '15X' and (@Partition in ('06', '05')) and ((@FinalCMG = '646' or (@FinalCMG is null and @MRDxCMG = '646')) or 
      (@FinalCMG = '647' or (@FinalCMG is null and @MRDxCMG = '647')) or (@FinalCMG = '648' or (@FinalCMG is null and @MRDxCMG = '648'))
      or (@FinalCMG = '639' or (@FinalCMG is null and @MRDxCMG = '639'))or (@FinalCMG = '640' or (@FinalCMG is null and @MRDxCMG = '640')))
      Begin   
          Set @FinalCMG = Null   
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE (((DiagProcCode) in (' + @DiagMProcAll  + ')) or
	  ((DiagProcCode) in (''''' + @DiagTyped0 + @DiagTyped3 + ')) and isnull(translatefrom, '''') = '''')
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
          SortOrder = 4 ORDER BY SortOrder' 
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
          If @FinalCMG is Null   
          Begin
           set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
           SortOrder > 4 ORDER BY SortOrder' 
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
           If @FinalCMG is Null and @MRDxCMG in ('646', '647', '648')
               Set @FinalCMG = 648   
           Else If @FinalCMG is Null and @MRDxCMG in ('639', '640')
               Set @FinalCMG = 640   
      	  End
      end 
      Else If @MCC = '14X' and (@Partition = '02')-- and right(@FinalMCCCode, 3) = 'L01'   
      Begin   
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
          SortOrder = 1 ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
             
          If @FinalCMG is Null   
              Set @FinalCMG = @FinalCMGTemp   
          Else  
          Begin  
             set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
             SortOrder > 1 ORDER BY SortOrder'   
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
  
             If @FinalCMG is Null   
                 Set @FinalCMG = @FinalCMGTemp   
             If @FinalCMG = '601'   
                 Set @FinalCMG = '603'   
             Else If @FinalCMG in ('602', '604')
             Begin   
                 set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + @DiagTyped3 + '))    
                 AND MCCCode = ''MC14XS02MOL03'''   
                 exec sp_executesql @sql, N'@count int output', @Count output   
                 If isnull(@Count, 0) > 0   
                     Set @FinalCMG = @FinalCMG - 1   
             End   
      End  
      end   
      Else If @MCC = '14X' and (@Partition = '02') and right(@FinalMCCCode, 3) <> 'L01' and SUBSTRING(@FinalMCCCode, 5, 2) <>  'XM'   
          Set @FinalCMG = 999   
     Else If @MCC = '14X' and (@FinalCMG Between '608' and '611' or (@FinalCMG is null and @MRDxCMG Between '608' and '611'))--(@FinalCMG = '608' or @FinalCMG = '609')   
     Begin   
         If @FinalCMG = '608'   
             Set @FinalCMG = '610'   
         Else 
         Begin   
             set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + @DiagTyped3 +  '))    
             AND MCCCode = ''MC14XM01MOL04'''  
             exec sp_executesql @sql, N'@count int output', @Count output  
             If isnull(@Count, 0) > 0 and @FinalCMG is not null
                 Set @FinalCMG = @FinalCMG - 1   
             Else If isnull(@Count, 0) > 0 and @FinalCMG is null
                 Set @FinalCMG = @MRDxCMG - 1   
         End   
     End   
      Else If @MCC = '14X' and (@FinalCMG in ('620', '621'))   
      Begin   
          If @FinalCMG = '621'   
          Begin   
              set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagnosisAll + '))    
              AND MCCCode = ''MC14XM06PRL10'''   
              exec sp_executesql @sql, N'@count int output', @Count output   
              If isnull(@Count, 0) > 0   
                  Set @FinalCMG = @FinalCMG - 1   
          End   
      end   
      Else if @MCC = '21X' and (@Partition in ('05', '06'))   
      Begin   
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   

          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   

          If @FinalCMG is Null 
              Set @FinalCMG = @FinalCMGTemp  
          If @FinalCMG in ('176', '178', '181')   
              Set @FinalCMG = '183'   
          Else If @FinalCMG in ('177', '179', '182')   
          Begin  
              set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
              AND MCCCode = ''MC21XS' + @Partition + 'NPL02'''   
              exec sp_executesql @sql, N'@count int output', @Count output   
              If isnull(@Count, 0) > 0   
                  Set @FinalCMG = @FinalCMG - 1   
          End   
      end   
      Else if @MCC = '22X' and (@Partition in ('01', '02')) --Ticket 9698
      Begin   
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   

          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   

          If @FinalCMG is Null 
              Set @FinalCMG = @FinalCMGTemp  
      end 
      Else If @MCC = '25X' and SUBSTRING(@Branch, 6, 1) = 'S' and SUBSTRING(@Branch, 7, 2) = '05' and @FinalCMG in ('351', '350') 
      Begin
   	Declare @MC25Proc as VarChar(15) 
  	Declare @MC25Count as int   
          If @FinalCMG = 350   
   	  Begin 
              set @SQL = 'SELECT @MC25Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @ProceduresAll + '))    
              AND MCCCode = ''MC25XS05PRL03'''   
              exec sp_executesql @sql, N'@MC25Count int output', @MC25Count output   
           If @MC25Count = 1 
           Begin
                   set @SQL = 'SELECT  @MC25Proc = diagproccode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @ProceduresAll + '))    
                   AND MCCCode = ''MC25XS05PRL03'''   
                   exec sp_executesql @sql, N'@MC25Proc varchar(15) output', @MC25Proc output                   
  
                  If len(replace(@ProceduresAll, '''' + @MC25Proc + '''', '')) < (len(@ProceduresAll) - len(@MC25Proc) - 3)
                           Set @MC25Count = 2 
           End
   End 
   
          If isnull(@MC25Count, 0) < 2   
              Set @FinalCMG = 351   
      End   

      if len(@FinalMCCCode) > 10   
          Set @Branch = left(isnull(@FinalMCCCode, ''), 10)   

      If @FinalCMG is null   
      Begin   
          If @BranchCMG is null   
              Set @FinalCMG = @MRDxCMG   
          Else   
              Set @FinalCMG = @BranchCMG   
          If @FinalCMG is null 
               Set @FinalCMG = '999'   
      End   

      --Ticket 9330
      If @MCC is null
	set @MCC = '99'

      if len(@FinalMCCCode) > 10   
          Set @Branch = left(isnull(@FinalMCCCode, ''), 10)  

      Declare @MedSurgInd as VarChar(1) 
      Declare @MedSurgNon as VarChar(1) 
      SELECT @MedSurgNon = cmgmcctype, @MedSurg = cmgmcctype, @MedSurgInd = RIWInd FROM CMG_Etc_2003T WHERE (cmgcode = @FinalCMG) and (ciagegroup = @AgeGroup)    

      Set @PlexA = 0   
      Set @PlexB = 0   
      Set @PlexC = 0   
      Set @PlexD = 0   
      Set @PlexP = 0   
      Set @PlexCMCC = 0   
      If exists (SELECT * FROM CMG_Etc_2003T WHERE ((cmgcode = @FinalCMG) AND (cicpxlvl = 9) and (ciagegroup = @AgeGroup)) or @MedSurg = '9') 
          set @Complexity = 9   
      Set @DiagTypeAll = replace(@DiagTypeAll, @DiagMostResposible + '|', 'XXXXX|')   

      if @Plx4 = 'Y' and isnull(@Complexity, '') <> '9'
	set @Complexity = 4  
      If isnull(@AbstractID, 0) > 0 and (CHARINDEX ('1GZ31CAND', @ProceduresAll ) > 0 or CHARINDEX ('1GZ31CRND', @ProceduresAll ) > 0)
   and @Complexity is null
      Begin   
	   if exists (SELECT dbo.AB_Intervention.AbstractID FROM dbo.AB_Intervention LEFT OUTER JOIN
           dbo.ICD_ProcFile10 ON dbo.AB_Intervention.IntervCode = dbo.ICD_ProcFile10.Code LEFT OUTER JOIN
           dbo.LU_IntervAttExtent ON dbo.AB_Intervention.IntervAttribExtent = dbo.LU_IntervAttExtent.Code
           WHERE (dbo.LU_IntervAttExtent.CIHIValue IN ('EX')) AND (dbo.ICD_ProcFile10.CIHIValue  in ('1GZ31CAND', '1GZ31CRND')) AND (dbo.AB_Intervention.AbstractID = @AbstractID))
	   set @Complexity = 4  
      End

     --If there are duplicate diagnosis with the same type, take type 1
     Declare @DupDiagComplex as Varchar(20)
     set @SQL = 'SELECT top 1 @DupDiagComplex = diagnosis FROM CMG_Plx2002   
         WHERE DiagTypeCombine in (' + @DiagTypeAll + ')
 	AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''') 
 	And Diagnosis not in (SELECT DiagnosisEx FROM dbo.CMG_PlxException2001 WHERE (MCCEx = LEFT(''' + @MCC + ''',2)) AND (CMGEx = ''' + @FinalCMG + '''))
 	group by diagnosis having Count(diagnosis) > 1'   
     exec sp_executesql @sql, N'@DupDiagComplex VarChar(20) output', @DupDiagComplex output 

     If isnull(@DupDiagComplex, '') <> ''
    	Set @DiagTypeAll = replace(@DiagTypeAll, @DupDiagComplex + '|2', 'XXXXX|2')   

  
           Create TABLE #PlxTemp (PlCount int, Plex varchar(1))
  --Plex Levels
   set @SQL = 'SELECT count(*) as PlCount, substring(Plexity, cast(LEFT(''' + @MCC + ''',2) as int), 1) as Plex FROM CMG_Plx2003   
          WHERE DiagTypeCombine in (' + @DiagTypeAll + ')
   AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''') 
   And Diagnosis not in (SELECT DiagnosisEx FROM dbo.CMG_PlxException2003 WHERE (MCCEx = LEFT(''' + @MCC + ''',2)) AND (CMGEx = ''' + @FinalCMG + '''))
   group by substring(Plexity, cast(LEFT(''' + @MCC + ''',2) as int), 1)'   
   Insert into #PlxTemp Exec (@SQL)
  
      if @Complexity is null and @@Rowcount > 0   
      Begin  
  --Level C Not Home Plex
   set @SQL = 'SELECT @PlexCMCC = count(*) FROM CMG_Plx2003   
        WHERE DiagTypeCombine in (' + @DiagTypeAll + ') and substring(Plexity, cast(LEFT(''' + @MCC + ''',2) as int), 1) = ''C'' 
   and HomeMCC <> LEFT(''' + @MCC + ''',2)
   AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''') 
   And Diagnosis not in (SELECT DiagnosisEx FROM dbo.CMG_PlxException2003 WHERE (MCCEx = LEFT(''' + @MCC + ''',2)) AND (CMGEx = ''' + @FinalCMG + '''))'   
   exec sp_executesql @sql, N'@PlexCMCC VarChar(1) output', @PlexCMCC output   
   Set @PlexA = isnull((select PlCount from #PlxTemp where Plex = 'A'), 0)
   Set @PlexB = isnull((select PlCount from #PlxTemp where Plex = 'B'), 0)
   Set @PlexC = isnull((select PlCount from #PlxTemp where Plex = 'C'), 0)
   Set @PlexD = isnull((select PlCount from #PlxTemp where Plex = 'D'), 0)
   Set @PlexP = isnull((select PlCount from #PlxTemp where Plex = 'P'), 0)
   If @PlexCMCC > 1
           Set @PlexCMCC = 1
  
          If @PlexA > 0 or @PlexB > 1 or (@PlexB = 1 and @PlexC > 0 and @PlexCMCC = 1)   
              Set @Complexity = 4   
          Else If @PlexB > 0 or (@PlexC > 1 and @PlexCMCC = 1) or (@PlexC > 10 and @PlexCMCC = 0)   
              Set @Complexity = 3   
          Else If @PlexD > 0 or @PlexP > 0 or (@PlexC = 1 and @PlexCMCC = 1)    
              or (@PlexC > 0 and @PlexC < 11 and @PlexCMCC = 0)   
              Set @Complexity = 2   
          Else   
              Set @Complexity = 1   
      End   

      If isnull(@Complexity, '') = ''   
          Set @Complexity = 1   
      
      Set @MCC = Replace(@MCC, 'X', '')   
      Set @ComplexityLevel = @Complexity   
      SELECT Top 1 @CmgDesc = cmgdesc, @CmgTrim = ciagtrim, @CmgELOS = ciagelos, @CmgPDRA = ciagpdra, @CmgPDWGT = ciagpdwgt, @CmgRIW = ciagriw   
      FROM dbo.CMG_Etc_2003T WHERE (cmgcode = @FinalCMG) AND (cicpxlvl = @ComplexityLevel) AND (ciagegroup = @AgeGroup) --AND (cmgmcctype = @MedSurg)  
  --print @CmgDesc 
  --print @CmgTrim 
  --print @CmgELOS 
  --print @CmgPDRA 
  
   --New 2002/09/30 
      If @MedSurg = 9 
      Set @MedSurg = 1   
      If @FinalCMG in ('910', '912', '998', '999') and @LOS < cast(@CMGELOS as decimal(7,4))   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      Else If @FinalCMG in ('910', '912', '998', '999') and @LOS >= cast(@CMGELOS as decimal(7,4))   
          Set @CMGRIW = @CmgRIW
      else if @DDisposition = '07' and @LOS <= @CMGTrim and @LOS <= 10   
      Begin   
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer    
              WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr is null and dxyear = 2003)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      else if @DDisposition = '07' and @LOS <= @CMGTrim and @LOS > 10   
      Begin 
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
              WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr is null and dxyear = 2003)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      Else If @DDisposition = '06' and @LOS <= cast(@CMGELOS as decimal(7,4))   
          Set @CMGRIW = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,4))) as decimal(7,4))   
      Else If @DDisposition = '06' and @LOS > cast(@CMGELOS as decimal(7,4)) and @LOS <= @CMGTrim   
          Set @CMGRIW = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@CmgELOS as decimal(7,4))) as decimal(7,4))   
      Else If @IsAcuteTo = 1 and @LOS <= 10 and @LOS <= @CMGTrim   
      Begin   
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
              WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='O' and dxyear = 2003)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      Else If @IsAcuteTo = 1 and @LOS > 10 and @LOS <= @CMGTrim   
      Begin   
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
              WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='O' and dxyear = 2003)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      Else If @IsAcuteFrom = 1 and @LOS <= 10 and @LOS <= @CMGTrim   
      Begin   
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
              WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='I' and dxyear = 2003)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      Else If @IsAcuteFrom = 1 and @LOS > 10 and @LOS <= @CMGTrim   
      Begin   
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
              WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='I' and dxyear = 2003)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      Else If @LOS > @CMGTrim   
          Set @CMGRIW = cast(cast(@CMGRIW as decimal(7,4)) + (cast(@CmgPDRA as decimal(7,4)) * cast((cast(@LOS as decimal(7,2)) - cast(@CmgELOS as decimal(7,4))) as decimal(9,4))) as decimal(9,4))   

      Declare @CMGNon as int
      Select @CMGNon = CMGNonValue from CMG_NonBool where CMGNonYear = 2004
      if @CmgRIW is not null and isnull(@CMGNon, 0) = 0
      Begin  
          Select @RIW$ = CostPerRiw from H_InstitutionProfile where code = @InstNumber   
          if isnull(@RIW$, '0') = '0' or @RIW$ = ''   
              set @RIW$ = '0'   
          Set @CMGRIW$ = cast(@CmgRIW as decimal(7,4)) * cast(@RIW$ as decimal(6,2))   
          if @LOS - @CMGTrim > 0   
          Begin   
              Set @CMGMOH = left(@CMGRIW + (((@LOS - @CMGTrim) * cast(@CmgPDWGT as Decimal(7,4))) + (((cast(@CMGTrim as int) - cast(@CMGELOS as decimal(6,2))) * cast(@CmgPDWGT as Decimal(7,4)))) * .2), 10)   
              Set @CMGMOH$ = cast(@CmgMOH as decimal(9,4)) * cast(@RIW$ as decimal(6,2))   
          end   
          Else   
          Begin   
              Set @CMGMOH = @CMGRIW   
              Set @CMGMOH$ = @CMGRIW$   
          end   
          Set @CMGMOH = cast(@CMGMOH as decimal(8,4))   
          Set @CMGRIW$ = cast(@CMGRIW$ as decimal(10,2))   
          Set @CMGMOH$ = cast(@CMGMOH$ as decimal(10,2))   
      End
--If they have rights to non complex grouper do this
     else if @CmgRIW is not null and exists(select code from H_HospitalProfile where code + @CMGNon = 33101) --PR - 00945
     Begin
		declare @IsAcuteFromNon as bit
		declare @IsAcuteToNon as bit
		set @IsAcuteFromNon = @IsAcuteFrom
		Set @IsAcuteToNon = @IsAcuteTo
		if @IsAcuteFromNon = 0
		Begin
			If exists(select code FROM LU_Institution_10 WHERE code = @InstFrom and CIHIValue in ('53240', '53310', '53459', '53781', '53913'))
				set @IsAcuteFromNon = 1
		End
		If @IsAcuteToNon = 0
		Begin
			If exists(select code FROM LU_Institution_10 WHERE code = @InstTo and CIHIValue in ('53240', '53310', '53459', '53781', '53913'))
				set @IsAcuteToNon = 1
		End

          Select @RIW$ = CostPerRiw from H_InstitutionProfile where code = @InstNumber   
          if isnull(@RIW$, '0') = '0' or @RIW$ = ''   
              set @RIW$ = '0'   
          Set @CMGRIW$ = cast(@CmgRIW as decimal(7,4)) * cast(@RIW$ as decimal(6,2))   
	     Declare @MedSurgIndHold as VarChar(1)
	     If @Complexity = 9
	     Begin
		Set @MedSurgIndHold = @MedSurgInd
		Set @MedSurgInd = 9
	     End
	     Declare @CmgNonELOS as VarChar(10)   
	     Declare @CmgNonTrim as VarChar(10)

	     SELECT Top 1 @CmgNonTrim = ciagtrim, @CmgNonELOS = ciagelos, @CmgPDRA = ciagpdra, @CmgPDWGT = ciagpdwgt, @CMGMOH = ciagriw   
	     FROM dbo.CMG_ETC_2004_Non WHERE (cmgcode = @FinalCMG) AND (ciagegroup = @AgeGroup) and (ICDType = 'T') --AND (cmgmcctype = @MedSurg)   

	     If @MedSurg = 9 
	 	Set @MedSurg = 1   
	     If @FinalCMG in ('910', '912', '998', '999') and @LOS < cast(@CmgNonELOS as decimal(7,4))   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     else if @DDisposition = '07' and @LOS <= @CmgNonTrim and @LOS <= 10   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non    
	             WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and isnull(cmgxfr, '') = '' and dxyear = 2004)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))
    	     End   
	     else if @DDisposition = '07' and @LOS <= @CmgNonTrim and @LOS > 10   
	     Begin 
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non  
	             WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and isnull(cmgxfr, '') = '' and dxyear = 2004)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @DDisposition = '06' and @LOS <= cast(@CmgNonELOS as decimal(7,4))   
	         Set @CMGMOH = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,4))) as decimal(7,4))   
	     Else If @DDisposition = '06' and @LOS > cast(@CmgNonELOS as decimal(7,4)) and @LOS <= @CmgNonTrim   
	         Set @CMGMOH = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@CmgNonELOS as decimal(7,4))) as decimal(7,4))   
	     Else If @IsAcuteFromNon = 1 and @LOS <= 10 and @LOS <= @CmgNonTrim   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
	             WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and cmgxfr ='I' and dxyear = 2004)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @IsAcuteFromNon = 1 and @LOS > 10 and @LOS <= @CmgNonTrim   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
	             WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and cmgxfr ='I' and dxyear = 2004)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @IsAcuteToNon = 1 and @LOS <= 10 and @LOS <= @CmgNonTrim   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
	             WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and cmgxfr ='O' and dxyear = 2004)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @IsAcuteToNon = 1 and @LOS > 10 and @LOS <= @CmgNonTrim   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
	             WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and cmgxfr ='O' and dxyear = 2004)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @LOS > @CmgNonTrim 
	         Set @CMGMOH = cast(cast(@CMGMOH as decimal(7,4)) + (cast(@CmgPDRA as decimal(7,4)) * cast((cast(@LOS as decimal(7,2)) - cast(@CmgNonELOS as decimal(7,4))) as decimal(9,4))) as decimal(9,4))   
	     
	     If @MedSurgInd = 9
		Set @MedSurgInd = @MedSurgIndHold

	      If @DDisposition = '07'   
	          Set @NonAcuteQuartile = 'D'   
	      Else If @DDisposition = '06'   
	          Set @NonAcuteQuartile = 'S'   
	      Else If @IsAcuteFromNon = 1 or @IsAcuteToNon = 1 --or @DDisposition = '01' ticket 5711  
	          Set @NonAcuteQuartile = 'T'   
	      Else If cast(@LOS as varchar(10)) > @CmgNonTrim   
	          Set @NonAcuteQuartile = 'O'   
	      Else If @LOS > cast(@CmgNonELOS as decimal(7,4))   
	          Set @NonAcuteQuartile = 'B'   
	      Else   
	          Set @NonAcuteQuartile = 'I'  
          Set @CMGMOH$ = cast(@CmgMOH as decimal(9,4)) * cast(@RIW$ as decimal(6,2))   
          Set @CMGMOH = cast(@CMGMOH as decimal(8,4))   
          Set @CMGRIW$ = cast(@CMGRIW$ as decimal(10,2))   
          Set @CMGMOH$ = cast(@CMGMOH$ as decimal(10,2))   
      End   
     
      If @DDisposition = '07'   
          Set @AcuteQuartile = 'D'   
      Else If @DDisposition = '06'   
          Set @AcuteQuartile = 'S'   
      Else If @IsAcuteFrom = 1 or @IsAcuteTo = 1 --or @DDisposition = '01' ticket 5711  
          Set @AcuteQuartile = 'T'   
      Else If @LOS > @CMGTrim   
          Set @AcuteQuartile = 'O'   
      Else If @LOS > cast(@CMGELOS as decimal(7,4))   
          Set @AcuteQuartile = 'B'   
      Else   
          Set @AcuteQuartile = 'I'   
    
      If @MedSurgInd = '2' 
   Set @MedOrSurg = 'M' 
      Else 
   Set @MedOrSurg = 'S' 

	If isnull(@AbstractID, 0) > 0 and @Occurance = 1
	Begin
		Declare @AUCmg as Varchar(3)
		Declare @AUCplx as VarChar(1)
		Declare @AUMcc as Varchar(3)
		Declare @AUQuartile as VarChar(1)
		Declare @AURiw as VarChar(20)
		Declare @AUAid as Int
		--EN00085
		Declare @GrouperChange as VarChar(1)
		Set @GrouperChange = 'N'
		SELECT @AUAid = Abstractid, @AUCmg = CMG, @AUCplx = Complexity, @AUMcc = MCC, @AUQuartile = AcuteQuartile, @AURiw = CMG_RIW
		FROM AB_CMG where AbstractID = @AbstractID and OccurrenceNumber = 1 and CMG_Year = 2004
		If isnull(@AUAid, 0) > 0
		Begin
			If @AUCmg <> @FinalCMG
			Begin
				Insert into AB_GrouperAudit Values (@AbstractID, 2004, 'CMG', @AUCmg, @FinalCMG, GetDate())
				Set @GrouperChange = 'Y'
			End
			If @AUCplx <> @ComplexityLevel
				Insert into AB_GrouperAudit Values (@AbstractID, 2004, 'Complexity', @AUCplx, @ComplexityLevel, GetDate())
			If left(@AUMcc, 2) <> Left(@MCC, 2)
				Insert into AB_GrouperAudit Values (@AbstractID, 2004, 'MCC', @AUMcc, Left(@MCC, 3), GetDate())
			If @AUQuartile <> @AcuteQuartile
				Insert into AB_GrouperAudit Values (@AbstractID, 2004, 'Quartile', @AUQuartile, @AcuteQuartile, GetDate())
			If @AURiw <> @CmgRIW
			Begin
				Insert into AB_GrouperAudit Values (@AbstractID, 2004, 'RIW', @AURiw, @CmgRIW, GetDate())
				Set @GrouperChange = 'Y'
			End
		End
		If @GrouperChange = 'Y' and @FlagRecord = 'Y'
			Update AB_Abstract set iscorrected = 2 where abstractid = @AbstractID and issubmited = 1 and isdeleted = 2 and iscorrected = 1
				and batchyear = 2004
	End
      
      If isnull(@AbstractID, 0) > 0 
      Begin   
          If @Occurance = 1
	set @ExpiryDate = null
          Delete ab_CMG where Abstractid = @Abstractid and CMG_Year = 2004 and OccurrenceNumber = @Occurance   
          If IsNull(@FinalCMG, '') <> '' and isnull(@DiagMostResposible, '') <> ''
          Begin   
              Set @DiagMostResposible = (select top 1 code from ICD_DiagFile10 where cihivalue = @DiagMostResposible)   
              INSERT INTO [dbo].[AB_CMG] ([AbstractID], [OccurrenceNumber], [CMG_Year], [ICD_Type], [Diagnosis_Code],   
              [Diagnosis_Type], [CMG], [Complexity], [MCC], [AcuteQuartile], [CMG_RIW], [MOH_RIW],   
              [RIW_Dollar], [MOH_Dollar], [CMG_ELOS], [CMG_Trim], [CMG_Description], [MCC_Surg], MOHQuartile, ExpiryDate) VALUES    
              (@AbstractID, @Occurance, 2004, 'T', @DiagMostResposible, 11, @FinalCMG, @ComplexityLevel, rtrim(Left(@MCC, 3)), @AcuteQuartile, @CmgRIW, @CmgMOH,    
              cast(@CmgRIW$ as money), cast(@CmgMOH$ as money), @CmgELOS, @CMGTrim, @CMGDesc, @MedOrSurg,@NonAcuteQuartile, @ExpiryDate)   
              Update ab_CMG set CMGModelType = ModelType, CMGTenthPercent = TenthPercent, CMGTwentyFifthPercent = TwentyFifthPercent, CMGFiftiethPercent = FiftiethPercent
              FROM dbo.AB_CMG LEFT OUTER JOIN
              dbo.CMG_Etc_2003T ON dbo.AB_CMG.Complexity = dbo.CMG_Etc_2003T.cicpxlvl AND dbo.AB_CMG.CMG = dbo.CMG_Etc_2003T.cmgcode
              WHERE abstractid = @AbstractID and CMG_Year = 2004 and ciagegroup = @AgeGroup
          End   
      
      End   
      set nocount off    

  --    print datediff(ms, @SDate, getdate())   
      Return 0





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE                          PROCEDURE [P_CMG2005_T]   
      @Age as Int,   
      @AgeCode as int, 
      @LOS as int,   
      @AcuteLOS as int,   
      @ICDType as VarChar(2),   
      @Gender as VarChar(1),   
      @Weight as int,   
      @DDisposition as VarChar(2),   
      @InstNumber as int,   
      @InstTo as int,   
      @InstFrom as int,   
      @DiagMostResposible as VarChar(10),   
      @DiagnosisAll as VarChar(500),   
      @DiagTypeAll as VarChar(500),   
      @DiagTyped1 as VarChar(500),   
      @DiagTyped2 as VarChar(500),   
      @DiagTyped0 as VarChar(500),   
      @DiagTyped3 as VarChar(500),   
      @ProceduresAll as VarChar(1000),   
      @Procedure1 as VarChar(10),   
      @FinalCMG as VarChar(3) output,   
      @ComplexityLevel as Int output,   
      @MCC as VarChar(3) output,   
      @AcuteQuartile as VarChar(10) output,   
      @CmgRIW as VarChar(10) output,   
      @CmgMOH as VarChar(10) output,   
      @CmgRIW$ as VarChar(20) output,   
      @CmgMOH$ as VarChar(20) output,   
      @CmgELOS as VarChar(10) output,   
      @CmgTrim as VarChar(10) output,   
      @CmgDesc as VarChar(60) output,   
      @MedOrSurg as VarChar(1) output,  
      @AbstractID as Int,

      --Ticket 9011
      @Occurance as int = 1,
      @ExpiryDate as varchar(10) = NULL,
      --Ticket 9373
      @AgeGroup as int,
      @Plx4 as VarChar(1),
	  @FlagRecord as VarChar(1) = 'N'
   AS    
      Declare @MRDxCMG VarChar(8)   
      Declare @Branch VarChar(10)   
      Declare @BranchTemp VarChar(10)   
      Declare @BranchCMG VarChar(3)   
      Declare @IBranchCMG VarChar(3)   
      Declare @Partition as VarChar(2)   
      Declare @FinalSubBranch as VarChar(1)   
      Declare @FinalMCCCode as VarChar(14)   
      Declare @CmgALOS as VarChar(10)   
      Declare @CmgPDRA as VarChar(10)   
      Declare @CmgPDWGT as VarChar(10)   
      Declare @Cat1 as int   
      Declare @Cat2 as int   
      Declare @PlexHomeMcc as VarChar(2)   
      Declare @PlexCount as int   
      Declare @PlexLevel as VarChar(1)   
      Declare @PlexDiagnosis as VarChar(6)   
      Declare @PlexA as int   
      Declare @PlexB as int   
      Declare @PlexC as int   
      Declare @PlexD as int   
      Declare @PlexP as int   
      Declare @Complexity as int   
      Declare @PlexCMCC as int   
      Declare @MedSurg as int      
      Declare @RIW$ as VarChar(10)   
      Declare @CMGProc as Varchar(12)   
      Declare @FinalMCCCodeTemp as VarChar(14)   
      Declare @FinalCMGTemp as VarChar(14)   
      Declare @RIWDeath as VarChar(10)   
      Declare @HospProv as VarChar(2)   
      Declare @IsAcuteTo as bit   
      Declare @IsAcuteFrom as bit   
      Declare @SQL as NVarChar(3000)   
      Declare @count as int   
      Declare @AgeNumber as int   
      Declare @SDate as datetime   
      Declare @NonAcuteQuartile as VarChar(1)
   set @SDate = getdate()   
      Set Nocount on
      Set @IsAcuteTo = 0   
      Set @IsAcuteFrom = 0   
      
     If @AgeCode = 1 and @Age > 28 
     Set @AgeCode = 3 
    
      If @Gender = 'M'   
          Set @Gender = '1'   
      Else If @Gender = 'F'   
          Set @Gender = '2'   
      If isnull(@DiagMostResposible, '0') = '0'   
          Set @DiagMostResposible = ''   
      
      if exists (SELECT * FROM LU_Institution_10 WHERE code = @InstTo and InstCareType = 'A')   
   set @IsAcuteTo = 1  
      if exists (SELECT * FROM LU_Institution_10 WHERE code = @InstFrom and InstCareType = 'A')   
   set @IsAcuteFrom = 1  
      
      If rtrim(@DiagTypeAll) = ''   
          Set @DiagTypeAll = '''XXX'''   
      If @ProceduresAll = ''   
          Set @ProceduresAll = '''XXX'''   
      
      Declare @DiagMProcAll as VarChar(2000)   
      Declare @DiagMProc as VarChar(2000)   
      Set @DiagMProcAll = ''   
      If @DiagMostResposible <> ''   
      Begin   
          set @DiagMProcAll = '''' + @DiagMostResposible + ''', '    
          set @DiagMProc = '''' + @DiagMostResposible + ''', '    
      End   
      Set @DiagMProcAll = replace(@DiagMProcAll, ', ,',  ', ')   
      Set @DiagTypeAll = replace(@DiagTypeAll, ', ,',  ', ')   
      
      If @DiagnosisAll <> ''   
          Set @DiagMProcAll = @DiagMProcAll + @DiagnosisAll + ', '   
  
      If @ProceduresAll <> ''   
      Begin   
          Set @DiagMProcAll = @DiagMProcAll + @ProceduresAll   
          Set @DiagMProc = @DiagMProc + @ProceduresAll   
      End   
      If right(@DiagMProcAll, 2) = ', '   
          Set @DiagMProcAll = Left(@DiagMProcAll, len(@DiagMProcAll) - 2)   
      If right(@DiagMProc, 2) = ', '   
          Set @DiagMProc = Left(@DiagMProc, len(@DiagMProc) - 2)   
      Set @DiagMProcAll = replace(@DiagMProcAll, ', ,',  '')   
    
      If right(@DiagMProcAll, 1) <> ''''   
          Set @DiagMProcAll = @DiagMProcAll + ''''   
      If isnull(@DiagnosisAll, '') = '' 
          Set @DiagnosisAll = '''XXX''' 
  
    --TICKET 8965
	If @DDisposition = '08'  
	  set @MCC = '99X'         
	Else if @DDisposition = '09'   
	Begin   
	  set @MCC = '99'
	  Set @FinalCMG = '997'
	  Set @CmgDesc = 'Stillbirth'
	End 
	Else If (@Weight = 0 and isnull(@AgeCode, 0) <> 1) or (@Weight <> 0 and isnull(@AgeCode, 0) > 1) 	
          SELECT Top 1 @MCC = [MCC], @MRDxCMG = [CMG], @BranchTemp = [MCCCode]  FROM CMG_Main2003   
          WHERE ([DiagProcCode]= @DiagMostResposible) AND ([Priority] = 3) AND (Gender = @Gender Or Gender = 3)   
	Else if @Weight < 200 
	Begin
	Set @MCC = '99'
	Set @FinalCMG = '999'
	End
	Else if @Weight < 750 AND @Weight >= 200
	Begin   
	  set @MCC = '15X'   
	  Set @FinalCMG = '625'   
	End   
	Else if @Weight < 1000   
	Begin   
	  set @MCC = '15X'   
	  Set @MRDxCMG = '626'   
	End   
	Else if @Weight < 1500   
	Begin   
	  set @MCC = '15X'   
	  Set @MRDxCMG = '628'   
	  Set @BranchTemp = 'MC15XM03MD'   
	End   
	Else if @Weight < 2000   
	Begin   
	  set @MCC = '15X'   
	  Set @MRDxCMG = '632'   
	  Set @BranchTemp = 'MC15XM04MD'   
	End   
	Else if @Weight < 2500   
	Begin   
	  set @MCC = '15X'   
	  Set @MRDxCMG = '640'   
	  Set @BranchTemp = 'MC15XM05MD'   
	End   
	Else if @Weight > 2499 AND @Weight < 9000
	Begin   
	  set @MCC = '15X'   
	  Set @MRDxCMG = '648'   
	  Set @BranchTemp = 'MC15XM06MD'   
	End
	Else if @Weight > 8999 
	Begin
	Set @MCC = '99'
	Set @FinalCMG = '999'
	End
      If (@BranchTemp in ('MC19XM01MD', 'MC19XM02MD', 'MC19XM05MD') and @LOS < 6 and (@DDisposition = '05' or (@IsAcuteTo = 0 or @IsAcuteFrom = 0)) and @DDisposition not in ('06', '07')
   and (@IsAcuteTo = 0 and @IsAcuteFrom = 0)) 
      Begin   
          Set @FinalCMG = @MRDxCMG + 1   
          Set @Branch = @BranchTemp   
      End   
      If left(@DiagMostResposible, 3) = 'Z53' and (@MCC <> '23' and len(@ProceduresAll) = 0)--modified 2006/02/27
      Begin 
      Set @FinalCMG = @MRDxCMG  
      Set @FinalMCCCode = @BranchTemp         
      End 
  
      If @DDisposition = '08' 
      Begin 
      set @FinalCMG = 996 
      End 

      If @FinalCMG is NULL   
      Begin   
          Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
          WHERE DiagProcCode in (' + @ProceduresAll + ') AND MCC = ''' + @MCC + ''' AND Priority < 3 ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
           @Branch output, @BranchCMG Output, @CMGProc Output
          Set @Partition = SUBSTRING(@Branch, 7, 2)   
          If isnull(@Branch, '0') = '0' and @MCC = '18X' and isnull(@Procedure1, '0') <> '0'   
          begin   

              Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
              WHERE DiagProcCode in (' + @ProceduresAll + ')  and translatefrom like ''appdh%'' ORDER BY SortOrder'   

              exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
           @Branch output, @BranchCMG Output, @CMGProc Output
              If isnull(@Branch, '0') <> '0'   
              begin   
                  Set @Branch = 'MC18XS02PR'   
                  Set @BranchCMG = '750'   
              end   
          end   
          Else If isnull(@Branch, '0') = '0' and @MCC = '17A' and isnull(@Procedure1, '0') <> '0'   
          begin   
              Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
              WHERE DiagProcCode in (' + @ProceduresAll + ') and translatefrom like ''appdh%'' ORDER BY SortOrder'   
              exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output',
           @Branch output, @BranchCMG Output, @CMGProc Output
   
              If isnull(@Branch, '0') <> '0'   
              begin   
              Set @Branch = Null 
              Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
              WHERE DiagProcCode in (' + @DiagMProcAll + ') AND MCCCode = ''MC17AS03MDL01'' ORDER BY SortOrder'   
              exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
                   @Branch output, @BranchCMG Output, @CMGProc Output
    
              If isnull(@Branch, '0') = '0'   
              begin   
                      Set @FinalMCCCode = 'MC17AS03PR'   
                      Set @FinalCMG = '728'   
              End 
              end   
          end   
          Else If isnull(@Branch, '0') = '0' and @MCC = '17B' and isnull(@Procedure1, '0') <> '0'   
          begin   
              Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
              WHERE DiagProcCode in (' + @ProceduresAll + ') and translatefrom like ''appdh%'' ORDER BY SortOrder'   
              exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
           @Branch output, @BranchCMG Output, @CMGProc Output
              If isnull(@Branch, '0') <> '0'   
              begin   
                  Set @FinalCMG = '734'   
                  Set @BranchCMG = '734'   
              end   
          end   
          Else if @MCC = '05A' and (@Partition = '06' or @Partition = '07') and SUBSTRING(@Branch, 5, 2) = 'AS'   
          Begin   
              SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003    
              WHERE DiagProcCode = (@DiagMostResposible) AND MCC = @MCC AND (Partition = @Partition) AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= 'AS' ORDER BY SortOrder   
              If @FinalCMG is null   
              Begin   
                  If @BranchCMG is null   
                      Set @FinalCMG = @MRDxCMG   
                  Else   
                      Set @FinalCMG = @BranchCMG   
              End   
          End   
          else If isnull(@Branch, '0') = '0'   
              Set @Branch = @BranchTemp   
          Set @Partition = SUBSTRING(@Branch, 7, 2)   
   if isnull(@FinalSubBranch, '') = ''
   Begin
              Set @SQL = 'SELECT Top 1 @FinalSubBranch = MedicalSurgical FROM CMG_Main2003   WHERE MCCCode = ''' + @Branch + ''''   
              exec sp_executesql @sql, N'@FinalSubBranch VarChar(1) output', @FinalSubBranch output
       if isnull(@FinalSubBranch, '') = ''
           Set @FinalSubBranch = '2'
   end
      End   
  
      If @MCC = '15X'   
      Begin   
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003              WHERE DiagProcCode in (' + @DiagMProcAll + ') AND (MCC = ''' + @MCC + ''')    


          AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
      End   
      Else If @MCC = '13X'   
      Begin   
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE DiagProcCode in (' + @DiagMProc + ') AND (MCC = ''' + @MCC + ''')    
          AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
      End   
      Else If @MCC = '24X'   
      Begin
         Declare @MCC24X as Varchar(10)
         If CHARINDEX(',', @DiagnosisAll) > 0
           set @MCC24X = left(@DiagnosisAll, CHARINDEX(',', @DiagnosisAll) - 1 )
	 Else if Len(@DiagnosisAll) > 0
           set @MCC24X = @DiagnosisAll

         Set @FinalCMG = Null
         If CHARINDEX(@MCC24X, @DiagTyped1 + ' ' + @DiagTyped2) > 0
         Begin
           Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002    
           WHERE DiagProcCode in (' + @MCC24X + ') AND MCC = ''' + @MCC + '''     
           AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
         End

         If @FinalCMG is Null and CHARINDEX(@MCC24X, @DiagTyped1 + ' ' + @DiagTyped2) > 0
		Set @FinalCMG = '868'
	 Else If CHARINDEX(@MCC24X, @DiagTyped1 + ' ' + @DiagTyped2) = 0
         Begin   
           Set @FinalCMG = '999'   
           Set @FinalMCCCode = 'MC99XM01MD'   
           Set @MCC = '99'   
         End   
      End
      Else If @FinalCMG is null and @BranchCMG is not null and @MCC not in ('05A', '08X', '10X') 
      Begin 
   Declare @ProcTemp as VarChar(15) 
          set @FinalCMGTemp = @BranchCMG   
     Set @ProcTemp = @CMGProc 
     Set @BranchTemp = @BranchCMG 
          Set @BranchCMG = Null   
   
          Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
          WHERE DiagProcCode in (' + @ProceduresAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
          AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', @Branch output, @BranchCMG Output, @CMGProc Output   
   If @BranchCMG is null 
           Begin 
              Set @FinalCMG = @FinalCMGTemp 
              Set @FinalMCCCode = @BranchTemp 
              Set @CMGProc = @ProcTemp 
           End 
   Else 
           Begin 
              Set @FinalCMG = @BranchCMG 
              Set @FinalMCCCode = @Branch 
           End 
      End 
      Else If @FinalCMG is null   
      Begin   
	If  @mcc = '23X' and @ProceduresAll = '''XXX'''
	   Set @SQL = ''
	Else
           Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003    
           WHERE DiagProcCode in (' + @DiagMProcAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
           AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
       End   
   
    If @MCC = '05A' and (@Partition Between '03' and '15') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02'   
      Begin   
          declare @Diag05 as VarChar(1000) 
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   
   
          set @Diag05 = replace(@DiagMProcAll, replace(replace(Replace(substring(@DiagTypeAll, charindex('|3', @DiagTypeAll) -5, 6), '|', ''), ' ', ''), '''', ''), 'xxx') 
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE (DiagProcCode) in (' + @Diag05 + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
          AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch +  ''' and SortOrder > 6 ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
      
          If @FinalCMG is Null   
              Set @FinalCMG = @FinalCMGTemp   
      End   
      --New 2002/09/20  
      Else If (@MCC = '05A' and (@Partition Between '19' and '21')) or (@MCC = '04X' and (@Partition Between '09' and '11')) or (@MCC = '01X' and (@Partition Between '09' and '11'))  
       or (@MCC = '06X' and (@Partition Between '19' and '21')) or (@MCC = '08X' and (@Partition Between '27' and '29')) or (@MCC = '11X' and (@Partition Between '17' and '19'))  
       or (@MCC = '05B' and (@Partition Between '12' and '14')) 
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 ORDER BY SortOrder'    
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
     
          If @FinalCMG is Null and isnull(@FinalCMGTemp, '0')  = '902' 
   	Begin 
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003    
  
             WHERE DiagProcCode in (' + @ProceduresAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
             AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
	   End 
	   Else If @FinalCMG is Null 
              Set @FinalCMG = @FinalCMGTemp    
      End    
      Else If @MCC = '05A' and (@Partition Between '03' and '15') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) <> 'L02'   
          Set @FinalCMG = Null   
      Else If (@MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02' AND (@LOS >= 4)) or    
          ((@MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02') and (@DDisposition in ('07', '06') or @IsAcuteTo = 1 or @IsAcutefrom = 1))   
      Begin   
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003    
          WHERE (DiagProcCode) in (' + @DiagMProcAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
          AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' and SortOrder > 2 ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
          If @FinalCMG is Null   
              Set @FinalCMG = @FinalCMGTemp   
          else if @Partition = '01'   
              Set @FinalCMG = @FinalCMG - 4              else   
              Set @FinalCMG = @FinalCMG - 2   
      end   
      Else If @MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02' And @LOS < 4   
          Set @FinalCMG = '218'   
      Else if @MCC = '05A' and (@Partition = '03' or @Partition = '04' or @Partition = '05')   
      Begin   
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
             
          If @FinalCMG is Null   
              Set @FinalCMG = @FinalCMGTemp   
          If @FinalCMG in ('176', '178', '181')   
              Set @FinalCMG = '183'   
          Else If @FinalCMG in ('177', '179', '182')   
          Begin   
              set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
              AND MCCCode = ''MC05AS' + @Partition + 'NPL02'''   
              exec sp_executesql @sql, N'@count int output', @Count output   
              If isnull(@Count, 0) > 0   
                  Set @FinalCMG = @FinalCMG - 1   
          End   
      end   
      Else if @MCC = '05A' and @Partition = '10' and (@FinalCMG = '181' or @FinalCMG = '182')   
      Begin  
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   
	If @FinalCMGTemp = '182'
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND sortorder = 2 AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
	else
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND sortorder = 1 AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   

          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
             
          If @FinalCMG is Null and @FinalCMGTemp = '182'
              Set @FinalCMG = '182' 
          else If @FinalCMG is Null and @FinalCMGTemp = '181'
              Set @FinalCMG = '194'   
      End   
      --New 2002/09/19  
      Else If @MCC = '06X' and (@Partition = '12')  
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = @FinalCMGTemp    
      End    
      --New 2002/09/24  
      Else If ((@MCC = '08X' and (@Partition in ('04', '05', '07'))) or (@MCC = '21X' and (@Partition in ('08', '10'))) or 
           (@MCC = '23X' and (@Partition in ('02', '04')))) and @FinalCMG in ('350', '354')
      Begin    
          set @FinalCMG = NULL  
          Declare @MC08Count as int 
	  set @MC08Count = 0

	Declare @TempProcString as varchar(1000)
	Declare @TempProcString2 as varchar(1000)
	Declare @MultiReplaceCountTemp as int
	
	set @TempProcString = @ProceduresAll
	
	While len(@TempProcString) > 1
	Begin
		set @MultiReplaceCountTemp = 0
		if CHARINDEX ( ',' , @TempProcString, CHARINDEX(', ',@TempProcString)+1  ) > 1
			set @TempProcString2 = substring(@TempProcString,0, CHARINDEX ( ',' , @TempProcString, CHARINDEX(', ',@TempProcString  )+1))
		else
			set @TempProcString2 = @TempProcString

		--Ticket 10639
		If @MCC = '21X'
	          set @SQL = 'SELECT @MultiReplaceCountTemp = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @TempProcString2 + '))    
	          AND MCCCode = ''MC' + left(@mcc, 2) + 'XS' + @Partition + 'PRL03''' 
		Else
	          set @SQL = 'SELECT @MultiReplaceCountTemp = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @TempProcString2 + '))    
	          AND MCCCode = ''MC' + left(@mcc, 2) + 'XS' + @Partition + 'PRL01''' 

	          exec sp_executesql @sql, N'@MultiReplaceCountTemp int output', @MultiReplaceCountTemp output
  		if @MultiReplaceCountTemp > 0
			set @MC08Count = @MC08Count + 1
		set @TempProcString = right(@TempProcString, len(@TempProcString)-len(@TempProcString2))
		if len(@TempProcString) > 4
			set @TempProcString = right(@TempProcString, len(@TempProcString) - 2)
		else
			Set @TempProcString = ''
	End
   
          If isnull(@MC08Count, 0) > 1 and len(@ProceduresAll) > 30 
             Set @FinalCMG = 350    
          Else  
          Begin  
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
             WHERE ((DiagProcCode) in (' + @DiagMProcAll + ')) 
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SortOrder > 1 ORDER BY SortOrder'    
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          End  
   
          If @FinalCMG is Null    
     Begin
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
             WHERE ((DiagProcCode) in (' + @DiagMProcAll + ')) 
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 2 ORDER BY SortOrder'    
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
     End
      End    
      Else If @MCC = '08X' and (@Partition between '10' and '25') and SUBSTRING(@Branch, 6, 1) = 'S' 
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = @FinalCMGTemp    
      End    
      --New 2002/09/19  
      Else If @MCC = '09X'  
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = @FinalCMGTemp    

	  If @FinalCMG = '438'
	  Begin
	          set @FinalCMGTemp = @FinalCMG    
	          Set @FinalCMG = Null    
	
	          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
	          WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
	           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
	          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = '437'    
	  End
	  --Ticket 10302
	  If @FinalCMG = '427'
	  Begin
	          set @FinalCMGTemp = @FinalCMG    
	          Set @FinalCMG = Null    
	
	          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
	          WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
	           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
	          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = '425'    
	  End
      End    
      Else If @MCC = '10X' and @Partition = '01' and SUBSTRING(@FinalMCCCode, 5, 2) = 'XS' 
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = @FinalCMGTemp    
      End    
      --New 2002/09/25  
      Else If @MCC = '19X' and (@FinalCMG not in ('771', '778', '767')) and @FinalCMG is not null 
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Declare @LenDiag as int 
          Declare @Diag19X as NVarChar(200) 
          set @LenDiag = len(@DiagMProcAll) - len(@DiagMostResposible) - 4 
          If @LenDiag < 0 
          Begin 

             Set @LenDiag = 0 
             Set @Diag19X = '''''' 
          End 
          Else 
             Set @Diag19X = right(@DiagMProcAll, @LenDiag) 
          set @Diag19X = replace(@Diag19X, replace(replace(Replace(substring(@DiagTypeAll, charindex('|3', @DiagTypeAll) -5, 6), '|', ''), ' ', ''), '''', ''), 'xxx') 
     If right(@Diag19X, 1) = ',' 
           set @Diag19X = left(@Diag19X, len(@Diag19X)-1)

     If right(@Diag19X, 1) <> '''' 
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
             WHERE ((DiagProcCode) in (' + @Diag19X + '''))    
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
     Else
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
             WHERE ((DiagProcCode) in (' + @Diag19X + '))    
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    

          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
          Begin  
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
             WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
              AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 1 ORDER BY SortOrder'    
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          End  
      End   
    Else If @MCC = '11X' and (@Partition = '01') and right(@FinalMCCCode, 3) = 'L01' 
      Begin	
	If @LOS > 2 or @DDisposition in ('06','07') or @isAcuteTo = 1 or @isAcuteFrom = 1
		Set @FinalCMG = '520'	
	Else if @LOS < 3 AND @isAcuteTo = 0 and @isAcuteFrom = 0
		Set @FinalCMG = '999'	
      End  
      Else if @MCC = '13X' and @FinalMCCCode like 'MC13XS04%'   
      Begin   
          If @FinalMCCCode = 'MC13XS04PRL02'   
          Begin   
              set @FinalCMGTemp = @FinalCMG   
              Set @FinalCMG = Null   
              set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProc + '))    
              AND MCCCode in (''MC13XS04MDL03'', ''MC13XS04PRL04'') ORDER BY SortOrder'   
              exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
      
              If @FinalCMG is Null   
                  Set @FinalCMG = '579'   
          End   
          Else If @FinalMCCCode = 'MC13XS04MDL01'   
          Begin   
              set @FinalCMGTemp = @FinalCMG   
              Set @FinalCMG = Null   
              set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProc + '))    
              AND MCCCode = ''MC13XS04PRL02'''   
              exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
   
              If @FinalCMG is Null   
                  Set @FinalCMG = @FinalCMGTemp   
          End   
          If @FinalMCCCode = 'MC13XS04MDL03'   
          Begin   
              set @FinalCMGTemp = @FinalCMG   
              Set @FinalCMG = Null   
              set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProc + '))    
              AND MCCCode = ''MC13XS04PRL04'''   
              exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
                 
              If @FinalCMG is Null   
                  Set @FinalCMG = @FinalCMGTemp   
          End   
          Else If @FinalMCCCode = 'MC13XS04PRL04'   
              Set @FinalCMG = '579'   
      end   
      Else If (@MCC = '14X' and (@Partition = '05')) And (@LOS >= 3 or @IsAcuteTo = 1 or @IsAcuteFrom = 1) 
          Set @FinalCMG = '599'   
      Else If @MCC = '14X' and (@Partition = '01') and @FinalSubBranch = 1 and ((@FinalCMG = '612' or (@FinalCMG is null and @MRDxCMG = '612')))
      Begin   
          Set @FinalCMG = Null   
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
          SortOrder = 1 ORDER BY SortOrder' 
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
          If @FinalCMG is Null   
              Set @FinalCMG = 600   
      end   
      Else If @MCC = '15X' and (@Partition Between '03' and '06') and right(@FinalMCCCode, 3) = 'L01'  And @DDisposition in ('04', '05') And @LOS < 6   
          Set @FinalCMG = 998   
--Added on Ticket 9161
      Else If @MCC= '15X' and (@Partition Between '03' and '06') and right(@FinalMCCCode, 3) = 'L01' and (@DDisposition in ('07', '06') or @IsAcuteTo = 1 or @IsAcutefrom = 1 or @LOS > 6) 
      Begin

	  If @Partition = '03'
          	Set @FinalCMG = 627  
	  If @Partition = '04'
          	Set @FinalCMG = 630  
	  If @Partition = '05'
          	Set @FinalCMG = 636  
	  If @Partition = '06'
          	Set @FinalCMG = 643  
      End
      Else If @MCC = '15X' and (@Partition in ('06', '05')) and ((@FinalCMG = '646' or (@FinalCMG is null and @MRDxCMG = '646')) or 
      (@FinalCMG = '647' or (@FinalCMG is null and @MRDxCMG = '647')) or (@FinalCMG = '648' or (@FinalCMG is null and @MRDxCMG = '648'))
      or (@FinalCMG = '639' or (@FinalCMG is null and @MRDxCMG = '639'))or (@FinalCMG = '640' or (@FinalCMG is null and @MRDxCMG = '640')))
      Begin   
          Set @FinalCMG = Null   
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE (((DiagProcCode) in (' + @DiagMProcAll  + ')) or
	  ((DiagProcCode) in (''''' + @DiagTyped0 + @DiagTyped3 + ')) and isnull(translatefrom, '''') = '''')
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
          SortOrder = 4 ORDER BY SortOrder' 
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
          If @FinalCMG is Null   
          Begin
           set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
           SortOrder > 4 ORDER BY SortOrder' 
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
           If @FinalCMG is Null and @MRDxCMG in ('646', '647', '648')
               Set @FinalCMG = 648   
           Else If @FinalCMG is Null and @MRDxCMG in ('639', '640')
               Set @FinalCMG = 640   
      	  End
      end 
      Else If @MCC = '14X' and (@Partition = '02')-- and right(@FinalMCCCode, 3) = 'L01'   
      Begin   
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
          SortOrder = 1 ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
             
          If @FinalCMG is Null   
              Set @FinalCMG = @FinalCMGTemp   
          Else  
          Begin  
             set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
             SortOrder > 1 ORDER BY SortOrder'   
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
  
             If @FinalCMG is Null   
                 Set @FinalCMG = @FinalCMGTemp   
             If @FinalCMG = '601'   
                 Set @FinalCMG = '603'   
             Else If @FinalCMG in ('602', '604')
             Begin   
                 set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + @DiagTyped3 + '))    
                 AND MCCCode = ''MC14XS02MOL03'''   
                 exec sp_executesql @sql, N'@count int output', @Count output   
                 If isnull(@Count, 0) > 0   
                     Set @FinalCMG = @FinalCMG - 1   
             End   
      End  
      end   
      Else If @MCC = '14X' and (@Partition = '02') and right(@FinalMCCCode, 3) <> 'L01' and SUBSTRING(@FinalMCCCode, 5, 2) <>  'XM'   
          Set @FinalCMG = 999   
     Else If @MCC = '14X' and (@FinalCMG Between '608' and '611' or (@FinalCMG is null and @MRDxCMG Between '608' and '611'))--(@FinalCMG = '608' or @FinalCMG = '609')   
     Begin   
         If @FinalCMG = '608'   
             Set @FinalCMG = '610'   
         Else 
         Begin   
             set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + @DiagTyped3 +  '))    
             AND MCCCode = ''MC14XM01MOL04'''  
             exec sp_executesql @sql, N'@count int output', @Count output  
             If isnull(@Count, 0) > 0 and @FinalCMG is not null
                 Set @FinalCMG = @FinalCMG - 1   
             Else If isnull(@Count, 0) > 0 and @FinalCMG is null
                 Set @FinalCMG = @MRDxCMG - 1   
         End   
     End   
      Else If @MCC = '14X' and (@FinalCMG in ('620', '621'))   
      Begin   
          If @FinalCMG = '621'   
          Begin   
              set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagnosisAll + '))    
              AND MCCCode = ''MC14XM06PRL10'''   
              exec sp_executesql @sql, N'@count int output', @Count output   
              If isnull(@Count, 0) > 0   
                  Set @FinalCMG = @FinalCMG - 1   
          End   
      end   
      Else if @MCC = '21X' and (@Partition in ('05', '06'))   
      Begin   
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   

          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   

          If @FinalCMG is Null 
              Set @FinalCMG = @FinalCMGTemp  
          If @FinalCMG in ('176', '178', '181')   
              Set @FinalCMG = '183'   
          Else If @FinalCMG in ('177', '179', '182')   
          Begin  

              set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
              AND MCCCode = ''MC21XS' + @Partition + 'NPL02'''   
              exec sp_executesql @sql, N'@count int output', @Count output   
              If isnull(@Count, 0) > 0   
                  Set @FinalCMG = @FinalCMG - 1   
          End   
      end   
      Else if @MCC = '22X' and (@Partition in ('01', '02')) --Ticket 9698
      Begin   
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   

          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   

          If @FinalCMG is Null 
              Set @FinalCMG = @FinalCMGTemp  
      end 
      Else If @MCC = '25X' and SUBSTRING(@Branch, 6, 1) = 'S' and SUBSTRING(@Branch, 7, 2) = '05' and @FinalCMG in ('351', '350') 
      Begin
   	Declare @MC25Proc as VarChar(15) 
  	Declare @MC25Count as int   
          If @FinalCMG = 350   
   	  Begin 
              set @SQL = 'SELECT @MC25Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @ProceduresAll + '))    
              AND MCCCode = ''MC25XS05PRL03'''   
              exec sp_executesql @sql, N'@MC25Count int output', @MC25Count output   
           If @MC25Count = 1 
           Begin
                   set @SQL = 'SELECT  @MC25Proc = diagproccode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @ProceduresAll + '))    
                   AND MCCCode = ''MC25XS05PRL03'''   
                   exec sp_executesql @sql, N'@MC25Proc varchar(15) output', @MC25Proc output                   
  
                  If len(replace(@ProceduresAll, '''' + @MC25Proc + '''', '')) < (len(@ProceduresAll) - len(@MC25Proc) - 3)
                           Set @MC25Count = 2 
           End
   End 
   
          If isnull(@MC25Count, 0) < 2   
              Set @FinalCMG = 351   
      End   

      if len(@FinalMCCCode) > 10   
          Set @Branch = left(isnull(@FinalMCCCode, ''), 10)   

      If @FinalCMG is null   
      Begin   
          If @BranchCMG is null   
              Set @FinalCMG = @MRDxCMG   
          Else   
              Set @FinalCMG = @BranchCMG   
          If @FinalCMG is null 
               Set @FinalCMG = '999'   
      End   

      --Ticket 9330
      If @MCC is null
	set @MCC = '99'
  
      if len(@FinalMCCCode) > 10   
          Set @Branch = left(isnull(@FinalMCCCode, ''), 10)  

      Declare @MedSurgInd as VarChar(1) 
      Declare @MedSurgNon as VarChar(1) 
      SELECT @MedSurgNon = cmgmcctype, @MedSurg = cmgmcctype, @MedSurgInd = RIWInd FROM CMG_Etc_2005T WHERE (cmgcode = @FinalCMG) and (ciagegroup = @AgeGroup)    

      Set @PlexA = 0   
      Set @PlexB = 0   
      Set @PlexC = 0   
      Set @PlexD = 0   
      Set @PlexP = 0   
      Set @PlexCMCC = 0   
      If exists (SELECT * FROM CMG_Etc_2005T WHERE ((cmgcode = @FinalCMG) AND (cicpxlvl = 9) and (ciagegroup = @AgeGroup)) or @MedSurg = '9') 
          set @Complexity = 9   
      Set @DiagTypeAll = replace(@DiagTypeAll, @DiagMostResposible + '|', 'XXXXX|')   

      if @Plx4 = 'Y' and isnull(@Complexity, '') <> '9'
	set @Complexity = 4  
      If isnull(@AbstractID, 0) > 0 and (CHARINDEX ('1GZ31CAND', @ProceduresAll ) > 0 or CHARINDEX ('1GZ31CRND', @ProceduresAll ) > 0)
   and @Complexity is null
      Begin   
	   if exists (SELECT dbo.AB_Intervention.AbstractID FROM dbo.AB_Intervention LEFT OUTER JOIN
           dbo.ICD_ProcFile10 ON dbo.AB_Intervention.IntervCode = dbo.ICD_ProcFile10.Code LEFT OUTER JOIN
           dbo.LU_IntervAttExtent ON dbo.AB_Intervention.IntervAttribExtent = dbo.LU_IntervAttExtent.Code
           WHERE (dbo.LU_IntervAttExtent.CIHIValue IN ('EX')) AND (dbo.ICD_ProcFile10.CIHIValue  in ('1GZ31CAND', '1GZ31CRND')) AND (dbo.AB_Intervention.AbstractID = @AbstractID))
	   set @Complexity = 4  
      End

     --If there are duplicate diagnosis with the same type, take type 1
     Declare @DupDiagComplex as Varchar(20)
     set @SQL = 'SELECT top 1 @DupDiagComplex = diagnosis FROM CMG_Plx2002   
         WHERE DiagTypeCombine in (' + @DiagTypeAll + ')
 	AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''') 
 	And Diagnosis not in (SELECT DiagnosisEx FROM dbo.CMG_PlxException2001 WHERE (MCCEx = LEFT(''' + @MCC + ''',2)) AND (CMGEx = ''' + @FinalCMG + '''))
 	group by diagnosis having Count(diagnosis) > 1'   
     exec sp_executesql @sql, N'@DupDiagComplex VarChar(20) output', @DupDiagComplex output 

     If isnull(@DupDiagComplex, '') <> ''
    	Set @DiagTypeAll = replace(@DiagTypeAll, @DupDiagComplex + '|2', 'XXXXX|2')   

  
           Create TABLE #PlxTemp (PlCount int, Plex varchar(1))
  --Plex Levels
   set @SQL = 'SELECT count(*) as PlCount, substring(Plexity, cast(LEFT(''' + @MCC + ''',2) as int), 1) as Plex FROM CMG_Plx2003   
          WHERE DiagTypeCombine in (' + @DiagTypeAll + ')
   AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''') 
   And Diagnosis not in (SELECT DiagnosisEx FROM dbo.CMG_PlxException2003 WHERE (MCCEx = LEFT(''' + @MCC + ''',2)) AND (CMGEx = ''' + @FinalCMG + '''))
   group by substring(Plexity, cast(LEFT(''' + @MCC + ''',2) as int), 1)'   
   Insert into #PlxTemp Exec (@SQL)
  
      if @Complexity is null and @@Rowcount > 0   
      Begin  
  --Level C Not Home Plex
   set @SQL = 'SELECT @PlexCMCC = count(*) FROM CMG_Plx2003   
        WHERE DiagTypeCombine in (' + @DiagTypeAll + ') and substring(Plexity, cast(LEFT(''' + @MCC + ''',2) as int), 1) = ''C'' 
   and HomeMCC <> LEFT(''' + @MCC + ''',2)
   AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''') 
   And Diagnosis not in (SELECT DiagnosisEx FROM dbo.CMG_PlxException2003 WHERE (MCCEx = LEFT(''' + @MCC + ''',2)) AND (CMGEx = ''' + @FinalCMG + '''))'   
   exec sp_executesql @sql, N'@PlexCMCC VarChar(1) output', @PlexCMCC output   
   Set @PlexA = isnull((select PlCount from #PlxTemp where Plex = 'A'), 0)
   Set @PlexB = isnull((select PlCount from #PlxTemp where Plex = 'B'), 0)
   Set @PlexC = isnull((select PlCount from #PlxTemp where Plex = 'C'), 0)
   Set @PlexD = isnull((select PlCount from #PlxTemp where Plex = 'D'), 0)
   Set @PlexP = isnull((select PlCount from #PlxTemp where Plex = 'P'), 0)
   If @PlexCMCC > 1
           Set @PlexCMCC = 1
  
          If @PlexA > 0 or @PlexB > 1 or (@PlexB = 1 and @PlexC > 0 and @PlexCMCC = 1)   
              Set @Complexity = 4   
          Else If @PlexB > 0 or (@PlexC > 1 and @PlexCMCC = 1) or (@PlexC > 10 and @PlexCMCC = 0)   
              Set @Complexity = 3   
          Else If @PlexD > 0 or @PlexP > 0 or (@PlexC = 1 and @PlexCMCC = 1)    
              or (@PlexC > 0 and @PlexC < 11 and @PlexCMCC = 0)   
              Set @Complexity = 2   
          Else   
              Set @Complexity = 1   
      End   

      If isnull(@Complexity, '') = ''   
          Set @Complexity = 1   
      
      Set @MCC = Replace(@MCC, 'X', '')   
      Set @ComplexityLevel = @Complexity   
      SELECT Top 1 @CmgDesc = cmgdesc, @CmgTrim = ciagtrim, @CmgELOS = ciagelos, @CmgPDRA = ciagpdra, @CmgPDWGT = ciagpdwgt, @CmgRIW = ciagriw   
      FROM dbo.CMG_Etc_2005T WHERE (cmgcode = @FinalCMG) AND (cicpxlvl = @ComplexityLevel) AND (ciagegroup = @AgeGroup) --AND (cmgmcctype = @MedSurg)  
  --print @CmgDesc 
  --print @CmgTrim 
  --print @CmgELOS 
  --print @CmgPDRA 
  

   --New 2002/09/30 
      If @MedSurg = 9 
      Set @MedSurg = 1   
      If @FinalCMG in ('910', '912', '998', '999') and @LOS < cast(@CMGELOS as decimal(7,4))   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      Else If @FinalCMG in ('910', '912', '998', '999') and @LOS >= cast(@CMGELOS as decimal(7,4))   
          Set @CMGRIW = @CmgRIW
      else if @DDisposition = '07' and @LOS <= @CMGTrim and @LOS <= 10   
      Begin   
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer    
              WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr is null and dxyear = 2005)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      else if @DDisposition = '07' and @LOS <= @CMGTrim and @LOS > 10   
      Begin 
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
              WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr is null and dxyear = 2005)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   

      Else If @DDisposition = '06' and @LOS <= cast(@CMGELOS as decimal(7,4))   
          Set @CMGRIW = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,4))) as decimal(7,4))   
      Else If @DDisposition = '06' and @LOS > cast(@CMGELOS as decimal(7,4)) and @LOS <= @CMGTrim   
          Set @CMGRIW = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@CmgELOS as decimal(7,4))) as decimal(7,4))   
      Else If @IsAcuteTo = 1 and @LOS <= 10 and @LOS <= @CMGTrim   
      Begin   
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
              WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='O' and dxyear = 2005)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      Else If @IsAcuteTo = 1 and @LOS > 10 and @LOS <= @CMGTrim   
      Begin   
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
              WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='O' and dxyear = 2005)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      Else If @IsAcuteFrom = 1 and @LOS <= 10 and @LOS <= @CMGTrim   
      Begin   
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
              WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='I' and dxyear = 2005)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      Else If @IsAcuteFrom = 1 and @LOS > 10 and @LOS <= @CMGTrim   
      Begin   
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
              WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='I' and dxyear = 2005)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      Else If @LOS > @CMGTrim   
          Set @CMGRIW = cast(cast(@CMGRIW as decimal(7,4)) + (cast(@CmgPDRA as decimal(7,4)) * cast((cast(@LOS as decimal(7,2)) - cast(@CmgELOS as decimal(7,4))) as decimal(9,4))) as decimal(9,4))   

      Declare @CMGNon as int
      Select @CMGNon = CMGNonValue from CMG_NonBool where CMGNonYear = 2005
      if @CmgRIW is not null and isnull(@CMGNon, 0) = 0
      Begin  
          Select @RIW$ = CostPerRiw from H_InstitutionProfile where code = @InstNumber   
          if isnull(@RIW$, '0') = '0' or @RIW$ = ''   
              set @RIW$ = '0'   
          Set @CMGRIW$ = cast(@CmgRIW as decimal(7,4)) * cast(@RIW$ as decimal(6,2))   
          if @LOS - @CMGTrim > 0   
          Begin   
              Set @CMGMOH = left(@CMGRIW + (((@LOS - @CMGTrim) * cast(@CmgPDWGT as Decimal(7,4))) + (((cast(@CMGTrim as int) - cast(@CMGELOS as decimal(6,2))) * cast(@CmgPDWGT as Decimal(7,4)))) * .2), 10)   
              Set @CMGMOH$ = cast(@CmgMOH as decimal(9,4)) * cast(@RIW$ as decimal(6,2))   
          end   
          Else   
          Begin   
              Set @CMGMOH = @CMGRIW   
              Set @CMGMOH$ = @CMGRIW$   
          end   
          Set @CMGMOH = cast(@CMGMOH as decimal(8,4))   
          Set @CMGRIW$ = cast(@CMGRIW$ as decimal(10,2))   
          Set @CMGMOH$ = cast(@CMGMOH$ as decimal(10,2))   
      End
--If they have rights to non complex grouper do this
     else if @CmgRIW is not null and exists(select code from H_HospitalProfile where code + @CMGNon = 33101) --PR - 00945
     Begin
		declare @IsAcuteFromNon as bit
		declare @IsAcuteToNon as bit
		set @IsAcuteFromNon = @IsAcuteFrom
		Set @IsAcuteToNon = @IsAcuteTo
		if @IsAcuteFromNon = 0
		Begin
			If exists(select code FROM LU_Institution_10 WHERE code = @InstFrom and CIHIValue in ('53240', '53310', '53459', '53781', '53913'))
				set @IsAcuteFromNon = 1
		End
		If @IsAcuteToNon = 0
		Begin
			If exists(select code FROM LU_Institution_10 WHERE code = @InstTo and CIHIValue in ('53240', '53310', '53459', '53781', '53913'))
				set @IsAcuteToNon = 1
		End

          Select @RIW$ = CostPerRiw from H_InstitutionProfile where code = @InstNumber   
          if isnull(@RIW$, '0') = '0' or @RIW$ = ''   
              set @RIW$ = '0'   
          Set @CMGRIW$ = cast(@CmgRIW as decimal(7,4)) * cast(@RIW$ as decimal(6,2))   
	     Declare @MedSurgIndHold as VarChar(1)
	     If @Complexity = 9
	     Begin
		Set @MedSurgIndHold = @MedSurgInd
		Set @MedSurgInd = 9
	     End
	     Declare @CmgNonELOS as VarChar(10)   
	     Declare @CmgNonTrim as VarChar(10)

	     SELECT Top 1 @CmgNonTrim = ciagtrim, @CmgNonELOS = ciagelos, @CmgPDRA = ciagpdra, @CmgPDWGT = ciagpdwgt, @CMGMOH = ciagriw   
	     FROM dbo.CMG_ETC_2005_Non WHERE (cmgcode = @FinalCMG) AND (ciagegroup = @AgeGroup) and (ICDType = 'T') --AND (cmgmcctype = @MedSurg)   

	     If @MedSurg = 9 
	 		Set @MedSurg = 1   
         if @MedSurgNon = 3
                   set @MedSurgNon = 2
	     If @FinalCMG in ('910', '912', '998', '999') and @LOS < cast(@CmgNonELOS as decimal(7,4))   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     else if @DDisposition = '07' and @LOS <= @CmgNonTrim and @LOS <= 10   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non    
	             WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and isnull(cmgxfr, '') = '' and dxyear = 2005)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))
    	     End   
	     else if @DDisposition = '07' and @LOS <= @CmgNonTrim and @LOS > 10   
	     Begin 
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non  
	             WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and isnull(cmgxfr, '') = '' and dxyear = 2005)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @DDisposition = '06' and @LOS <= cast(@CmgNonELOS as decimal(7,4))   
	         Set @CMGMOH = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,4))) as decimal(7,4))   
	     Else If @DDisposition = '06' and @LOS > cast(@CmgNonELOS as decimal(7,4)) and @LOS <= @CmgNonTrim   
	         Set @CMGMOH = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@CmgNonELOS as decimal(7,4))) as decimal(7,4))   
	     Else If @IsAcuteFromNon = 1 and @LOS <= 10 and @LOS <= @CmgNonTrim   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
	             WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and cmgxfr ='I' and dxyear = 2005)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @IsAcuteFromNon = 1 and @LOS > 10 and @LOS <= @CmgNonTrim   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
	             WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and cmgxfr ='I' and dxyear = 2005)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @IsAcuteToNon = 1 and @LOS <= 10 and @LOS <= @CmgNonTrim   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
	             WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and cmgxfr ='O' and dxyear = 2005)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @IsAcuteToNon = 1 and @LOS > 10 and @LOS <= @CmgNonTrim   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
	             WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and cmgxfr ='O' and dxyear = 2005)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @LOS > @CmgNonTrim
	         Set @CMGMOH = cast(cast(@CMGMOH as decimal(7,4)) + (cast(@CmgPDRA as decimal(7,4)) * cast((cast(@LOS as decimal(7,2)) - cast(@CmgNonELOS as decimal(7,4))) as decimal(9,4))) as decimal(9,4))   
	     
	     If @MedSurgInd = 9
		Set @MedSurgInd = @MedSurgIndHold

	      If @DDisposition = '07'   
	          Set @NonAcuteQuartile = 'D'   
	      Else If @DDisposition = '06'   
	          Set @NonAcuteQuartile = 'S'   
	      Else If @IsAcuteFrom = 1 or @IsAcuteTo = 1 --or @DDisposition = '01' ticket 5711  
	          Set @NonAcuteQuartile = 'T'   
	      Else If cast(@LOS as varchar(10)) > @CmgNonTrim   
	          Set @NonAcuteQuartile = 'O'   
	      Else If @LOS > cast(@CmgNonELOS as decimal(7,4))   
	          Set @NonAcuteQuartile = 'B'   

	      Else   
	          Set @NonAcuteQuartile = 'I'  
          Set @CMGMOH$ = cast(@CmgMOH as decimal(9,4)) * cast(@RIW$ as decimal(6,2))   
          Set @CMGMOH = cast(@CMGMOH as decimal(8,4))   
          Set @CMGRIW$ = cast(@CMGRIW$ as decimal(10,2))   
          Set @CMGMOH$ = cast(@CMGMOH$ as decimal(10,2))   
      End   
     
      If @DDisposition = '07'   
          Set @AcuteQuartile = 'D'   
      Else If @DDisposition = '06'   
          Set @AcuteQuartile = 'S' 
		--Ticket PR-00766  
      Else If @IsAcuteFromNon = 1 or @IsAcuteToNon = 1 or @IsAcuteFrom = 1 or @IsAcuteTo = 1--or @DDisposition = '01' ticket 5711  
          Set @AcuteQuartile = 'T'   
      Else If @LOS > @CMGTrim   
          Set @AcuteQuartile = 'O'   
      Else If @LOS > cast(@CMGELOS as decimal(7,4))   
          Set @AcuteQuartile = 'B'   
      Else   
          Set @AcuteQuartile = 'I'   
    
      If @MedSurgInd = '2' 
	Set @MedOrSurg = 'M' 
      Else 
	Set @MedOrSurg = 'S' 
      
	--Ticket 10884 Enhancement for CMG Auditing
	If isnull(@AbstractID, 0) > 0 and @Occurance = 1
	Begin
		Declare @AUCmg as Varchar(3)
		Declare @AUCplx as VarChar(1)
		Declare @AUMcc as Varchar(3)
		Declare @AUQuartile as VarChar(1)
		Declare @AURiw as VarChar(20)
		Declare @AUAid as Int
		Declare @GrouperChange as VarChar(1)
		Set @GrouperChange = 'N'
		SELECT @AUAid = Abstractid, @AUCmg = CMG, @AUCplx = Complexity, @AUMcc = MCC, @AUQuartile = AcuteQuartile, @AURiw = CMG_RIW
		FROM AB_CMG where AbstractID = @AbstractID and OccurrenceNumber = 1 and CMG_Year = 2005
		If isnull(@AUAid, 0) > 0
		Begin
			If @AUCmg <> @FinalCMG
			Begin
				Insert into AB_GrouperAudit Values (@AbstractID, 2005, 'CMG', @AUCmg, @FinalCMG, GetDate())
				Set @GrouperChange = 'Y'
			End
			If @AUCplx <> @ComplexityLevel
				Insert into AB_GrouperAudit Values (@AbstractID, 2005, 'Complexity', @AUCplx, @ComplexityLevel, GetDate())
			If left(@AUMcc, 2) <> Left(@MCC, 2)
				Insert into AB_GrouperAudit Values (@AbstractID, 2005, 'MCC', @AUMcc, Left(@MCC, 3), GetDate())
			If @AUQuartile <> @AcuteQuartile
				Insert into AB_GrouperAudit Values (@AbstractID, 2005, 'Quartile', @AUQuartile, @AcuteQuartile, GetDate())
			If @AURiw <> @CmgRIW
			Begin
				Insert into AB_GrouperAudit Values (@AbstractID, 2005, 'RIW', @AURiw, @CmgRIW, GetDate())
				Set @GrouperChange = 'Y'
			End
		End
		If @GrouperChange = 'Y' and @FlagRecord = 'Y'
			Update AB_Abstract set iscorrected = 2 where abstractid = @AbstractID and issubmited = 1 and isdeleted = 2 and iscorrected = 1
				and batchyear = 2005
	End

      If isnull(@AbstractID, 0) > 0 
      Begin   
          If @Occurance = 1
	set @ExpiryDate = null
          Delete ab_CMG where Abstractid = @Abstractid and CMG_Year = 2005 and OccurrenceNumber = @Occurance   
          If IsNull(@FinalCMG, '') <> '' and isnull(@DiagMostResposible, '') <> ''
          Begin   
              Set @DiagMostResposible = (select top 1 code from ICD_DiagFile10 where cihivalue = @DiagMostResposible)   
              INSERT INTO [dbo].[AB_CMG] ([AbstractID], [OccurrenceNumber], [CMG_Year], [ICD_Type], [Diagnosis_Code],   
              [Diagnosis_Type], [CMG], [Complexity], [MCC], [AcuteQuartile], [CMG_RIW], [MOH_RIW],   
              [RIW_Dollar], [MOH_Dollar], [CMG_ELOS], [CMG_Trim], [CMG_Description], [MCC_Surg], MOHQuartile, ExpiryDate) VALUES    
              (@AbstractID, @Occurance, 2005, 'T', @DiagMostResposible, 11, @FinalCMG, @ComplexityLevel, rtrim(Left(@MCC, 3)), @AcuteQuartile, @CmgRIW, @CmgMOH,    
              cast(@CmgRIW$ as money), cast(@CmgMOH$ as money), @CmgELOS, @CMGTrim, @CMGDesc, @MedOrSurg,@NonAcuteQuartile, @ExpiryDate)   
              Update ab_CMG set CMGModelType = ModelType, CMGTenthPercent = TenthPercent, CMGTwentyFifthPercent = TwentyFifthPercent, CMGFiftiethPercent = FiftiethPercent
              FROM dbo.AB_CMG LEFT OUTER JOIN
              dbo.CMG_Etc_2005T ON dbo.AB_CMG.Complexity = dbo.CMG_Etc_2005T.cicpxlvl AND dbo.AB_CMG.CMG = dbo.CMG_Etc_2005T.cmgcode
              WHERE abstractid = @AbstractID and CMG_Year = 2005 and ciagegroup = @AgeGroup
          End   
      
      End   
      set nocount off    

  --    print datediff(ms, @SDate, getdate())   
      Return 0







GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_CMG2006_T]   
      @Age as Int,   
      @AgeCode as int, 
      @LOS as int,   
      @AcuteLOS as int,   
      @ICDType as VarChar(2),   
      @Gender as VarChar(1),   
      @Weight as int,   
      @DDisposition as VarChar(2),   
      @InstNumber as int,   
      @InstTo as int,   
      @InstFrom as int,   
      @DiagMostResposible as VarChar(10),   
      @DiagnosisAll as VarChar(500),   
      @DiagTypeAll as VarChar(500),   
      @DiagTyped1 as VarChar(500),   
      @DiagTyped2 as VarChar(500),   
      @DiagTyped0 as VarChar(500),   
      @DiagTyped3 as VarChar(500),   
      @ProceduresAll as VarChar(1000),   
      @Procedure1 as VarChar(10),   
      @FinalCMG as VarChar(3) output,   
      @ComplexityLevel as Int output,   
      @MCC as VarChar(3) output,   
      @AcuteQuartile as VarChar(10) output,   
      @CmgRIW as VarChar(10) output,   
      @CmgMOH as VarChar(10) output,   
      @CmgRIW$ as VarChar(20) output,   
      @CmgMOH$ as VarChar(20) output,   
      @CmgELOS as VarChar(10) output,   
      @CmgTrim as VarChar(10) output,   
      @CmgDesc as VarChar(60) output,   
      @MedOrSurg as VarChar(1) output,  
      @AbstractID as Int,

      --Ticket 9011
      @Occurance as int = 1,
      @ExpiryDate as varchar(10) = NULL,
      --Ticket 9373
      @AgeGroup as int,
      @Plx4 as VarChar(1),
	  @FlagRecord as VarChar(1) = 'N'
   AS    
      Declare @MRDxCMG VarChar(8)   
      Declare @Branch VarChar(10)   
      Declare @BranchTemp VarChar(10)   
      Declare @BranchCMG VarChar(3)   
      Declare @IBranchCMG VarChar(3)   
      Declare @Partition as VarChar(2)   
      Declare @FinalSubBranch as VarChar(1)   
      Declare @FinalMCCCode as VarChar(14)   
      Declare @CmgALOS as VarChar(10)   
      Declare @CmgPDRA as VarChar(10)   
      Declare @CmgPDWGT as VarChar(10)   
      Declare @Cat1 as int   
      Declare @Cat2 as int   
      Declare @PlexHomeMcc as VarChar(2)   
      Declare @PlexCount as int   
      Declare @PlexLevel as VarChar(1)   
      Declare @PlexDiagnosis as VarChar(6)   
      Declare @PlexA as int   
      Declare @PlexB as int   
      Declare @PlexC as int   
      Declare @PlexD as int   
      Declare @PlexP as int   
      Declare @Complexity as int   
      Declare @PlexCMCC as int   
      Declare @MedSurg as int      
      Declare @RIW$ as VarChar(10)   
      Declare @CMGProc as Varchar(12)   
      Declare @FinalMCCCodeTemp as VarChar(14)   
      Declare @FinalCMGTemp as VarChar(14)   
      Declare @RIWDeath as VarChar(10)   
      Declare @HospProv as VarChar(2)   
      Declare @IsAcuteTo as bit   
      Declare @IsAcuteFrom as bit   
      Declare @SQL as NVarChar(4000)   
      Declare @count as int   
      Declare @AgeNumber as int   
      Declare @SDate as datetime   
      Declare @NonAcuteQuartile as VarChar(1)
   set @SDate = getdate()   
      Set Nocount on
      Set @IsAcuteTo = 0   
      Set @IsAcuteFrom = 0   
      
     If @AgeCode = 1 and @Age > 28 
     Set @AgeCode = 3 
    
      If @Gender = 'M'   
          Set @Gender = '1'   
      Else If @Gender = 'F'   
          Set @Gender = '2'   
      If isnull(@DiagMostResposible, '0') = '0'   
          Set @DiagMostResposible = ''   
      
      if exists (SELECT * FROM LU_Institution_10 WHERE code = @InstTo and InstCareType = 'A')   
   set @IsAcuteTo = 1  
      if exists (SELECT * FROM LU_Institution_10 WHERE code = @InstFrom and InstCareType = 'A')   
   set @IsAcuteFrom = 1  
      
      If rtrim(@DiagTypeAll) = ''   
          Set @DiagTypeAll = '''XXX'''   
      If @ProceduresAll = ''   
          Set @ProceduresAll = '''XXX'''   
      
      Declare @DiagMProcAll as VarChar(2000)   
      Declare @DiagMProc as VarChar(2000)   
      Set @DiagMProcAll = ''   
      If @DiagMostResposible <> ''   
      Begin   
          set @DiagMProcAll = '''' + @DiagMostResposible + ''', '    
          set @DiagMProc = '''' + @DiagMostResposible + ''', '    
      End   
      Set @DiagMProcAll = replace(@DiagMProcAll, ', ,',  ', ')   
      Set @DiagTypeAll = replace(@DiagTypeAll, ', ,',  ', ')   
      
      If @DiagnosisAll <> ''   
          Set @DiagMProcAll = @DiagMProcAll + @DiagnosisAll + ', '   
  
      If @ProceduresAll <> ''   
      Begin   
          Set @DiagMProcAll = @DiagMProcAll + @ProceduresAll   
          Set @DiagMProc = @DiagMProc + @ProceduresAll   
      End   
      If right(@DiagMProcAll, 2) = ', '   
          Set @DiagMProcAll = Left(@DiagMProcAll, len(@DiagMProcAll) - 2)   
      If right(@DiagMProc, 2) = ', '   
          Set @DiagMProc = Left(@DiagMProc, len(@DiagMProc) - 2)   
      Set @DiagMProcAll = replace(@DiagMProcAll, ', ,',  '')   
    
      If right(@DiagMProcAll, 1) <> ''''   
          Set @DiagMProcAll = @DiagMProcAll + ''''   
      If isnull(@DiagnosisAll, '') = '' 
          Set @DiagnosisAll = '''XXX''' 
  
    --TICKET 8965
	If @DDisposition = '08'  
	  set @MCC = '99X'         
	Else if @DDisposition = '09'   
	Begin   
	  set @MCC = '99'
	  Set @FinalCMG = '997'
	  Set @CmgDesc = 'Stillbirth'
	End 
	Else If (@Weight = 0 and isnull(@AgeCode, 0) <> 1) or (@Weight <> 0 and isnull(@AgeCode, 0) > 1) 	
          SELECT Top 1 @MCC = [MCC], @MRDxCMG = [CMG], @BranchTemp = [MCCCode]  FROM CMG_Main2003   
          WHERE ([DiagProcCode]= @DiagMostResposible) AND ([Priority] = 3) AND (Gender = @Gender Or Gender = 3)   
	Else if @Weight < 200 
	Begin
	Set @MCC = '99'
	Set @FinalCMG = '999'
	End
	Else if @Weight < 750 AND @Weight >= 200
	Begin   
	  set @MCC = '15X'   
	  Set @FinalCMG = '625'   
	End   
	Else if @Weight < 1000   
	Begin   
	  set @MCC = '15X'   
	  Set @MRDxCMG = '626'   
	End   
	Else if @Weight < 1500   
	Begin   
	  set @MCC = '15X'   
	  Set @MRDxCMG = '628'   
	  Set @BranchTemp = 'MC15XM03MD'   
	End   
	Else if @Weight < 2000   
	Begin   
	  set @MCC = '15X'   
	  Set @MRDxCMG = '632'   
	  Set @BranchTemp = 'MC15XM04MD'   
	End   
	Else if @Weight < 2500   
	Begin   
	  set @MCC = '15X'   
	  Set @MRDxCMG = '640'   
	  Set @BranchTemp = 'MC15XM05MD'   
	End   
	Else if @Weight > 2499 AND @Weight < 9000
	Begin   
	  set @MCC = '15X'   
	  Set @MRDxCMG = '648'   
	  Set @BranchTemp = 'MC15XM06MD'   
	End
	Else if @Weight > 8999 
	Begin
	Set @MCC = '99'
	Set @FinalCMG = '999'
	End
      If (@BranchTemp in ('MC19XM01MD', 'MC19XM02MD', 'MC19XM05MD') and @LOS < 6 and (@DDisposition = '05' or (@IsAcuteTo = 0 or @IsAcuteFrom = 0)) and @DDisposition not in ('06', '07')
   and (@IsAcuteTo = 0 and @IsAcuteFrom = 0)) 
      Begin   
          Set @FinalCMG = @MRDxCMG + 1   
          Set @Branch = @BranchTemp   
      End   
      If left(@DiagMostResposible, 3) = 'Z53' and (@MCC <> '23' and len(@ProceduresAll) = 0)--modified 2006/02/27
      Begin 
      Set @FinalCMG = @MRDxCMG  
      Set @FinalMCCCode = @BranchTemp         
      End 
  
      If @DDisposition = '08' 
      Begin 
      set @FinalCMG = 996 
      End 

      If @FinalCMG is NULL   
      Begin   
          Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
          WHERE DiagProcCode in (' + @ProceduresAll + ') AND MCC = ''' + @MCC + ''' AND Priority < 3 ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
           @Branch output, @BranchCMG Output, @CMGProc Output
          Set @Partition = SUBSTRING(@Branch, 7, 2)   
          If isnull(@Branch, '0') = '0' and @MCC = '18X' and isnull(@Procedure1, '0') <> '0'   
          begin   

              Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
              WHERE DiagProcCode in (' + @ProceduresAll + ')  and translatefrom like ''appdh%'' ORDER BY SortOrder'   

              exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
           @Branch output, @BranchCMG Output, @CMGProc Output
              If isnull(@Branch, '0') <> '0'   
              begin   
                  Set @Branch = 'MC18XS02PR'   
                  Set @BranchCMG = '750'   
              end   
          end   
          Else If isnull(@Branch, '0') = '0' and @MCC = '17A' and isnull(@Procedure1, '0') <> '0'   
          begin   
              Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
              WHERE DiagProcCode in (' + @ProceduresAll + ') and translatefrom like ''appdh%'' ORDER BY SortOrder'   
              exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output',
           @Branch output, @BranchCMG Output, @CMGProc Output
   
              If isnull(@Branch, '0') <> '0'   
              begin   
              Set @Branch = Null 
              Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
              WHERE DiagProcCode in (' + @DiagMProcAll + ') AND MCCCode = ''MC17AS03MDL01'' ORDER BY SortOrder'   
              exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
                   @Branch output, @BranchCMG Output, @CMGProc Output
    
              If isnull(@Branch, '0') = '0'   
              begin   
                      Set @FinalMCCCode = 'MC17AS03PR'   
                      Set @FinalCMG = '728'   
              End 
              end   
          end   
          Else If isnull(@Branch, '0') = '0' and @MCC = '17B' and isnull(@Procedure1, '0') <> '0'   
          begin   
              Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
              WHERE DiagProcCode in (' + @ProceduresAll + ') and translatefrom like ''appdh%'' ORDER BY SortOrder'   
              exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', 
           @Branch output, @BranchCMG Output, @CMGProc Output
              If isnull(@Branch, '0') <> '0'   
              begin   
                  Set @FinalCMG = '734'   
                  Set @BranchCMG = '734'   
              end   
          end   
          Else if @MCC = '05A' and (@Partition = '06' or @Partition = '07') and SUBSTRING(@Branch, 5, 2) = 'AS'   
          Begin   
              SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003    
              WHERE DiagProcCode = (@DiagMostResposible) AND MCC = @MCC AND (Partition = @Partition) AND Priority = 4 and SUBSTRING(MCCCode, 5, 2)= 'AS' ORDER BY SortOrder   
              If @FinalCMG is null   
              Begin   
                  If @BranchCMG is null   
                      Set @FinalCMG = @MRDxCMG   
                  Else   
                      Set @FinalCMG = @BranchCMG   
              End   
          End   
          else If isnull(@Branch, '0') = '0'   
              Set @Branch = @BranchTemp   
          Set @Partition = SUBSTRING(@Branch, 7, 2)   
   if isnull(@FinalSubBranch, '') = ''
   Begin
              Set @SQL = 'SELECT Top 1 @FinalSubBranch = MedicalSurgical FROM CMG_Main2003   WHERE MCCCode = ''' + @Branch + ''''   
              exec sp_executesql @sql, N'@FinalSubBranch VarChar(1) output', @FinalSubBranch output
       if isnull(@FinalSubBranch, '') = ''
           Set @FinalSubBranch = '2'
   end
      End   
  
      If @MCC = '15X'   
      Begin   
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003              WHERE DiagProcCode in (' + @DiagMProcAll + ') AND (MCC = ''' + @MCC + ''')    


          AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
      End   
      Else If @MCC = '13X'   
      Begin   
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE DiagProcCode in (' + @DiagMProc + ') AND (MCC = ''' + @MCC + ''')    
          AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
      End   
      Else If @MCC = '24X'   
      Begin
         Declare @MCC24X as Varchar(10)
         If CHARINDEX(',', @DiagnosisAll) > 0
           set @MCC24X = left(@DiagnosisAll, CHARINDEX(',', @DiagnosisAll) - 1 )
	 Else if Len(@DiagnosisAll) > 0
           set @MCC24X = @DiagnosisAll

         Set @FinalCMG = Null
         If CHARINDEX(@MCC24X, @DiagTyped1 + ' ' + @DiagTyped2) > 0
         Begin
           Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2002    
           WHERE DiagProcCode in (' + @MCC24X + ') AND MCC = ''' + @MCC + '''     
           AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
         End

         If @FinalCMG is Null and CHARINDEX(@MCC24X, @DiagTyped1 + ' ' + @DiagTyped2) > 0
		Set @FinalCMG = '868'
	 Else If CHARINDEX(@MCC24X, @DiagTyped1 + ' ' + @DiagTyped2) = 0
         Begin   
           Set @FinalCMG = '999'   
           Set @FinalMCCCode = 'MC99XM01MD'   
           Set @MCC = '99'   
         End   
      End
      Else If @FinalCMG is null and @BranchCMG is not null and @MCC not in ('05A', '08X', '10X') 
      Begin 
   Declare @ProcTemp as VarChar(15) 
          set @FinalCMGTemp = @BranchCMG   
     Set @ProcTemp = @CMGProc 
     Set @BranchTemp = @BranchCMG 
          Set @BranchCMG = Null   
   
          Set @SQL = 'SELECT Top 1 @Branch = MCCCode, @BranchCMG = CMG, @CMGProc = DiagProcCode FROM CMG_Main2003    
          WHERE DiagProcCode in (' + @ProceduresAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
          AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@Branch VarChar(10) output, @BranchCMG VarChar(14) output, @CMGProc VarChar(14) output', @Branch output, @BranchCMG Output, @CMGProc Output   
   If @BranchCMG is null 
           Begin 
              Set @FinalCMG = @FinalCMGTemp 
              Set @FinalMCCCode = @BranchTemp 
              Set @CMGProc = @ProcTemp 
           End 
   Else 
           Begin 
              Set @FinalCMG = @BranchCMG 
              Set @FinalMCCCode = @Branch 
           End 
      End 
      Else If @FinalCMG is null   
      Begin   
	If  @mcc = '23X' and @ProceduresAll = '''XXX'''
	   Set @SQL = ''
	Else
           Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003    
           WHERE DiagProcCode in (' + @DiagMProcAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
           AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
       End   
   
    If @MCC = '05A' and (@Partition Between '03' and '15') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02'   
      Begin   
          declare @Diag05 as VarChar(1000) 
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   
   
          set @Diag05 = replace(@DiagMProcAll, replace(replace(Replace(substring(@DiagTypeAll, charindex('|3', @DiagTypeAll) -5, 6), '|', ''), ' ', ''), '''', ''), 'xxx') 
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE (DiagProcCode) in (' + @Diag05 + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
          AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch +  ''' and SortOrder > 6 ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
      
          If @FinalCMG is Null   
              Set @FinalCMG = @FinalCMGTemp   
      End   
      --New 2002/09/20  
      Else If (@MCC = '05A' and (@Partition Between '19' and '21')) or (@MCC = '04X' and (@Partition Between '09' and '11')) or (@MCC = '01X' and (@Partition Between '09' and '11'))  
       or (@MCC = '06X' and (@Partition Between '19' and '21')) or (@MCC = '08X' and (@Partition Between '27' and '29')) or (@MCC = '11X' and (@Partition Between '17' and '19'))  
       or (@MCC = '05B' and (@Partition Between '12' and '14')) 
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 ORDER BY SortOrder'    
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
     
          If @FinalCMG is Null and isnull(@FinalCMGTemp, '0')  = '902' 
   	Begin 
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003    
  
             WHERE DiagProcCode in (' + @ProceduresAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
             AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
	   End 
	   Else If @FinalCMG is Null 
              Set @FinalCMG = @FinalCMGTemp    
      End    
      Else If @MCC = '05A' and (@Partition Between '03' and '15') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) <> 'L02'   
          Set @FinalCMG = Null   
      Else If (@MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02' AND (@LOS >= 4)) or    
          ((@MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02') and (@DDisposition in ('07', '06') or @IsAcuteTo = 1 or @IsAcutefrom = 1))   
      Begin   
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003    
          WHERE (DiagProcCode) in (' + @DiagMProcAll + ') AND MCC = ''' + @MCC + ''' AND (Partition = ''' + @Partition + ''')    
          AND Priority = 4 and MedicalSurgical = ''' + @FinalSubBranch + ''' and SortOrder > 2 ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
          If @FinalCMG is Null   
              Set @FinalCMG = @FinalCMGTemp   
          else if @Partition = '01'   
              Set @FinalCMG = @FinalCMG - 4              else   
              Set @FinalCMG = @FinalCMG - 2   
      end   
      Else If @MCC = '05A' and (@Partition Between '01' and '02') and SUBSTRING(@FinalMCCCode, 5, 2) <> 'AS' and right(@FinalMCCCode, 3) = 'L02' And @LOS < 4   
          Set @FinalCMG = '218'   
      Else if @MCC = '05A' and (@Partition = '03' or @Partition = '04' or @Partition = '05')   
      Begin   
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
             
          If @FinalCMG is Null   
              Set @FinalCMG = @FinalCMGTemp   
          If @FinalCMG in ('176', '178', '181')   
              Set @FinalCMG = '183'   
          Else If @FinalCMG in ('177', '179', '182')   
          Begin   
              set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
              AND MCCCode = ''MC05AS' + @Partition + 'NPL02'''   
              exec sp_executesql @sql, N'@count int output', @Count output   
              If isnull(@Count, 0) > 0   
                  Set @FinalCMG = @FinalCMG - 1   
          End   
      end   
      Else if @MCC = '05A' and @Partition = '10' and (@FinalCMG = '181' or @FinalCMG = '182')   
      Begin  
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   
	If @FinalCMGTemp = '182'
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND sortorder = 2 AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
	else
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND sortorder = 1 AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   

          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
             
          If @FinalCMG is Null and @FinalCMGTemp = '182'
              Set @FinalCMG = '182' 
          else If @FinalCMG is Null and @FinalCMGTemp = '181'
              Set @FinalCMG = '194'   
      End   
      --New 2002/09/19  
      Else If @MCC = '06X' and (@Partition = '12')  
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = @FinalCMGTemp    
      End    
      --New 2002/09/24  
      Else If ((@MCC = '08X' and (@Partition in ('04', '05', '07'))) or (@MCC = '21X' and (@Partition in ('08', '10'))) or 
           (@MCC = '23X' and (@Partition in ('02', '04')))) and @FinalCMG in ('350', '354')
      Begin    
          set @FinalCMG = NULL  
          Declare @MC08Count as int 
	  set @MC08Count = 0

	Declare @TempProcString as varchar(1000)
	Declare @TempProcString2 as varchar(1000)
	Declare @MultiReplaceCountTemp as int
	
	set @TempProcString = @ProceduresAll
	
	While len(@TempProcString) > 1
	Begin
		set @MultiReplaceCountTemp = 0
		if CHARINDEX ( ',' , @TempProcString, CHARINDEX(', ',@TempProcString)+1  ) > 1
			set @TempProcString2 = substring(@TempProcString,0, CHARINDEX ( ',' , @TempProcString, CHARINDEX(', ',@TempProcString  )+1))
		else
			set @TempProcString2 = @TempProcString

		--Ticket 10639
		If @MCC = '21X'
	          set @SQL = 'SELECT @MultiReplaceCountTemp = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @TempProcString2 + '))    
	          AND MCCCode = ''MC' + left(@mcc, 2) + 'XS' + @Partition + 'PRL03''' 
		Else
	          set @SQL = 'SELECT @MultiReplaceCountTemp = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @TempProcString2 + '))    
	          AND MCCCode = ''MC' + left(@mcc, 2) + 'XS' + @Partition + 'PRL01''' 

	          exec sp_executesql @sql, N'@MultiReplaceCountTemp int output', @MultiReplaceCountTemp output
  		if @MultiReplaceCountTemp > 0
			set @MC08Count = @MC08Count + 1
		set @TempProcString = right(@TempProcString, len(@TempProcString)-len(@TempProcString2))
		if len(@TempProcString) > 4
			set @TempProcString = right(@TempProcString, len(@TempProcString) - 2)
		else
			Set @TempProcString = ''
	End
   
          If isnull(@MC08Count, 0) > 1 and len(@ProceduresAll) > 30 
             Set @FinalCMG = 350    
          Else  
          Begin  
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
             WHERE ((DiagProcCode) in (' + @DiagMProcAll + ')) 
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and SortOrder > 1 ORDER BY SortOrder'    
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          End  
   
          If @FinalCMG is Null    
     Begin
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
             WHERE ((DiagProcCode) in (' + @DiagMProcAll + ')) 
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 2 ORDER BY SortOrder'    
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
     End
      End    
      Else If @MCC = '08X' and (@Partition between '10' and '25') and SUBSTRING(@Branch, 6, 1) = 'S' 
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = @FinalCMGTemp    
      End    
      --New 2002/09/19  
      Else If @MCC = '09X'  
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = @FinalCMGTemp    

	  If @FinalCMG = '438'
	  Begin
	          set @FinalCMGTemp = @FinalCMG    
	          Set @FinalCMG = Null    
	
	          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
	          WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
	           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
	          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = '437'    
	  End
	  --Ticket 10302
	  If @FinalCMG = '427'
	  Begin
	          set @FinalCMGTemp = @FinalCMG    
	          Set @FinalCMG = Null    
	
	          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
	          WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
	           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
	          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = '425'    
	  End
      End    
      Else If @MCC = '10X' and @Partition = '01' and SUBSTRING(@FinalMCCCode, 5, 2) = 'XS' 
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
          WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
              Set @FinalCMG = @FinalCMGTemp    
      End    
      --New 2002/09/25  
      Else If @MCC = '19X' and (@FinalCMG not in ('771', '778', '767')) and @FinalCMG is not null 
      Begin    
          set @FinalCMGTemp = @FinalCMG    
          Set @FinalCMG = Null    
          Declare @LenDiag as int 
          Declare @Diag19X as NVarChar(3000) 
          set @LenDiag = len(@DiagMProcAll) - len(@DiagMostResposible) - 4 
          If @LenDiag < 0 
          Begin 

             Set @LenDiag = 0 
             Set @Diag19X = '''''' 
          End 
          Else 
             Set @Diag19X = right(@DiagMProcAll, @LenDiag) 
          set @Diag19X = replace(@Diag19X, replace(replace(Replace(substring(@DiagTypeAll, charindex('|3', @DiagTypeAll) -5, 6), '|', ''), ' ', ''), '''', ''), 'xxx') 
     If right(@Diag19X, 1) = ',' 
           set @Diag19X = left(@Diag19X, len(@Diag19X)-1)

     If right(@Diag19X, 1) <> '''' 
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
             WHERE ((DiagProcCode) in (' + @Diag19X + '''))    
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    
     Else
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
             WHERE ((DiagProcCode) in (' + @Diag19X + '))    
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and SortOrder > 0 ORDER BY SortOrder'    

          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          If @FinalCMG is Null    
          Begin  
             Set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003   
             WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
              AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 1 ORDER BY SortOrder'    
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output    
          End  
      End   
    Else If @MCC = '11X' and (@Partition = '01') and right(@FinalMCCCode, 3) = 'L01' 
      Begin	
	If @LOS > 2 or @DDisposition in ('06','07') or @isAcuteTo = 1 or @isAcuteFrom = 1
		Set @FinalCMG = '520'	
	Else if @LOS < 3 AND @isAcuteTo = 0 and @isAcuteFrom = 0
		Set @FinalCMG = '999'	
      End  
      Else if @MCC = '13X' and @FinalMCCCode like 'MC13XS04%'   
      Begin   
          If @FinalMCCCode = 'MC13XS04PRL02'   
          Begin   
              set @FinalCMGTemp = @FinalCMG   
              Set @FinalCMG = Null   
              set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProc + '))    
              AND MCCCode in (''MC13XS04MDL03'', ''MC13XS04PRL04'') ORDER BY SortOrder'   
              exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
      
              If @FinalCMG is Null   
                  Set @FinalCMG = '579'   
          End   
          Else If @FinalMCCCode = 'MC13XS04MDL01'   
          Begin   
              set @FinalCMGTemp = @FinalCMG   
              Set @FinalCMG = Null   
              set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProc + '))    
              AND MCCCode = ''MC13XS04PRL02'''   
              exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
   
              If @FinalCMG is Null   
                  Set @FinalCMG = @FinalCMGTemp   
          End   
          If @FinalMCCCode = 'MC13XS04MDL03'   
          Begin   
              set @FinalCMGTemp = @FinalCMG   
              Set @FinalCMG = Null   
              set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProc + '))    
              AND MCCCode = ''MC13XS04PRL04'''   
              exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
                 
              If @FinalCMG is Null   
                  Set @FinalCMG = @FinalCMGTemp   
          End   
          Else If @FinalMCCCode = 'MC13XS04PRL04'   
              Set @FinalCMG = '579'   
      end   
      Else If (@MCC = '14X' and (@Partition = '05')) And (@LOS >= 3 or @IsAcuteTo = 1 or @IsAcuteFrom = 1) 
          Set @FinalCMG = '599'   
      Else If @MCC = '14X' and (@Partition = '01') and @FinalSubBranch = 1 and ((@FinalCMG = '612' or (@FinalCMG is null and @MRDxCMG = '612')))
      Begin   
          Set @FinalCMG = Null   
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
          SortOrder = 1 ORDER BY SortOrder' 
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
          If @FinalCMG is Null   
              Set @FinalCMG = 600   
      end   
      Else If @MCC = '15X' and (@Partition Between '03' and '06') and right(@FinalMCCCode, 3) = 'L01'  And @DDisposition in ('04', '05') And @LOS < 6   
          Set @FinalCMG = 998   
--Added on Ticket 9161
      Else If @MCC= '15X' and (@Partition Between '03' and '06') and right(@FinalMCCCode, 3) = 'L01' and (@DDisposition in ('07', '06') or @IsAcuteTo = 1 or @IsAcutefrom = 1 or @LOS > 6) 
      Begin

	  If @Partition = '03'
          	Set @FinalCMG = 627  
	  If @Partition = '04'
          	Set @FinalCMG = 630  
	  If @Partition = '05'
          	Set @FinalCMG = 636  
	  If @Partition = '06'
          	Set @FinalCMG = 643  
      End
      Else If @MCC = '15X' and (@Partition in ('06', '05')) and ((@FinalCMG = '646' or (@FinalCMG is null and @MRDxCMG = '646')) or 
      (@FinalCMG = '647' or (@FinalCMG is null and @MRDxCMG = '647')) or (@FinalCMG = '648' or (@FinalCMG is null and @MRDxCMG = '648'))
      or (@FinalCMG = '639' or (@FinalCMG is null and @MRDxCMG = '639'))or (@FinalCMG = '640' or (@FinalCMG is null and @MRDxCMG = '640')))
      Begin   
          Set @FinalCMG = Null   
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE (((DiagProcCode) in (' + @DiagMProcAll  + ')) or
	  ((DiagProcCode) in (''''' + @DiagTyped0 + @DiagTyped3 + ')) and isnull(translatefrom, '''') = '''')
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
          SortOrder = 4 ORDER BY SortOrder' 
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
          If @FinalCMG is Null   
          Begin
           set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
           AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
           SortOrder > 4 ORDER BY SortOrder' 
           exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
           If @FinalCMG is Null and @MRDxCMG in ('646', '647', '648')
               Set @FinalCMG = 648   
           Else If @FinalCMG is Null and @MRDxCMG in ('639', '640')
               Set @FinalCMG = 640   
      	  End
      end 
      Else If @MCC = '14X' and (@Partition = '02')-- and right(@FinalMCCCode, 3) = 'L01'   
      Begin   
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   
          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (''' + @DiagMostResposible + '''))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
          SortOrder = 1 ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
             
          If @FinalCMG is Null   
              Set @FinalCMG = @FinalCMGTemp   
          Else  
          Begin  
             set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
             AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' and    
             SortOrder > 1 ORDER BY SortOrder'   
             exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   
  
             If @FinalCMG is Null   
                 Set @FinalCMG = @FinalCMGTemp   
             If @FinalCMG = '601'   
                 Set @FinalCMG = '603'   
             Else If @FinalCMG in ('602', '604')
             Begin   
                 set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + @DiagTyped3 + '))    
                 AND MCCCode = ''MC14XS02MOL03'''   
                 exec sp_executesql @sql, N'@count int output', @Count output   
                 If isnull(@Count, 0) > 0   
                     Set @FinalCMG = @FinalCMG - 1   
             End   
      End  
      end   
      Else If @MCC = '14X' and (@Partition = '02') and right(@FinalMCCCode, 3) <> 'L01' and SUBSTRING(@FinalMCCCode, 5, 2) <>  'XM'   
          Set @FinalCMG = 999   
     Else If @MCC = '14X' and (@FinalCMG Between '608' and '611' or (@FinalCMG is null and @MRDxCMG Between '608' and '611'))--(@FinalCMG = '608' or @FinalCMG = '609')   
     Begin   
         If @FinalCMG = '608'   
             Set @FinalCMG = '610'   
         Else 
         Begin   
             set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + @DiagTyped3 +  '))    
             AND MCCCode = ''MC14XM01MOL04'''  
             exec sp_executesql @sql, N'@count int output', @Count output  
             If isnull(@Count, 0) > 0 and @FinalCMG is not null
                 Set @FinalCMG = @FinalCMG - 1   
             Else If isnull(@Count, 0) > 0 and @FinalCMG is null
                 Set @FinalCMG = @MRDxCMG - 1   
         End   
     End   
      Else If @MCC = '14X' and (@FinalCMG in ('620', '621'))   
      Begin   
          If @FinalCMG = '621'   
          Begin   
              set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagnosisAll + '))    
              AND MCCCode = ''MC14XM06PRL10'''   
              exec sp_executesql @sql, N'@count int output', @Count output   
              If isnull(@Count, 0) > 0   
                  Set @FinalCMG = @FinalCMG - 1   
          End   
      end   
      Else if @MCC = '21X' and (@Partition in ('05', '06'))   
      Begin   
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   

          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   

          If @FinalCMG is Null 
              Set @FinalCMG = @FinalCMGTemp  
          If @FinalCMG in ('176', '178', '181')   
              Set @FinalCMG = '183'   
          Else If @FinalCMG in ('177', '179', '182')   
          Begin  

              set @SQL = 'SELECT @Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
              AND MCCCode = ''MC21XS' + @Partition + 'NPL02'''   
              exec sp_executesql @sql, N'@count int output', @Count output   
              If isnull(@Count, 0) > 0   
                  Set @FinalCMG = @FinalCMG - 1   
          End   
      end   
      Else if @MCC = '22X' and (@Partition in ('01', '02')) --Ticket 9698
      Begin   
          set @FinalCMGTemp = @FinalCMG   
          Set @FinalCMG = Null   

          set @SQL = 'SELECT Top 1 @FinalCMG = CMG, @FinalMCCCode = MCCCode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @DiagMProcAll + '))    
          AND (MCC = ''' + @MCC + ''') AND (Partition = ''' + @Partition + ''') AND Priority = 4 and MedicalSurgical =  ''' + @FinalSubBranch + ''' ORDER BY SortOrder'   
          exec sp_executesql @sql, N'@FinalCMG VarChar(3) output, @FinalMCCCode VarChar(14) output', @FinalCMG output, @FinalMCCCode Output   

          If @FinalCMG is Null 
              Set @FinalCMG = @FinalCMGTemp  
      end 
      Else If @MCC = '25X' and SUBSTRING(@Branch, 6, 1) = 'S' and SUBSTRING(@Branch, 7, 2) = '05' and @FinalCMG in ('351', '350') 
      Begin
   	Declare @MC25Proc as VarChar(15) 
  	Declare @MC25Count as int   
          If @FinalCMG = 350   
   	  Begin 
              set @SQL = 'SELECT @MC25Count = count(*) FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @ProceduresAll + '))    
              AND MCCCode = ''MC25XS05PRL03'''   
              exec sp_executesql @sql, N'@MC25Count int output', @MC25Count output   
           If @MC25Count = 1 
           Begin
                   set @SQL = 'SELECT  @MC25Proc = diagproccode FROM CMG_Main2003 WHERE ((DiagProcCode) in (' + @ProceduresAll + '))    
                   AND MCCCode = ''MC25XS05PRL03'''   
                   exec sp_executesql @sql, N'@MC25Proc varchar(15) output', @MC25Proc output                   
  
                  If len(replace(@ProceduresAll, '''' + @MC25Proc + '''', '')) < (len(@ProceduresAll) - len(@MC25Proc) - 3)
                           Set @MC25Count = 2 
           End
   End 
   
          If isnull(@MC25Count, 0) < 2   
              Set @FinalCMG = 351   
      End   

      if len(@FinalMCCCode) > 10   
          Set @Branch = left(isnull(@FinalMCCCode, ''), 10)   

      If @FinalCMG is null   
      Begin   
          If @BranchCMG is null   
              Set @FinalCMG = @MRDxCMG   
          Else   
              Set @FinalCMG = @BranchCMG   
          If @FinalCMG is null 
               Set @FinalCMG = '999'   
      End   

      --Ticket 9330
      If @MCC is null
	set @MCC = '99'
  
      if len(@FinalMCCCode) > 10   
          Set @Branch = left(isnull(@FinalMCCCode, ''), 10)  

      Declare @MedSurgInd as VarChar(1) 
      Declare @MedSurgNon as VarChar(1) 
      SELECT @MedSurgNon = cmgmcctype, @MedSurg = cmgmcctype, @MedSurgInd = RIWInd FROM CMG_Etc_2005T WHERE (cmgcode = @FinalCMG) and (ciagegroup = @AgeGroup)    

      Set @PlexA = 0   
      Set @PlexB = 0   
      Set @PlexC = 0   
      Set @PlexD = 0   
      Set @PlexP = 0   
      Set @PlexCMCC = 0   
      If exists (SELECT * FROM CMG_Etc_2005T WHERE ((cmgcode = @FinalCMG) AND (cicpxlvl = 9) and (ciagegroup = @AgeGroup)) or @MedSurg = '9') 
          set @Complexity = 9   
      Set @DiagTypeAll = replace(@DiagTypeAll, @DiagMostResposible + '|', 'XXXXX|')   

      if @Plx4 = 'Y' and isnull(@Complexity, '') <> '9'
	set @Complexity = 4  
      If isnull(@AbstractID, 0) > 0 and (CHARINDEX ('1GZ31CAND', @ProceduresAll ) > 0 or CHARINDEX ('1GZ31CRND', @ProceduresAll ) > 0)
   and @Complexity is null
      Begin   
	   if exists (SELECT dbo.AB_Intervention.AbstractID FROM dbo.AB_Intervention LEFT OUTER JOIN
           dbo.ICD_ProcFile10 ON dbo.AB_Intervention.IntervCode = dbo.ICD_ProcFile10.Code LEFT OUTER JOIN
           dbo.LU_IntervAttExtent ON dbo.AB_Intervention.IntervAttribExtent = dbo.LU_IntervAttExtent.Code
           WHERE (dbo.LU_IntervAttExtent.CIHIValue IN ('EX')) AND (dbo.ICD_ProcFile10.CIHIValue  in ('1GZ31CAND', '1GZ31CRND')) AND (dbo.AB_Intervention.AbstractID = @AbstractID))
	   set @Complexity = 4  
      End

     --If there are duplicate diagnosis with the same type, take type 1
     Declare @DupDiagComplex as Varchar(20)
     set @SQL = 'SELECT top 1 @DupDiagComplex = diagnosis FROM CMG_Plx2002   
         WHERE DiagTypeCombine in (' + @DiagTypeAll + ')
 	AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''') 
 	And Diagnosis not in (SELECT DiagnosisEx FROM dbo.CMG_PlxException2001 WHERE (MCCEx = LEFT(''' + @MCC + ''',2)) AND (CMGEx = ''' + @FinalCMG + '''))
 	group by diagnosis having Count(diagnosis) > 1'   
     exec sp_executesql @sql, N'@DupDiagComplex VarChar(20) output', @DupDiagComplex output 

     If isnull(@DupDiagComplex, '') <> ''
    	Set @DiagTypeAll = replace(@DiagTypeAll, @DupDiagComplex + '|2', 'XXXXX|2')   

  
           Create TABLE #PlxTemp (PlCount int, Plex varchar(1))
  --Plex Levels
   set @SQL = 'SELECT count(*) as PlCount, substring(Plexity, cast(LEFT(''' + @MCC + ''',2) as int), 1) as Plex FROM CMG_Plx2003   
          WHERE DiagTypeCombine in (' + @DiagTypeAll + ')
   AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''') 
   And Diagnosis not in (SELECT DiagnosisEx FROM dbo.CMG_PlxException2003 WHERE (MCCEx = LEFT(''' + @MCC + ''',2)) AND (CMGEx = ''' + @FinalCMG + '''))
   group by substring(Plexity, cast(LEFT(''' + @MCC + ''',2) as int), 1)'   
   Insert into #PlxTemp Exec (@SQL)
  
      if @Complexity is null and @@Rowcount > 0   
      Begin  
  --Level C Not Home Plex
   set @SQL = 'SELECT @PlexCMCC = count(*) FROM CMG_Plx2003   
        WHERE DiagTypeCombine in (' + @DiagTypeAll + ') and substring(Plexity, cast(LEFT(''' + @MCC + ''',2) as int), 1) = ''C'' 
   and HomeMCC <> LEFT(''' + @MCC + ''',2)
   AND (MedSurg = ''' + Cast(@MedSurg as VarChar(1)) + ''') 
   And Diagnosis not in (SELECT DiagnosisEx FROM dbo.CMG_PlxException2003 WHERE (MCCEx = LEFT(''' + @MCC + ''',2)) AND (CMGEx = ''' + @FinalCMG + '''))'   
   exec sp_executesql @sql, N'@PlexCMCC VarChar(1) output', @PlexCMCC output   
   Set @PlexA = isnull((select PlCount from #PlxTemp where Plex = 'A'), 0)
   Set @PlexB = isnull((select PlCount from #PlxTemp where Plex = 'B'), 0)
   Set @PlexC = isnull((select PlCount from #PlxTemp where Plex = 'C'), 0)
   Set @PlexD = isnull((select PlCount from #PlxTemp where Plex = 'D'), 0)
   Set @PlexP = isnull((select PlCount from #PlxTemp where Plex = 'P'), 0)
   If @PlexCMCC > 1
           Set @PlexCMCC = 1
  
          If @PlexA > 0 or @PlexB > 1 or (@PlexB = 1 and @PlexC > 0 and @PlexCMCC = 1)   
              Set @Complexity = 4   
          Else If @PlexB > 0 or (@PlexC > 1 and @PlexCMCC = 1) or (@PlexC > 10 and @PlexCMCC = 0)   
              Set @Complexity = 3   
          Else If @PlexD > 0 or @PlexP > 0 or (@PlexC = 1 and @PlexCMCC = 1)    
              or (@PlexC > 0 and @PlexC < 11 and @PlexCMCC = 0)   
              Set @Complexity = 2   
          Else   
              Set @Complexity = 1   
      End   

      If isnull(@Complexity, '') = ''   
          Set @Complexity = 1   
      
      Set @MCC = Replace(@MCC, 'X', '')   
      Set @ComplexityLevel = @Complexity   
      SELECT Top 1 @CmgDesc = cmgdesc, @CmgTrim = ciagtrim, @CmgELOS = ciagelos, @CmgPDRA = ciagpdra, @CmgPDWGT = ciagpdwgt, @CmgRIW = ciagriw   
      FROM dbo.CMG_Etc_2005T WHERE (cmgcode = @FinalCMG) AND (cicpxlvl = @ComplexityLevel) AND (ciagegroup = @AgeGroup) --AND (cmgmcctype = @MedSurg)  
  --print @CmgDesc 
  --print @CmgTrim 
  --print @CmgELOS 
  --print @CmgPDRA 
  

   --New 2002/09/30 
      If @MedSurg = 9 
      Set @MedSurg = 1   
      If @FinalCMG in ('910', '912', '998', '999') and @LOS < cast(@CMGELOS as decimal(7,4))   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      Else If @FinalCMG in ('910', '912', '998', '999') and @LOS >= cast(@CMGELOS as decimal(7,4))   
          Set @CMGRIW = @CmgRIW
      else if @DDisposition = '07' and @LOS <= @CMGTrim and @LOS <= 10   
      Begin   
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer    
              WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr is null and dxyear = 2005)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      else if @DDisposition = '07' and @LOS <= @CMGTrim and @LOS > 10   
      Begin 
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
              WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr is null and dxyear = 2005)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   

      Else If @DDisposition = '06' and @LOS <= cast(@CMGELOS as decimal(7,4))   
          Set @CMGRIW = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,4))) as decimal(7,4))   
      Else If @DDisposition = '06' and @LOS > cast(@CMGELOS as decimal(7,4)) and @LOS <= @CMGTrim   
          Set @CMGRIW = cast((cast(@CmgPDWGT as decimal(7,4)) * cast(@CmgELOS as decimal(7,4))) as decimal(7,4))   
      Else If @IsAcuteTo = 1 and @LOS <= 10 and @LOS <= @CMGTrim   
      Begin   
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
              WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='O' and dxyear = 2005)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      Else If @IsAcuteTo = 1 and @LOS > 10 and @LOS <= @CMGTrim   
      Begin   
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
              WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='O' and dxyear = 2005)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      Else If @IsAcuteFrom = 1 and @LOS <= 10 and @LOS <= @CMGTrim   
      Begin   
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
              WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='I' and dxyear = 2005)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      Else If @IsAcuteFrom = 1 and @LOS > 10 and @LOS <= @CMGTrim   
      Begin   
          Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer   
              WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgInd) AND (PlxLevel = @ComplexityLevel) and cmgxfr ='I' and dxyear = 2005)   
          Set @CMGRIW = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@RIWDeath as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
      End   
      Else If @LOS > @CMGTrim   
          Set @CMGRIW = cast(cast(@CMGRIW as decimal(7,4)) + (cast(@CmgPDRA as decimal(7,4)) * cast((cast(@LOS as decimal(7,2)) - cast(@CmgELOS as decimal(7,4))) as decimal(9,4))) as decimal(9,4))   

      Declare @CMGNon as int
      Select @CMGNon = CMGNonValue from CMG_NonBool where CMGNonYear = 2006
      if @CmgRIW is not null and isnull(@CMGNon, 0) = 0
      Begin  
          Select @RIW$ = CostPerRiw from H_InstitutionProfile where code = @InstNumber   
          if isnull(@RIW$, '0') = '0' or @RIW$ = ''   
              set @RIW$ = '0'   
          Set @CMGRIW$ = cast(@CmgRIW as decimal(7,4)) * cast(@RIW$ as decimal(6,2))   
          if @LOS - @CMGTrim > 0   
          Begin   
              Set @CMGMOH = left(@CMGRIW + (((@LOS - @CMGTrim) * cast(@CmgPDWGT as Decimal(7,4))) + (((cast(@CMGTrim as int) - cast(@CMGELOS as decimal(6,2))) * cast(@CmgPDWGT as Decimal(7,4)))) * .2), 10)   
              Set @CMGMOH$ = cast(@CmgMOH as decimal(9,4)) * cast(@RIW$ as decimal(6,2))   
          end   
          Else   
          Begin   
              Set @CMGMOH = @CMGRIW   
              Set @CMGMOH$ = @CMGRIW$   
          end   
          Set @CMGMOH = cast(@CMGMOH as decimal(8,4))   
          Set @CMGRIW$ = cast(@CMGRIW$ as decimal(10,2))   
          Set @CMGMOH$ = cast(@CMGMOH$ as decimal(10,2))   
      End
--If they have rights to non complex grouper do this
     else if @CmgRIW is not null and exists(select code from H_HospitalProfile where code + @CMGNon = 33101) --PR - 00945
     Begin
		declare @IsAcuteFromNon as bit
		declare @IsAcuteToNon as bit
		set @IsAcuteFromNon = @IsAcuteFrom
		Set @IsAcuteToNon = @IsAcuteTo
		if @IsAcuteFromNon = 0
		Begin
			If exists(select code FROM LU_Institution_10 WHERE code = @InstFrom and CIHIValue in ('53240', '53310', '53459', '53781', '53913'))
				set @IsAcuteFromNon = 1
		End
		If @IsAcuteToNon = 0
		Begin
			If exists(select code FROM LU_Institution_10 WHERE code = @InstTo and CIHIValue in ('53240', '53310', '53459', '53781', '53913'))
				set @IsAcuteToNon = 1
		End

          Select @RIW$ = CostPerRiw from H_InstitutionProfile where code = @InstNumber   
          if isnull(@RIW$, '0') = '0' or @RIW$ = ''   
              set @RIW$ = '0'   
          Set @CMGRIW$ = cast(@CmgRIW as decimal(7,4)) * cast(@RIW$ as decimal(6,2))   
	     Declare @MedSurgIndHold as VarChar(1)
	     If @Complexity = 9
	     Begin
		Set @MedSurgIndHold = @MedSurgInd
		Set @MedSurgInd = 9
	     End
	     Declare @CmgNonELOS as decimal(10, 4)
	     Declare @CmgNonTrim as decimal(10, 4)
        --ED - 01593
        declare @DDate datetime
        if @AbstractID > 0
            set @DDate = (select top 1 DischargeDate from AB_Abstract where AbstractID = @AbstractID)

        --ED - 02057 add 2009 PAC10
        set @CmgNonTrim = null
        if isnull(@DDate, '1950/01/01') > '2009/03/31'
	        SELECT Top 1 @CmgNonTrim = ciagtrim, @CmgNonELOS = ciagelos, @CmgPDRA = ciagpdra, @CmgPDWGT = ciagpdwgt, @CMGMOH = ciagriw   
	        FROM dbo.CMG_ETC_2008_Non WHERE (cmgcode = @FinalCMG) AND (ciagegroup = @AgeGroup) and (ICDType = 'T') --AND (cmgmcctype = @MedSurg)   
        if isnull(@DDate, '1950/01/01') > '2007/03/31' and @CmgNonTrim is null
	        SELECT Top 1 @CmgNonTrim = ciagtrim, @CmgNonELOS = ciagelos, @CmgPDRA = ciagpdra, @CmgPDWGT = ciagpdwgt, @CMGMOH = ciagriw   
	        FROM dbo.CMG_ETC_2007_Non WHERE (cmgcode = @FinalCMG) AND (ciagegroup = @AgeGroup) and (ICDType = 'T') --AND (cmgmcctype = @MedSurg)   
        if @CmgNonTrim is null or isnull(@DDate, '1950/01/01') < '2007/04/01' 
	        SELECT Top 1 @CmgNonTrim = ciagtrim, @CmgNonELOS = ciagelos, @CmgPDRA = ciagpdra, @CmgPDWGT = ciagpdwgt, @CMGMOH = ciagriw   
	        FROM dbo.CMG_ETC_2006_Non WHERE (cmgcode = @FinalCMG) AND (ciagegroup = @AgeGroup) and (ICDType = 'T') --AND (cmgmcctype = @MedSurg)   

	     --SELECT @CmgNonTrim, @CmgNonELOS, @CmgPDRA, @CmgPDWGT, @CMGMOH, @MedSurg, @MedSurgNon, @IsAcuteFromNon, @IsAcuteToNon, @RIWDeath

        --ED - 01724
        declare @dxYear int
        set @dxYear = 2006
        if isnull(@DDate, '1950/01/01') > '2009/03/31' and exists (select top 1 * from dbo.CMG_DeathXfer_non where dxyear = 2008)
            set @dxYear = 2008
        else if isnull(@DDate, '1950/01/01') > '2007/03/31' and exists (select top 1 * from dbo.CMG_DeathXfer_non where dxyear = 2007)
            set @dxYear = 2007

	     If @MedSurg = 9 
	 	Set @MedSurg = 1   
        -- PR - 03046 I don't know why Troy do this way. 
--		if @MedSurgNon = 3
--			set @MedSurgNon = 2
		 --ED - 02057
	     If @FinalCMG in ('910', '912', '998', '999') and @LOS < cast(@CmgNonELOS as decimal(7,4))   
	         Set @CMGMOH = cast(cast(@CmgPDRA as decimal(7,5)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     --If @FinalCMG in ('910', '912', '998', '999') --ED - 01593 and @LOS < cast(@CmgNonELOS as decimal(7,4))   
	     --    Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,4)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   

	     else if @DDisposition = '07' and @LOS <= @CmgNonTrim  and @LOS <= 10   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non    
	             WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and isnull(cmgxfr, '') = '' and dxyear = @dxYear)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,5)) * cast(@RIWDeath as decimal(7,5)) * cast(@LOS as decimal(7,2)) as decimal(7,4))
    	     End   
	     else if @DDisposition = '07' and @LOS <= @CmgNonTrim and @LOS > 10    --ignore the change ED - 01593 @LOS <= @CmgNonTrim 
	     Begin 
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non  
	             WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and isnull(cmgxfr, '') = '' and dxyear = @dxYear)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,5)) * cast(@RIWDeath as decimal(7,5)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @DDisposition = '06' and @LOS <= cast(@CmgNonELOS as decimal(7,5))   
	         Set @CMGMOH = cast((cast(@CmgPDWGT as decimal(7,5)) * cast(@LOS as decimal(7,5))) as decimal(7,4))   
	     Else If @DDisposition = '06' and @LOS > cast(@CmgNonELOS as decimal(7,5)) and @LOS <= @CmgNonTrim   
	         Set @CMGMOH = cast((cast(@CmgPDWGT as decimal(7,5)) * cast(@CmgNonELOS as decimal(7,5))) as decimal(7,4))   
	     Else If @IsAcuteFromNon = 1 and @LOS <= 10 and @LOS <= @CmgNonTrim   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
	             WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and cmgxfr ='I' and dxyear = @dxYear)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,5)) * cast(@RIWDeath as decimal(7,5)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @IsAcuteFromNon = 1 and @LOS > 10 and @LOS <= @CmgNonTrim   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
	             WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and cmgxfr ='I' and dxyear = @dxYear)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,5)) * cast(@RIWDeath as decimal(7,5)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @IsAcuteToNon = 1 and @LOS <= 10 and @LOS <= @CmgNonTrim   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
	             WHERE (TLOS = @LOS) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and cmgxfr ='O' and dxyear = @dxYear)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,5)) * cast(@RIWDeath as decimal(7,5)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @IsAcuteToNon = 1 and @LOS > 10 and @LOS <= @CmgNonTrim   
	     Begin   
	         Set @RIWDeath = (SELECT Top 1 CIHIDthCCF FROM dbo.CMG_DeathXfer_non   
	             WHERE (TLOS = 10) AND (RIWProcInd = @MedSurgNon) AND (ICDType = 'T') and cmgxfr ='O' and dxyear = @dxYear)   
	         Set @CMGMOH = cast(cast(@CmgPDWGT as decimal(7,5)) * cast(@RIWDeath as decimal(7,5)) * cast(@LOS as decimal(7,2)) as decimal(7,4))   
	     End   
	     Else If @LOS > @CmgNonTrim --Ignore the change ED - 01593 change to greater and equal. Before it has greater only
	         Set @CMGMOH = cast(cast(@CMGMOH as decimal(7,5)) + (cast(@CmgPDRA as decimal(7,5)) * cast((cast(@LOS as decimal(7,2)) - cast(@CmgNonELOS as decimal(7,5))) as decimal(9,5))) as decimal(9,4))   
	     
	     If @MedSurgInd = 9
		Set @MedSurgInd = @MedSurgIndHold

	      If @DDisposition = '07'   
	          Set @NonAcuteQuartile = 'D'   
	      Else If @DDisposition = '06'   
	          Set @NonAcuteQuartile = 'S'   
	      Else If @IsAcuteFrom = 1 or @IsAcuteTo = 1 --or @DDisposition = '01' ticket 5711  
	          Set @NonAcuteQuartile = 'T'   
	      Else If cast(@LOS as varchar(10)) > @CmgNonTrim   
	          Set @NonAcuteQuartile = 'O'   
	      Else If @LOS > cast(@CmgNonELOS as decimal(7,5))   
	          Set @NonAcuteQuartile = 'B'   

	      Else   
	          Set @NonAcuteQuartile = 'I'  
          Set @CMGMOH$ = cast(@CmgMOH as decimal(9,4)) * cast(@RIW$ as decimal(6,2))   
          --PR - 02989
          -- Set @CMGMOH = cast(@CMGMOH as decimal(8,4))   
          Set @CMGMOH = cast(@CMGMOH as decimal(9,4))   
          Set @CMGRIW$ = cast(@CMGRIW$ as decimal(10,2))   
          Set @CMGMOH$ = cast(@CMGMOH$ as decimal(10,2))   
      End   
     
      If @DDisposition = '07'   
          Set @AcuteQuartile = 'D'   
      Else If @DDisposition = '06'   
          Set @AcuteQuartile = 'S'   
		--Ticket PR-00766  
      Else If @IsAcuteFromNon = 1 or @IsAcuteToNon = 1 or @IsAcuteFrom = 1 or @IsAcuteTo = 1--or @DDisposition = '01' ticket 5711  
          Set @AcuteQuartile = 'T'   
      Else If @LOS > @CMGTrim   
          Set @AcuteQuartile = 'O'   
      Else If @LOS > cast(@CMGELOS as decimal(7,5))   
          Set @AcuteQuartile = 'B'   
      Else   
          Set @AcuteQuartile = 'I'   
    
      If @MedSurgInd = '2' 
	Set @MedOrSurg = 'M' 
      Else 
	Set @MedOrSurg = 'S' 
      
	--Ticket 10884 Enhancement for CMG Auditing
	If isnull(@AbstractID, 0) > 0 and @Occurance = 1
	Begin
		Declare @AUCmg as Varchar(3)
		Declare @AUCplx as VarChar(1)
		Declare @AUMcc as Varchar(3)
		Declare @AUQuartile as VarChar(1)
		Declare @AURiw as VarChar(20)
		Declare @AUAid as Int
		Declare @GrouperChange as VarChar(1)
		Set @GrouperChange = 'N'
		SELECT @AUAid = Abstractid, @AUCmg = CMG, @AUCplx = Complexity, @AUMcc = MCC, @AUQuartile = AcuteQuartile, @AURiw = CMG_RIW
		FROM AB_CMG where AbstractID = @AbstractID and OccurrenceNumber = 1 and CMG_Year = 2006
		If isnull(@AUAid, 0) > 0
		Begin
			If @AUCmg <> @FinalCMG
			Begin
				Insert into AB_GrouperAudit Values (@AbstractID, 2006, 'CMG', @AUCmg, @FinalCMG, GetDate())
				Set @GrouperChange = 'Y'
			End
			If @AUCplx <> @ComplexityLevel
				Insert into AB_GrouperAudit Values (@AbstractID, 2006, 'Complexity', @AUCplx, @ComplexityLevel, GetDate())
			If left(@AUMcc, 2) <> Left(@MCC, 2)
				Insert into AB_GrouperAudit Values (@AbstractID, 2006, 'MCC', @AUMcc, Left(@MCC, 3), GetDate())
			If @AUQuartile <> @AcuteQuartile
				Insert into AB_GrouperAudit Values (@AbstractID, 2006, 'Quartile', @AUQuartile, @AcuteQuartile, GetDate())
			If @AURiw <> @CmgRIW
			Begin
				Insert into AB_GrouperAudit Values (@AbstractID, 2006, 'RIW', @AURiw, @CmgRIW, GetDate())
				Set @GrouperChange = 'Y'
			End
		End
		If @GrouperChange = 'Y' and @FlagRecord = 'Y'
			Update AB_Abstract set iscorrected = 2 where abstractid = @AbstractID and issubmited = 1 and isdeleted = 2 and iscorrected = 1
				and batchyear = 2006
	End

      If isnull(@AbstractID, 0) > 0 
      Begin   
          If @Occurance = 1
	set @ExpiryDate = null
          Delete ab_CMG where Abstractid = @Abstractid and CMG_Year = 2006 and OccurrenceNumber = @Occurance   
          If IsNull(@FinalCMG, '') <> '' and isnull(@DiagMostResposible, '') <> ''
          Begin   
              Set @DiagMostResposible = (select top 1 code from ICD_DiagFile10 where cihivalue = @DiagMostResposible)   
              INSERT INTO [dbo].[AB_CMG] ([AbstractID], [OccurrenceNumber], [CMG_Year], [ICD_Type], [Diagnosis_Code],   
              [Diagnosis_Type], [CMG], [Complexity], [MCC], [AcuteQuartile], [CMG_RIW], [MOH_RIW],   
              [RIW_Dollar], [MOH_Dollar], [CMG_ELOS], [CMG_Trim], [CMG_Description], [MCC_Surg], MOHQuartile, ExpiryDate) VALUES    
              (@AbstractID, @Occurance, 2006, 'T', @DiagMostResposible, 11, @FinalCMG, @ComplexityLevel, rtrim(Left(@MCC, 3)), @AcuteQuartile, @CmgRIW, @CmgMOH,    
              cast(@CmgRIW$ as money), cast(@CmgMOH$ as money), @CmgELOS, @CMGTrim, @CMGDesc, @MedOrSurg,@NonAcuteQuartile, @ExpiryDate)   

              Update ab_CMG set CMGModelType = ModelType, CMGTenthPercent = TenthPercent, CMGTwentyFifthPercent = TwentyFifthPercent, CMGFiftiethPercent = FiftiethPercent 
              FROM dbo.AB_CMG LEFT OUTER JOIN
              dbo.CMG_Etc_2005T ON dbo.AB_CMG.Complexity = dbo.CMG_Etc_2005T.cicpxlvl AND dbo.AB_CMG.CMG = dbo.CMG_Etc_2005T.cmgcode
              WHERE abstractid = @AbstractID and CMG_Year = 2006 and ciagegroup = @AgeGroup
          End   
      
      End   
      set nocount off    

  --    print datediff(ms, @SDate, getdate())   
      Return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create  PROCEDURE [P_CPI_ROILegalComments_Fetch]
	(@ChartNumber	 	[varchar](50),
	 @HospitalID		[int],
	 @ROILegalComments 	[varchar](500) output
)
AS 
set @ROILegalComments = (select top 1 ROILegalComments from CM_CPI where ChartNumber = @ChartNumber
                and (isnull(HospitalID, 0) = 0 or isnull(@HospitalID, 0) = 0 or isnull(HospitalID, 0) = isnull(@HospitalID, 0))
            order by  isnull((case when  isnull(@HospitalID, 0) = 0 then 0 - HospitalID  else HospitalID end), 0) desc)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [P_CPI_ROILegalComments_Save]
	(@ChartNumber	 	[varchar](50),
	 @HospitalID		[int],
	 @ROILegalComments 	[varchar](500))
AS 
declare @PID int
set @PID = (select top 1 PatientID from CM_CPI where ChartNumber = @ChartNumber
                and (isnull(HospitalID, 0) = 0 or isnull(@HospitalID, 0) = 0 or isnull(HospitalID, 0) = isnull(@HospitalID, 0))
            order by  isnull((case when  isnull(@HospitalID, 0) = 0 then 0 - HospitalID  else HospitalID end), 0) desc)

update [dbo].[CM_CPI] 
set  ROILegalComments = @ROILegalComments
where PatientID = @PID


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_CPIMerge]
	@ChartNumberFrom as VarChar(10),
	@ChartNumberTo   as VarChar(10),
	@Coder       as int,
	@MergeChange as int = 0,    --0 = Merge, 1 = Change Chart#, 2 = Unmerge, 3 = UnChange(PR - 04076)
	@HospIDFrom  as int = 0,
	@HospIDTo    as int = 0,
	@PIDFrom     as int = 0,    -- PR - 03348
	@PIDTo       as int = 0,    -- PR - 03348
    @ID          as uniqueidentifier = null -- PR - 03348
AS
--  Rewritten for EN - 00182 by Troy - 2006/05/02
--	Declare @PIDFrom as int -- PR - 03348
--	Declare @PIDTo as int   -- PR - 03348

	Declare @CurserValue as int
	Declare @CurserValue2 as int
	Declare @UpdateID as uniqueidentifier
	Declare @OldUpdateID as uniqueidentifier
	Declare @OrgFirstName as Varchar(100)
	Declare @OrgLastName as VarChar(100)
	Declare @CountFrom as int
	Declare @CountTo as int
	Declare @NewVID as int--PR - 02057
    Declare @Error int -- PR - 03348
	Declare @NewULI varchar(50) --EN - 00511
	declare @MaxOcc int	--2.x-0244
	
    Declare @IsExistCCVol int -- ED - 01668
    set @IsExistCCVol = 0     -- ED - 01668

-- PR - 03348
    set @Error = 1 -- PR - 03348
    if isnull(@PIDFrom, 0) = 0
    begin
        if isnull(@HospIDFrom, 0) = 0
    	    select top 1 @PIDFrom = patientid, @OrgFirstName = FirstName, @OrgLastName = LastName, @HospIDFrom = isnull(HospitalID, 0) 
            from CM_CPI 
            where chartnumber = @ChartNumberFrom 
            order by isnull(HospitalID, 0)    
        else
    	    select top 1 @PIDFrom = patientid, @OrgFirstName = FirstName, @OrgLastName = LastName  
            from CM_CPI 
            where chartnumber = @ChartNumberFrom 
                and (isnull(HospitalID, 0) = 0 or @HospIDFrom = case @HospIDFrom when 0 then 0 else isnull(HospitalID, 0) end)			
            order by isnull(HospitalID, 0) desc   
    end
    else
    begin
	    select top 1 @OrgFirstName = FirstName, @OrgLastName = LastName, @HospIDFrom = isnull(HospitalID, 0) 
        from CM_CPI 
        where chartnumber = @ChartNumberFrom and PatientID = @PIDFrom
        order by isnull(HospitalID, 0)    
    end

    if isnull(@PIDTo, 0) = 0
    begin
        if @MergeChange <> 1    --PR - 03698
        begin
            if isnull(@HospIDTo, 0) = 0
    	        select top 1 @PIDTo = patientid, @HospIDTo = isnull(HospitalID, 0) , @NewULI = RegionalPatientID
                from CM_CPI 
                where chartnumber = @ChartNumberTo 
                order by isnull(HospitalID, 0)    
            else
    	        select top 1 @PIDTo = patientid, @NewULI = RegionalPatientID
                from CM_CPI 
                where chartnumber = @ChartNumberTo 
                    and (isnull(HospitalID, 0) = 0 or @HospIDTo = case @HospIDTo when 0 then 0 else isnull(HospitalID, 0) end)			
                order by isnull(HospitalID, 0) desc   
        end
    end
    else
    begin
	    select top 1 @HospIDTo = isnull(HospitalID, 0), @NewULI = RegionalPatientID
        from CM_CPI 
        where chartnumber = @ChartNumberTo and PatientID = @PIDTo
        order by isnull(HospitalID, 0)    
    end
    
    --PR - 04076
    if 	isnull(@PIDFrom, 0) = 0 or (isnull(@PIDTo, 0) = 0 and @MergeChange not in (1, 3)) goto ProcedureFinish 
    --if 	isnull(@PIDFrom, 0) = 0 or (isnull(@PIDTo, 0) = 0 and @MergeChange <> 1) goto ProcedureFinish 
    set @Error = 2 -- PR - 03348
	--Check first for unique charts, otherwise reject
--PR - 03348
	set @CountFrom = (select count(*) FROM dbo.CM_CPI_ChartLocked WHERE PatientID = @PIDFrom)
--	set @CountFrom = (select count(CM_CPI.patientid) FROM dbo.CM_CPI LEFT OUTER JOIN dbo.CM_CPI_ChartLocked 
--		ON dbo.CM_CPI.PatientID = dbo.CM_CPI_ChartLocked.PatientID  WHERE dbo.CM_CPI.chartnumber = @ChartNumberFrom and MergeID IS NULL)
		--and isnull(hospitalid, 0) = isnull(@HospIDFrom, 0) and MergeID IS NULL)PR - 01116

	if isnull(@CountFrom, 0) <> 0
        goto ProcedureFinish  

	If @MergeChange = 1
	Begin
        --PR - 03348
	    set @CountTo = (select count(*) FROM dbo.CM_CPI WHERE PatientID = @PIDTo or (ChartNumber = @ChartNumberTo and isnull(hospitalid, 0) = isnull(@HospIDFrom, 0)))
	    --set @CountTo = (select count(*) FROM dbo.CM_CPI WHERE PatientID = @PIDTo)
--		set @CountTo = (select count(CM_CPI.patientid) FROM dbo.CM_CPI LEFT OUTER JOIN dbo.CM_CPI_ChartLocked 
--			ON dbo.CM_CPI.PatientID = dbo.CM_CPI_ChartLocked.PatientID WHERE dbo.CM_CPI.chartnumber = @ChartNumberTo)
--			--and isnull(hospitalid, 0) = isnull(@HospIDTo, 0)) PR - 01116
		if isnull(@CountTo, 0) <> 0
			goto ProcedureFinish 
	End
	Else
	Begin
        --PR - 03348
		set @CountTo = (select count(*) FROM dbo.CM_CPI_ChartLocked WHERE PatientID = @PIDTo)
		--set @CountTo = (select count(CM_CPI.patientid) FROM dbo.CM_CPI LEFT OUTER JOIN dbo.CM_CPI_ChartLocked 
		--	ON dbo.CM_CPI.PatientID = dbo.CM_CPI_ChartLocked.PatientID WHERE dbo.CM_CPI.chartnumber = @ChartNumberTo and MergeID IS NULL)
			--and isnull(hospitalid, 0) = isnull(@HospIDTo, 0) and MergeID IS NULL)PR - 01116
        if isnull(@CountTo, 0) <> 0
			    goto ProcedureFinish  
	End

	

	Set @UpdateID = newid()

If isnull(@PIDFrom, 0) <> isnull(@PIDTo, 0) and isnull(@mergechange, 0) = 0
--If @ChartNumberFrom <> @ChartNumberTo and isnull(@mergechange, 0) = 0 -- PR - 03348
Begin
-- PR - 03348
--	select top 1 @PIDFrom = patientid, @OrgFirstName = FirstName, @OrgLastName = LastName from CM_CPI where chartnumber = @ChartNumberFrom --PR - 01479 and isnull(hospitalid, 0) = @HospIDFrom
--	select top 1 @PIDTo = patientid from CM_CPI where chartnumber = @ChartNumberTo --PR - 01479 and isnull(hospitalid, 0) = @HospIDFrom
	if isnull(@PIDFrom, 0) <> 0 and isnull(@PIDTo, 0) <> 0 
	Begin
        --PR - 03683 Client merge multi times.
        declare @masterchart int
        set @masterchart = (select top 1 masterchart from cm_cpi where PatientID in (@PIDFrom, @PIDTo) and masterchart > 0)
        if @masterchart > 0 goto ProcedureFinish  
        --

		Update CM_CPI set Firstname = left(lastname + ', ' + firstname, 35), lastname = 'Merged with C#' + @ChartNumberTo where PatientID = @PIDFrom
		--0244 
		if @HospIDFrom is null set @HospIDFrom = 0
		Update CM_CPI set [MothersChart] = @ChartNumberTo where [MothersChart] = @ChartNumberFrom and (isnull(HospitalID, 0) in (@HospIDFrom, 0) or @HospIDFrom = 0)
		Update CM_BabyChart set [BabyChartNumber] = @ChartNumberTo 
		from CM_BabyChart b inner join CM_CPI cpi on b.PatientID = cpi.PatientID
		where [BabyChartNumber] = @ChartNumberFrom and (isnull(HospitalID, 0) in (@HospIDFrom, 0) or @HospIDFrom = 0)
		--Move baby chart into merge chart baby chart
		set @MaxOcc = isnull((select max([BabyChartOccurrence]) from [dbo].[CM_BabyChart] where PatientID = @PIDTo), 0)
		Insert into [dbo].[CM_BabyChart](PatientID, BabyChartOccurrence, BabyChartNumber)
		select @PIDTo, a.BabyChartOccurrence + @MaxOcc, a.BabyChartNumber
		from  [dbo].[CM_BabyChart] a
			left join (select * from [dbo].[CM_BabyChart] where PatientID = @PIDTo) b on a.[BabyChartNumber] = b.[BabyChartNumber]
		where a.PatientID = @PIDFrom and b.[BabyChartNumber] is null
		--Modify Mother Chart
		if exists (select [MothersChart] from cm_cpi where patientid = @PIDFrom and isnull([MothersChart], '') <> '')
			Update cm_cpi
			set [MothersChart] = (select top 1 z.[MothersChart] from cm_cpi z where z.patientid = @PIDFrom and isnull(z.[MothersChart], '') <> '')
			where patientid = @PIDTo and isnull([MothersChart], '') = ''


		Update AB_Abstract 
		set Chartnumber = @ChartNumberTo , RegionalPatientID = @NewULI, 
		    FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)  --PR - 06021
        where chartnumber = @ChartNumberFrom AND IsDeleted <> 3
            and (isnull(HospitalID, 0) = 0 or @HospIDFrom = case @HospIDFrom when 0 then 0 else isnull(HospitalID, 0) end)			 -- PR - 03348

		Update RH_ClientInfo 
		set Chartnumber = @ChartNumberTo, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)  --PR - 06021 
        where chartnumber = @ChartNumberFrom AND IsDeleted <> 3
            and (isnull(HospitalID, 0) = 0 or @HospIDFrom = case @HospIDFrom when 0 then 0 else isnull(HospitalID, 0) end)			 -- PR - 03348

		Update CRS_Demographic 
		set Chartnumber = @ChartNumberTo, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)  --PR - 06021 
        where chartnumber = @ChartNumberFrom AND IsDeleted <> 3
            and (isnull(HospitalID, 0) = 0 or @HospIDFrom = case @HospIDFrom when 0 then 0 else isnull(HospitalID, 0) end)			 -- PR - 03348

		Update OMHRS_SecAA 
		set Chartnumber = @ChartNumberTo, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)  --PR - 06021 
        from OMHRS_SecAA inner join OMHRS_RecInfo on OMHRS_SecAA.AbstractID = OMHRS_RecInfo.AbstractId
        where chartnumber = @ChartNumberFrom AND IsDeleted <> 3
            and (isnull(HospitalID, 0) = 0 or @HospIDFrom = case @HospIDFrom when 0 then 0 else isnull(HospitalID, 0) end)			 -- PR - 03348

		Update dbo.CC_Demographic 
		set Chartnumber = @ChartNumberTo, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)  --PR - 06021 
        where chartnumber = @ChartNumberFrom
            and (isnull(HospitalID, 0) = 0 or @HospIDFrom = case @HospIDFrom when 0 then 0 else isnull(HospitalID, 0) end)			 -- PR - 03348

        --ED - 01668 TOH CC volume issue
        if exists (select code from dbo.h_hospitalprofile where hospitalid = 2014)
        begin
            if exists (select volumeid from dbo.CM_CPI_Volume where patientid = @PIDFrom)
                set @IsExistCCVol = 1
        end
        
        --ED - 01668
        if @IsExistCCVol = 1
        begin
		    Declare Cur_CC cursor for
		    select distinct isnull(hospitalid, 0) 
            from CM_CPI_Volume 
            where patientid = @PIDFrom and isnull(hospitalid, 0) not in (
		    select isnull(hospitalid, 0) from CM_CPI_Volume where patientid = @PIDTo and VolumeNumber = 'CC000001')
                and VolumeNumber = 'CC000001'
		    OPEN Cur_CC
		    fetch next from Cur_CC into @CurserValue
		    while @@fetch_status = 0    
		    begin  
			    set @NewVID = (SELECT MAX(VolumeID) + 1  from CM_CPI_Volume)--PR - 02057
			    insert into CM_CPI_Volume(VolumeID, PatientID, VolumeNumber, VolumeDateFrom, VolumenDateTo, PermLocation, CLInpatient, CLSDS, CLOutpatient, CLAmcare, CLMicroFilm, CLMircoFilmNum, 
                    CLOption1, CLOption2, CLOption3, CLOption4, CLBoxNumber, CLLinkedVolume, CLComments, CLCurrentLocation, SubVolume, LabelPrinted, HospitalID, BarCodeVolume, VolumeType, 
                    CLPreviousLocation, ActivityType, CLActivityID, UniversalID, DigitalIndicator, DestructionDate)
                SELECT TOP 1 @NewVID, @PIDTo, 'CC000001', VolumeDateFrom, VolumenDateTo, 
			    isnull((select top 1 code from LoanLU_Location where displaycode = 'DONOTUSE' and (hospitalid = @CurserValue or @CurserValue = 0)), 0), 
			    CLInpatient, CLSDS, CLOutpatient, CLAmcare, CLMicroFilm, CLMircoFilmNum, CLOption1, CLOption2, CLOption3, CLOption4, CLBoxNumber, CLLinkedVolume, CLComments = 'Create by chart merge', 
			    isnull((select top 1 code from LoanLU_Location where displaycode = 'DONOTUSE' and (hospitalid = @CurserValue or @CurserValue = 0)), 0), 
			    SubVolume, null, HospitalID, BarCodeVolume, VolumeType, CLPreviousLocation, ActivityType, CLActivityID, UniversalID, 
			    DigitalIndicator, --TS-222
                DestructionDate
			    FROM  dbo.CM_CPI_Volume 
                WHERE (PatientID = @PIDFrom) AND (isnull(HospitalID, 0) = @CurserValue) and VolumeNumber = 'CC000001'
                ORDER BY VolumenDateTo DESC, VolumeID Desc


			    fetch next from Cur_CC into @CurserValue
		    end
		    Close Cur_CC
		    Deallocate Cur_CC

        end
        --print 'point 1'
		--EN - 00316 copy over the most recent volume from each hospital if one doesnt' exist in desintation
		Declare Cur_Temp cursor for
		select distinct isnull(hospitalid, 0) 
        from CM_CPI_Volume 
        where patientid = @PIDFrom and isnull(hospitalid, 0) not in (
		select isnull(hospitalid, 0) from CM_CPI_Volume where patientid = @PIDTo and (@IsExistCCVol = 0 or (@IsExistCCVol = 1 and VolumeNumber <> 'CC000001')))
            and (@IsExistCCVol = 0 or (@IsExistCCVol = 1 and VolumeNumber <> 'CC000001')) --ED - 01668
		OPEN Cur_Temp
		fetch next from Cur_Temp    
		into @CurserValue
		while @@fetch_status = 0    
		begin  
			set @NewVID = (SELECT MAX(VolumeID) + 1  from CM_CPI_Volume)--PR - 02057
			insert into CM_CPI_Volume(VolumeID, PatientID, VolumeNumber, VolumeDateFrom, VolumenDateTo, PermLocation, CLInpatient, CLSDS, CLOutpatient, CLAmcare, CLMicroFilm, 
                CLMircoFilmNum, CLOption1, CLOption2, CLOption3, CLOption4, CLBoxNumber, CLLinkedVolume, CLComments, CLCurrentLocation, SubVolume, LabelPrinted, HospitalID, 
                BarCodeVolume, VolumeType, CLPreviousLocation, ActivityType, CLActivityID, UniversalID, DigitalIndicator, DestructionDate)
			SELECT TOP 1 @NewVID, @PIDTo, '  000001', VolumeDateFrom, VolumenDateTo, 
			isnull((select top 1 code from LoanLU_Location where displaycode = 'main'), 0), --PR - 02057
			CLInpatient, CLSDS, CLOutpatient, CLAmcare, CLMicroFilm, CLMircoFilmNum, CLOption1, CLOption2, CLOption3, CLOption4, CLBoxNumber, CLLinkedVolume, CLComments = 'Create by chart merge', 
			isnull((select top 1 code from LoanLU_Location where displaycode = 'NEWPAT'), 0), --PR - 02057
			SubVolume, null, HospitalID, BarCodeVolume, VolumeType, CLPreviousLocation, ActivityType, CLActivityID, UniversalID, 
		    DigitalIndicator, --TS-222
            DestructionDate
			FROM  dbo.CM_CPI_Volume WHERE (PatientID = @PIDFrom) AND (isnull(HospitalID, 0) = @CurserValue) ORDER BY VolumenDateTo DESC, VolumeID Desc

			fetch next from Cur_Temp    
			into @CurserValue
		end
		Close Cur_Temp
		Deallocate Cur_Temp
        --print 'point 2'
        --**Audit Volumes updated and update volumes
		--Get all the records with volumes that are being merged over
		select universalid as UID, abstractid as AID, isnull(hospitalid, 0) as HID, apptype as Appt, volumeid as VIDFrom, cast(null as int) as VIDTo, cast(null as datetime) as VDate
		into #RecordsFrom 
        from ab_main 
        where chartnumber = @ChartNumberFrom and appid <> 0 and isnull(volumeid, 0) <> 0
            and (isnull(HospitalID, 0) = 0 or @HospIDFrom = case @HospIDFrom when 0 then 0 else isnull(HospitalID, 0) end)			 -- PR - 03348

        --PR - 04407 run time error: EN-00447: Added Scan Flag
		--Get the Visit date for all the visits
        --PR - 04501 add L1Status
		CREATE TABLE #Visits ( UniversalID bigint, AbstractID int, Appid int, L1Status varchar(5),
            DCStatus VarChar(5), ScanFlag varchar(10),
			[Hosp ID] varchar(20), Care VarChar(10), PatientType VarChar(10), Inst varchar(10), VisitDate Datetime,
			[LevelCode] varchar(10))    --PR - 07438 add [LevelCode] code
		insert into #Visits
        exec P_HistoryVisit2 @ChartNumberFrom, '', @HospIDFrom, 0 --PR - 03348
		--exec P_HistoryVisit2 @ChartNumberFrom, '', 0, 0 --PR - 03348


        --print 'point 3'
		Update #RecordsFrom set VDate = VisitDate from #Visits Where Universalid = UID
		--Update VolumeFrom and VolumeTo dates of volume to be merged into 
		--Get all the existing volumes of the chart to be merged into
		select volumeid, patientid, VolumeNumber, VolumeDateFrom, volumenDateTo, isnull(hospitalid, 0) as HospID
		into #VolumeTo From CM_CPI_Volume where patientid = @PIDTo
		--Update the volumes with the correct HospitalID
		--Update #RecordsFrom set HID = hospitalid from CM_CPI_Volume where VIDFrom = volumeid
		Update #RecordsFrom set HID = isnull(hospitalid, 0) from CM_CPI_Volume 
        where VIDFrom = volumeid and HID <> isnull(hospitalid, 0)   --PR - 03561
        
		--Figure out which volumes to move the vists to
        if @IsExistCCVol = 1
        begin
	        Update #RecordsFrom set VIDTo = t.VolumeID 
            from #RecordsFrom f 
                inner join cm_cpi_volume v on f.VIDFrom = v.volumeid and v.volumenumber = 'CC000001'
                inner join #VolumeTo t on HospID = HID and t.volumenumber = 'CC000001'
            Update #RecordsFrom set VIDTo = VolumeID from #VolumeTo 
            where VDate between VolumeDateFrom and volumenDateTo and HospID = HID
                and isnull(VIDTo, 0) = 0
        end
        else
            Update #RecordsFrom set VIDTo = VolumeID from #VolumeTo 
            where VDate between VolumeDateFrom and volumenDateTo and HospID = HID

		--Those volumes that exist but don't fall in date range of merging volumes, update VolumeFrom/to
		Declare @MinVDate as DateTime
		Declare @MaxVDate as DateTime
		Declare @VolumeToUpdate as int
		Declare Cur_Temp cursor for
		SELECT distinct HID from #RecordsFrom where isnull(VIDTo, 0) = 0
		OPEN Cur_Temp
		fetch next from Cur_Temp    
		into @CurserValue
		while @@fetch_status = 0    
		begin  
			set @VolumeToUpdate = 0
			Select @MinVDate = isnull(min(VDate), '1950/01/01'), @MaxVDate = isnull(max(VDate), '2020/01/01') 
			from #RecordsFrom where isnull(VIDTo, 0) = 0 and HID = @CurserValue
			select top 1 @VolumeToUpdate = Volumeid From CM_CPI_Volume 
            where patientid = @PIDTo and hospitalid = @CurserValue and
                (@IsExistCCVol = 0 or (@IsExistCCVol = 1 and volumenumber <> 'CC000001'))
			order by isnull(volumenDateTo, '2020/01/01') desc
			if (isnull(@VolumeToUpdate, 0) <> 0)
			Begin
				update CM_CPI_Volume set VolumeDateFrom = @MinVDate where volumeid = @VolumeToUpdate 
				and VolumeDateFrom > @MinVDate
				update CM_CPI_Volume set volumenDateTo = @MaxVDate where volumeid = @VolumeToUpdate  
				and volumenDateTo < @MaxVDate
				Update #RecordsFrom set VIDTo = @VolumeToUpdate where HID = @CurserValue and isnull(VIDTo, 0) = 0
			End
			fetch next from Cur_Temp    
			into @CurserValue
		end
		Close Cur_Temp
		Deallocate Cur_Temp
        
        if @IsExistCCVol = 1
            Update CM_CPI_Volume
            set VolumeDateFrom = (case when mindate < isnull(VolumeDateFrom, getdate()) then mindate else VolumeDateFrom end),
                volumenDateTo  = (case when maxdate > isnull(volumenDateTo, '1950/01/01') then maxdate else volumenDateTo end)
            from cm_CPI_Volume v inner join (select VIDTO, Min(VDate) as mindate, max(Vdate) as maxdate from #RecordsFrom group by VIDTO) f on v.volumeid = f.VIDTO
            where v.volumenumber = 'CC000001' and (mindate < isnull(VolumeDateFrom, getdate()) or maxdate > isnull(volumenDateTo, '1950/01/01'))

		--Now add volumes for each hospital that doesn't exist
		Declare @VID as int
		Declare Cur_Temp cursor for
		SELECT distinct HID from #RecordsFrom where isnull(VIDTo, 0) = 0
		OPEN Cur_Temp
		fetch next from Cur_Temp    
		into @CurserValue
		while @@fetch_status = 0    
		begin    
			Select @MinVDate = isnull(min(VDate), '1950/01/01'), @MaxVDate = isnull(max(VDate), '2020/01/01') 
			from #RecordsFrom where isnull(VIDTo, 0) = 0 and HID = @CurserValue
			exec I_CM_CPI_Volume @PIDTo, 0, '  000001', 0, '', @MinVDate, @MaxVDate, 0, 0, '', 0, 0, 0, 0, 0, '', 0, 0, 0, 0, '', 0, 0, @CurserValue, 0, 0, 0, 0, 0 --PR - 05309      --PR - 03561 set @UID to 0.
			set @VID = (select max(volumeid) from CM_CPI_Volume)
			exec I_CM_Volume_History @VID, @Coder, 'Saved'
			Update #RecordsFrom set VIDTo = @VID where HID = @CurserValue and isnull(VIDTo, 0) = 0
			fetch next from Cur_Temp    
			into @CurserValue
		end
		Close Cur_Temp
		Deallocate Cur_Temp
		--Update Volume Reference in AB_Main
		Update AB_Main set VolumeID = VIDTo from #RecordsFrom where Universalid = UID
		--Update Volume Reference in AB_Abstract
		Update AB_Abstract set VolumeID = VIDTo from #RecordsFrom 
		where AbstractID = AID and Appt in (1, 2, 5, 101, 102, 105) 
		--Audit Volume Changes
		Insert into MRG_Volume2 select @UpdateID, VIDFrom, VIDTo, UID from #RecordsFrom

		--**Update Master Child relationship. If it is decided to move up the hiarchy instead, use the P_FetchChartFamily to figure it out.
		Declare @MasterFrom as int
		Select @MasterFrom = MasterChart from CM_CPI where patientid = @PIDFrom
		Update CM_CPI set MasterChart = @PIDTo where patientid = @PIDFrom
		Insert into MRG_Masterchild values (@UpdateID, @MasterFrom, @PIDTo)
		--**Audit Deficiencies updated and update Deficiencies
        --EN-00183
		Insert into MRG_Deficiency select @UpdateID, DefeciencyID, DefID from Def_SlipMain where DefPatientID = @PIDFrom

		Update Def_SlipMain set DefPatientID = @PIDTo where DefPatientID = @PIDFrom
		--**Audit ROIs updated and update ROIs
		Insert into MRG_ROI select @UpdateID, ROIID from ROI_Main where chartnumber = @ChartNumberFrom
		Update ROI_Main 
		set Chartnumber = @ChartNumberTo --, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)  --PR - 06021 
		where chartnumber = @ChartNumberFrom
		
		Exec I_CM_History @PIDFrom, @Coder
		Exec I_CM_History @PIDTo, @Coder
		--**Audit abstracts Updated
		Insert into MRG_Record select @UpdateID, UniversalID from AB_Main where chartnumber = @ChartNumberFrom
		--**Update AB_Main table for all abstracts effected
		Update AB_Main 
		set PatientID = @PIDTo, chartnumber = @ChartNumberTo, RegionalPatientID = @NewULI,
		    FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)  --PR - 06021
		where chartnumber = @ChartNumberFrom and apptype <> 0
            and (isnull(HospitalID, 0) = 0 or @HospIDFrom = case @HospIDFrom when 0 then 0 else isnull(HospitalID, 0) end)			 -- PR - 07543

		--**Lock Record if they are set up to do so
		Declare @DefHospID as int
		set @DefHospID = (select code from H_HospitalProfile where code in (
		select case hospitalid when 0 then isnull(defaultHospid, 0) else ISNULL(HospitalID, 0) end
		from u_users where code = 1))
		if isnull(@DefHospID, 0) = 0 
			set @DefHospID = (select top 1 code from H_HospitalProfile)
		if exists (select code from H_HospitalProfile where code = @DefHospID and reissuechart = 1)
			insert into CM_CPI_ChartLocked (PatientID, MergeID, ChartNumber) values (@PIDFrom, @UpdateID, @ChartNumberFrom)

		exec U_AB_Main @PIDFrom, 0
		Insert into MRG_Main values (@UpdateID, @PIDFrom, @ChartNumberFrom, @PIDTo, @ChartNumberTo, 
		@OrgFirstName, @OrgLastName, 'Merged', getdate(), @Coder)
		select * from #RecordsFrom
	End
end
else if isnull(@MergeChange, 0) = 1  
Begin
    --PR - 03348
	-- set @PIDFrom = (select top 1 patientid from CM_CPI where chartnumber = @ChartNumberFrom)
	-- set @PIDTo = (select top 1 patientid from CM_CPI where chartnumber = @ChartNumberTo)
 
	if isnull(@PIDFrom, 0) <> 0 and isnull(@PIDTo, 0) = 0 
	Begin
		Update CM_CPI 
		set chartnumber = @ChartNumberTo, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)  --PR - 06021
		Where PatientID = @PIDFrom
		--0244 
		if @HospIDFrom is null set @HospIDFrom = 0
		Update CM_CPI set [MothersChart] = @ChartNumberTo where [MothersChart] = @ChartNumberFrom and (isnull(HospitalID, 0) in (@HospIDFrom, 0) or @HospIDFrom = 0)
		Update CM_BabyChart set [BabyChartNumber] = @ChartNumberTo 
		from CM_BabyChart b inner join CM_CPI cpi on b.PatientID = cpi.PatientID
		where [BabyChartNumber] = @ChartNumberFrom and (isnull(HospitalID, 0) in (@HospIDFrom, 0) or @HospIDFrom = 0)

        -- 2003/03/11...Added to include Rehab.
		Update RH_ClientInfo 
		set Chartnumber = @ChartNumberTo, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)  --PR - 06021 
        where chartnumber = @ChartNumberFrom AND IsDeleted <> 3
            and (isnull(HospitalID, 0) = 0 or @HospIDFrom = case @HospIDFrom when 0 then 0 else isnull(HospitalID, 0) end)			 -- PR - 03348

		Update CRS_Demographic 
		set Chartnumber = @ChartNumberTo, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)  --PR - 06021 
        where chartnumber = @ChartNumberFrom AND IsDeleted <> 3
            and (isnull(HospitalID, 0) = 0 or @HospIDFrom = case @HospIDFrom when 0 then 0 else isnull(HospitalID, 0) end)			 -- PR - 03348

		Update OMHRS_SecAA 
        set Chartnumber = @ChartNumberTo, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)  --PR - 06021 
        from OMHRS_SecAA 
            inner join OMHRS_RecInfo on OMHRS_SecAA.AbstractID = OMHRS_RecInfo.AbstractId
        where chartnumber = @ChartNumberFrom AND IsDeleted <> 3 --PR - 04459
            and (isnull(HospitalID, 0) = 0 or @HospIDFrom = case @HospIDFrom when 0 then 0 else isnull(HospitalID, 0) end)			 -- PR - 03348

		Update CC_Demographic 
		set Chartnumber = @ChartNumberTo, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)  --PR - 06021 
        where chartnumber = @ChartNumberFrom
            and (isnull(HospitalID, 0) = 0 or @HospIDFrom = case @HospIDFrom when 0 then 0 else isnull(HospitalID, 0) end)			 -- PR - 03348


		Update ab_abstract 
		set Chartnumber = @ChartNumberTo, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)  --PR - 06021
        where chartnumber = @ChartNumberFrom AND IsDeleted <> 3
            and (isnull(HospitalID, 0) = 0 or @HospIDFrom = case @HospIDFrom when 0 then 0 else isnull(HospitalID, 0) end)			 -- PR - 03348

		Update roi_main 
		set Chartnumber = @ChartNumberTo --, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)  --PR - 06021 
        where chartnumber = @ChartNumberFrom
            and (isnull(HospitalID, 0) = 0 or @HospIDFrom = case @HospIDFrom when 0 then 0 else isnull(HospitalID, 0) end)			 -- PR - 03348
		--Added for Visit History
		Update AB_Main 
		set PatientID = @PIDTo, chartnumber = @ChartNumberTo, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)  --PR - 06021
        where chartnumber = @ChartNumberFrom  and apptype <> 0
            and (isnull(HospitalID, 0) = 0 or @HospIDFrom = case @HospIDFrom when 0 then 0 else isnull(HospitalID, 0) end)			 -- PR - 03348
		exec U_AB_Main @PIDFrom, 0

		set @PIDTo = @PIDFrom
		Exec I_CM_History @PIDTo, @Coder
	    Insert into MRG_Main values (@UpdateID, @PIDFrom, @ChartNumberFrom, @PIDTo, @ChartNumberTo, 
	    '', '', 'Changed', getdate(), @Coder)
	End
End

else if isnull(@MergeChange, 0) = 2 --UnMerge
Begin
    if @ID is null
		SELECT TOP 1 @OldUpdateID = ID, @PIDFrom = PatientIDFrom, @PIDTo = PatientIDTo, @OrgFirstName = OrgFirstName, @OrgLastName = OrgLastName
		FROM dbo.MRG_Main 
        WHERE (UpdateType = 'Merged') AND (ChartNumberFrom = @ChartNumberFrom) AND (ChartNumberTo = @ChartNumberTo)
		ORDER BY DateMerged DESC
    else    --PR - 03348
		SELECT TOP 1 @OldUpdateID = ID, @PIDFrom = PatientIDFrom, @PIDTo = PatientIDTo, @OrgFirstName = OrgFirstName, @OrgLastName = OrgLastName
		FROM dbo.MRG_Main 
        Where [ID] = @ID
		ORDER BY DateMerged DESC

		--EN - 00511
	    select top 1 @NewULI = RegionalPatientID from CM_CPI where PatientID = @PIDFrom
        
		Update CM_CPI set Firstname = @OrgFirstName, lastname = @OrgLastName where PatientID = @PIDFrom
		--0244 
		if @HospIDTo is null set @HospIDTo = 0
		Update CM_CPI set [MothersChart] = @ChartNumberFrom where [MothersChart] = @ChartNumberTo and (isnull(HospitalID, 0) in (@HospIDTo, 0) or @HospIDTo = 0)
		Update CM_BabyChart set [BabyChartNumber] = @ChartNumberFrom 
		from CM_BabyChart b inner join CM_CPI cpi on b.PatientID = cpi.PatientID
		where [BabyChartNumber] = @ChartNumberTo and (isnull(HospitalID, 0) in (@HospIDTo, 0) or @HospIDTo = 0)
		--Delete the merged baby chart
		Delete from [dbo].[CM_BabyChart]
		from  [dbo].[CM_BabyChart] a
			inner join (select * from [dbo].[CM_BabyChart] where PatientID = @PIDFrom) b on a.[BabyChartNumber] = b.[BabyChartNumber]
		where a.PatientID = @PIDTo

		Update AB_Abstract 
		set Chartnumber = @ChartNumberFrom, RegionalPatientID = @NewULI,
		    FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberFrom)  --PR - 06021 
		where abstractid in (
			select abstractid from ab_main where universalid in (
			select UniversalID from MRG_Record where ID = @OldUpdateID)
			And apptype in (1, 2, 5, 101, 102, 105)) And IsDeleted <> 3
			
		Update RH_ClientInfo 
		set Chartnumber = @ChartNumberFrom, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberFrom)  --PR - 06021 
		where abstractid in (
			select abstractid from ab_main where universalid in (
			select UniversalID from MRG_Record where ID = @OldUpdateID)
			And apptype = 3)  And IsDeleted <> 3
		
		Update CRS_Demographic 
		set Chartnumber = @ChartNumberFrom, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberFrom)  --PR - 06021  
		where abstractid in (
			select abstractid from ab_main where universalid in (
			select UniversalID from MRG_Record where ID = @OldUpdateID)
			And apptype = 4)  And IsDeleted <> 3
		
		Update OMHRS_SecAA 
		set Chartnumber = @ChartNumberFrom, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberFrom)  --PR - 06021  
        from OMHRS_SecAA inner join OMHRS_RecInfo on OMHRS_SecAA.AbstractID = OMHRS_RecInfo.AbstractID
        where OMHRS_SecAA.abstractid in (
			select abstractid from ab_main where universalid in (
			select UniversalID from MRG_Record where ID = @OldUpdateID)
			And apptype = 7)  And IsDeleted <> 3
			
		Update CC_Demographic 
		set Chartnumber = @ChartNumberFrom, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberFrom)  --PR - 06021  
		where abstractid in (
			select abstractid from ab_main where universalid in (
			select UniversalID from MRG_Record where ID = @OldUpdateID)
			And apptype = 8)

		--Audit Volumes updated and update volumes
		--Get the volumes that were merged
		select volumeidFrom as VIDFrom, volumeidTo as VIDTo, universalid as UID, 0 as Appt, null as AID
		into #RecordsFromUnmerge from MRG_Volume2 where ID = @OldUpdateID
		Update #RecordsFromUnmerge set Appt = AppType, AID = Abstractid from AB_Main where UID = Universalid
		--Update Volume Reference in AB_Main
		Update AB_Main set VolumeID = VIDFrom from #RecordsFromUnmerge where Universalid = UID
		--Update Volume Reference in AB_Abstract
		Update AB_Abstract set VolumeID = VIDFrom from #RecordsFromUnmerge 
		where AbstractID = AID and Appt in (1, 2, 5, 101, 102, 105) 
		--Audit Volume Changes
		Insert into MRG_Volume2 select @UpdateID, VIDTo, VIDFrom, UID from #RecordsFromUnmerge
		--Unlock CPI
		Delete CM_CPI_ChartLocked where PatientID = @PIDFrom
		--Audit Deficiencies updated and update Deficiencies
        --EN-00183
		Insert into MRG_Deficiency select @UpdateID, DeficiencyID, DefID from MRG_Deficiency where ID = @OldUpdateID
		--Update Def_SlipMain set DefPatientID = @PIDFrom where DefeciencyID in (Select DeficiencyID from MRG_Deficiency where ID = @OldUpdateID)
		Update Def_SlipMain set DefPatientID = @PIDFrom where DefID in (Select DefID from MRG_Deficiency where ID = @OldUpdateID)

		--Audit ROIs updated and update ROIs
		Insert into MRG_ROI select @UpdateID, ROIID from MRG_ROI where ID = @OldUpdateID
		Update ROI_Main 
		set Chartnumber = @ChartNumberFrom --, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberFrom)  --PR - 06021 
		where ROIID in (Select ROIID from MRG_ROI where ID = @OldUpdateID)
		
		Exec I_CM_History @PIDFrom, @Coder
		Exec I_CM_History @PIDTo, @Coder

		--**Update Master Child relationship. 
		Declare @MasterFromU as int
		Select @MasterFromU = MasterChartFrom from MRG_Masterchild where ID = @OldUpdateID
		Update CM_CPI set MasterChart = @MasterFromU where PatientID = @PIDFrom
		Insert into MRG_Masterchild values (@UpdateID, @PIDTo, @MasterFromU)
		--Audit abstracts Updated
		Insert into MRG_Record select @UpdateID, UniversalID from AB_Main where chartnumber = @ChartNumberFrom
		--Update AB_Main table for all abstracts effected
		Update AB_Main 
		set PatientID = @PIDFrom, chartnumber = @ChartNumberFrom, RegionalPatientID = @NewULI,
		    FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberFrom)  --PR - 06021  
		where UniversalID in (select UniversalID from MRG_Record where ID = @OldUpdateID) and  apptype <> 0
		exec U_AB_Main @PIDFrom, 0
		Insert into MRG_Main values (@UpdateID, @PIDFrom, @ChartNumberFrom, @PIDTo, @ChartNumberTo, 
		@OrgFirstName, @OrgLastName, 'Unmerged', getdate(), @Coder)
END
else if isnull(@MergeChange, 0)= 3   --PR - 04076 
Begin
	if isnull(@PIDFrom, 0) = 0 and isnull(@PIDTo, 0) <> 0 
	Begin
	
		Update CM_CPI 
		set chartnumber = @ChartNumberFrom, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberFrom)  --PR - 06021 
		Where PatientID = @PIDTo
		--0244 
		if @HospIDTo is null set @HospIDTo = 0
		Update CM_CPI set [MothersChart] = @ChartNumberFrom where [MothersChart] = @ChartNumberTo and (isnull(HospitalID, 0) in (@HospIDTo, 0) or @HospIDTo = 0)
		Update CM_BabyChart set [BabyChartNumber] = @ChartNumberFrom 
		from CM_BabyChart b inner join CM_CPI cpi on b.PatientID = cpi.PatientID
		where [BabyChartNumber] = @ChartNumberTo and (isnull(HospitalID, 0) in (@HospIDTo, 0) or @HospIDTo = 0)

		Update RH_ClientInfo 
		set Chartnumber = @ChartNumberFrom, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberFrom)  --PR - 06021 
        where chartnumber = @ChartNumberTo AND IsDeleted <> 3
            and (isnull(HospitalID, 0) = 0 or @HospIDTo = case @HospIDTo when 0 then 0 else isnull(HospitalID, 0) end)			 -- PR - 03348

		Update CRS_Demographic 
		set Chartnumber = @ChartNumberFrom, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberFrom)  --PR - 06021  
        where chartnumber = @ChartNumberTo AND IsDeleted <> 3
            and (isnull(HospitalID, 0) = 0 or @HospIDTo = case @HospIDTo when 0 then 0 else isnull(HospitalID, 0) end)			 -- PR - 03348
		
		Update OMHRS_SecAA 
		set Chartnumber = @ChartNumberFrom, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberFrom)  --PR - 06021 
        where chartnumber = @ChartNumberTo 
            and (isnull(HospitalID, 0) = 0 or @HospIDTo = case @HospIDTo when 0 then 0 else isnull(HospitalID, 0) end)			 -- PR - 03348
		
		Update CC_Demographic 
		set Chartnumber = @ChartNumberFrom, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberFrom)  --PR - 06021  
        where chartnumber = @ChartNumberTo 
            and (isnull(HospitalID, 0) = 0 or @HospIDTo = case @HospIDTo when 0 then 0 else isnull(HospitalID, 0) end)			 -- PR - 03348


		Update ab_abstract 
		set Chartnumber = @ChartNumberFrom, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberFrom)  --PR - 06021 
        where chartnumber = @ChartNumberTo AND IsDeleted <> 3
            and (isnull(HospitalID, 0) = 0 or @HospIDTo = case @HospIDTo when 0 then 0 else isnull(HospitalID, 0) end)			 -- PR - 03348

		Update roi_main 
		set Chartnumber = @ChartNumberFrom --, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberFrom)  --PR - 06021 
        where chartnumber = @ChartNumberTo 
            and (isnull(HospitalID, 0) = 0 or @HospIDTo = case @HospIDTo when 0 then 0 else isnull(HospitalID, 0) end)			 -- PR - 03348
		
		--Added for Visit History
		Update AB_Main 
		set PatientID = @PIDTo, chartnumber = @ChartNumberFrom, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberFrom)  --PR - 06021 
        where chartnumber =  @ChartNumberTo  and apptype <> 0
            and (isnull(HospitalID, 0) = 0 or @HospIDTo = case @HospIDTo when 0 then 0 else isnull(HospitalID, 0) end)			 -- PR - 03348
		exec U_AB_Main @PIDTo, 0

		Exec I_CM_History @PIDTo, @Coder
       
	    Insert into MRG_Main values (@UpdateID, @PIDTo, @ChartNumberFrom, @PIDTo, @ChartNumberTo, 
	    '', '', 'UnChanged', getdate(), @Coder)
	End
End

set @Error = 0  --PR - 03348

ProcedureFinish:
    return (@Error)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create procedure [P_CPIMerge_Check]
    @PatientID int
as
    declare @masterchart int
    set @masterchart = (select top 1 masterchart from cm_cpi where PatientID = @PatientID )
    select PatientID, ChartNumber
    from cm_cpi
    where patientid = @masterchart

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_CPIMerge_GetRelocateVisit]
	@SourceChartNumber as VarChar(20), 
	@TargetChartNumber as VarChar(20),
	@HospitalID as int = 0
AS  
	set nocount on

    select UniversalID, CNFrom, ChartTo, max(UniversalID) maxDate into #Relocate 
    from dbo.MRG_Relocate
    where ChartTo = @TargetChartNumber and @SourceChartNumber = CNFrom
    group by UniversalID, CNFrom, ChartTo    
    
    SELECT	dbo.AB_Main.UniversalID, dbo.AB_Main.AbstractID, dbo.AB_Main.AppID, 
		dbo.AB_Main.ICDType, 
		dbo.LU_CareType.DisplayCode AS CareType, 
		dbo.H_InstitutionProfile.DisplayCode AS Inst, 
		dbo.H_InstitutionProfile.UserDescription AS InstD, 
		CONVERT(VarChar(10), dbo.AB_Main.AdmitDate, 111) AS [Admit Date], 
		CONVERT(VarChar(10), dbo.AB_Main.DischargeDate, 111) AS [Discharge Date], 
		dbo.AB_Main.EncounterNumber AS [Enc. Num.], 
		CAST(dbo.AB_Main.EncounterSequence AS varchar(3)) AS [Enc. Seq.], 
		dbo.LU_MISCode.DisplayCode AS MISCode, 
		dbo.LU_AbstractStatus.DisplayCode AS DCStatus, 
		dbo.LU_AbstractStatus.UserDescription AS Status, 
		dbo.LU_YesBlank.DisplayCode AS Died, 
		LU_YesBlank_1.DisplayCode AS Trans, 
		LU_YesBlank_2.DisplayCode AS MDAS, 
		dbo.H_InstitutionProfile.LockDownDate, CAST('Open' AS varchar(10)) AS Lockdown, 
		dbo.AB_Main.HospitalID, 
		(select top 1 UserDescription from H_HospitalProfile where isnull(Code, 0) = isnull(dbo.AB_Main.HospitalID, -1)) as [HospitalIDD],
		12345 AS AssType, 
		dbo.AB_Main.RegisterNumber, 
		CONVERT(VarChar(10), dbo.AB_Main.AdmitDate, 111) AS [Visit Date], 
		dbo.LU_CodeFile.DisplayCode AS AmcareCareType,
--	 	(select top 1 DisplayCode from H_HospitalProfile as H where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID] --NP-00025
		cast('' as varchar(50)) as [Hosp ID], --PR - 00901
		(select top 1 DisplayCode from LU_NurseArea where isnull(Code, 0) = isnull(AdmittingNurseArea, 0)) as [AdmittingNurseArea],
		(select top 1 UserDescription from LU_NurseArea where isnull(Code, 0) = isnull(AdmittingNurseArea, 0)) as [AdmittingNurseAreaD],
		(select top 1 DisplayCode from LU_Provider where isnull(Code, 0) = isnull(AttendingPhysician, 0)) as [AttendingPhysician],
		(select top 1 UserDescription from LU_Provider where isnull(Code, 0) = isnull(AttendingPhysician, 0)) as [AttendingPhysicianD],
		(select top 1 DisplayCode from LU_Provider where isnull(Code, 0) = isnull(RefPhysician, 0)) as [RefPhysician],
		(select top 1 UserDescription from LU_Provider where isnull(Code, 0) = isnull(RefPhysician, 0)) as [RefPhysicianD],
		(select top 1 DisplayCode from ICD_DiagFile10 where isnull(Code, 0) = isnull(DiagnosisCode, 0)) as [DiagnosisCode],
		(select top 1 UserDescription from ICD_DiagFile10 where isnull(Code, 0) = isnull(DiagnosisCode, 0)) as [DiagnosisCodeD],
		(select top 1 DisplayCode from ICD_ProcFile10 where isnull(Code, 0) = isnull(IntervCode, 0)) as [IntervCode],
		(select top 1 UserDescription from ICD_ProcFile10 where isnull(Code, 0) = isnull(IntervCode, 0)) as [IntervCodeD],
		(select top 1 DisplayCode from LU_PatientType where isnull(Code, 0) = isnull(AB_Main.PatientType, 0)) as [PType], --PR-01802
		(select top 1 UserDescription from LU_PatientType where isnull(Code, 0) = isnull(AB_Main.PatientType, 0)) as [PTypeD] --PR-01802
	Into #VHTemp
	from dbo.MRG_Relocate m
        inner join dbo.ab_main ab on m.UniversalID = ab.UniversalID
        inner join #Relocate z on m.UniversalID = z.UniversalID and m.RelocateDate = z.maxDate
        left join dbo.LU_YesBlank AS LU_YesBlank_2 ON dbo.AB_Main.HasDAS = LU_YesBlank_2.Code 
        LEFT OUTER JOIN dbo.LU_YesBlank AS LU_YesBlank_1 ON dbo.AB_Main.HasTrans = LU_YesBlank_1.Code 
        LEFT OUTER JOIN	dbo.LU_YesBlank ON dbo.AB_Main.DeathIndicator = dbo.LU_YesBlank.Code 
        LEFT OUTER JOIN	dbo.H_InstitutionProfile ON dbo.AB_Main.InstitutionNumber = dbo.H_InstitutionProfile.Code
        left join dbo.LU_MISCode  on dbo.LU_MISCode.Code = dbo.AB_Main.MISCode
        left join dbo.LU_CareType on dbo.LU_CareType.Code = dbo.AB_Main.AppType
        left join dbo.LU_AbstractStatus on dbo.LU_AbstractStatus.Code = dbo.AB_Main.IsValidated
        left join dbo.LU_CodeFile  on dbo.LU_CodeFile.Code = dbo.LU_MISCode.AMCareType
	WHERE (dbo.AB_Main.IsDeleted = 2) and
        (ISNULL(AB_Main.HospitalID, 0) = 0 OR @HospitalID = case @HospitalID when 0 then 0 else ISNULL(AB_Main.HospitalID, 0) end) 	
        AND (dbo.AB_Main.AppType <> 0) 

	--Restrict by hospital
	if isnull(@HospitalID, 0) <> 0
		Delete #VHTemp where isnull(HospitalID, 0) <> @HospitalID and isnull(HospitalID, 0) <> 0 
		--Delete #VHTemp where HospitalID
	Update #VHTemp set [Hosp ID] = DisplayCode from H_HospitalProfile where code = #VHTemp.hospitalid--PR - 00901
	--Format Encounter Number Sequence
	Update #VHTEmp set [Enc. Seq.] = REPLACE(SPACE(3-LEN(ISNULL(CONVERT(VARCHAR(3),[Enc. Seq.]), 0))) + ISNULL(CONVERT(VARCHAR(3),[Enc. Seq.]), 0), ' ', '0')
	where [Enc. Seq.] is not null
	--Set Lockdown Status Flag
	Update #VHTEmp set LockDown = 'Locked' where lockdowndate > [Admit Date] and appid in (301,401)
	Update #VHTEmp set LockDown = 'Locked' where lockdowndate > [Discharge Date] and appid not in (301,401)
	--Update non Abstracts
	Update #VHTEmp set abstractid = universalID where appid = 3
	--Update Care Type
	-- AMCARE - EMERG CASES 
	Update #VHTEmp set CareType = AmcareCareType where appid in (301, 401)
	Update #VHTEmp set CareType = 'B' where appid in (301, 401) and CareType is null

	-- REHAB ADMISSION
	Update #VHTEmp set CareType = 'R-1' where appid = 250
	-- REHAB ADMISSION
	Update #VHTEmp set CareType = 'R-2' where appid = 251
	-- REHAB ADMISSION
	Update #VHTEmp set CareType = 'R-3' where appid = 252
	--Rehab Interm
	delete #VHTEmp where appid = 253
	-- OMHRS ADMISSION
	Update #VHTEmp set CareType = 'M-A' where appid = 650
	-- OMHRS Short Stay
	Update #VHTEmp set CareType = 'M-S' where appid = 651
	-- OMHRS Quarterly
	Update #VHTEmp set CareType = 'M-Q' where appid = 652
	-- OMHRS Change
	Update #VHTEmp set CareType = 'M-C' where appid = 653
	-- OMHRS Discharge
	Update #VHTEmp set CareType = 'M-D' where appid = 654


	If Exists (select * from #VHTEmp where left(CareType, 1) = 'R')
	Begin
		Update #VHTEmp set [Visit Date] = [Discharge Date] where caretype in ('R-2')
		Update #VHTEmp set [Visit Date] = CONVERT(VarChar(10), FollowUpDate, 111) from RH_ClientInfo where RH_ClientInfo.AbstractID = 
			#VHTEmp.AbstractID and #VHTEmp.appid = 252
	End

	--Get Assessment type if there are any CCRS
	If Exists (select * from #VHTEmp where CareType = 'L')
	Begin
		Update #VHTEmp set AssType = AA8 from CRS_Demographic where CRS_Demographic.abstractid = 
		#VHTEmp.AbstractID and CareType = 'L'
		-- CCRS ADMISSION BG 
		Update #VHTEmp set CareType = 'L-0A' where appid = 470 and AssType = 14501
		--  CCRS DEMO CHANGES 
		Update #VHTEmp set CareType = 'L-00' where appid = 471 and AssType = 14500
		-- CCRS ADMIT ASSESS 
		Update #VHTEmp set CareType = 'L-01' where appid = 473 and AssType = 14502
		-- CCRS FULL ASSESS
		Update #VHTEmp set CareType = 'L-02' where appid = 473 and AssType = 14503
		-- CCRS FULL ASSESS CHANGE
		Update #VHTEmp set CareType = 'L-03' where appid = 473 and AssType = 14504
		-- CCRS FULL ASSESS CORRECT 
		Update #VHTEmp set CareType = 'L-04' where appid = 473 and AssType = 14505
		-- CCRS QUARTER ASSESS 
		Update #VHTEmp set CareType = 'L-05' where appid = 472 and AssType = 14506
		-- CCRS QUARTER ASSESS CHANGE/CORRECT 
		Update #VHTEmp set CareType = 'L-10' where appid = 472 and AssType = 14511
		-- CCRS DISCHARGE W/OUT RETURN  
		Update #VHTEmp set CareType = 'L-06' where appid = 474 and AssType = 14507
		-- CCRS DISCHARGE W/ RETURN 
		Update #VHTEmp set CareType = 'L-07' where appid = 474 and AssType = '14508'
		-- CCRS DISCHARGE W/OUT ASSESSMENT
		Update #VHTEmp set CareType = 'L-08' where appid = 474 and AssType = '14509'
		-- CCRS RE-ENTRY
		Update #VHTEmp set CareType = 'L-09' where appid = 475 and AssType = '14510'
		--Update Display Dates for CCRS
		Update #VHTEmp set [Visit Date] = [Discharge Date] where caretype in ('L-06', 'L-07', 'L-08')
		Update #VHTEmp set [Visit Date] = CONVERT(VarChar(10), Z7, 111) from CRS_Demographic where caretype in ('L-00') and
			CRS_Demographic.AbstractID = #VHTEmp.AbstractID
		--Added L-01 and l-02 for Hong 2006/01/19
		Update #VHTEmp set [Visit Date] = CONVERT(VarChar(10), A3, 111) from CRS_Demographic where caretype in ('L-02', 'L-01', 'L-03', 'L-04', 'L-05', 'L-10') and
			CRS_Demographic.AbstractID = #VHTEmp.AbstractID
		Update #VHTEmp set [Visit Date] = CONVERT(VarChar(10), AB1b, 111) from CRS_Demographic where caretype in ('L-09') and
			CRS_Demographic.AbstractID = #VHTEmp.AbstractID
	End

	-- PR - 03302 - CCO
	--Get Diagnosis Code if there are any Cancer Care 
	If Exists (select * from #VHTEmp where AppID = 675)
	Begin
				
		Update #VHTEmp set #VHTEmp.DiagnosisCode  = case when CC_DiseaseRegister.DiagnosisCode = 0 then null else CC_DiseaseRegister.DiagnosisCode end 
		from CC_DiseaseRegister where CC_DiseaseRegister.abstractid = #VHTEmp.AbstractID and AppID = 675

		-- Diagnosis Code Description 
		Update #VHTEmp set DiagnosisCodeD = UserDescription  from ICD_DiagFile10 where isnull(Code, 0) = isnull(DiagnosisCode, 0)
		and AppID = 675
		Update #VHTEmp set #VHTEmp.DiagnosisCode  = DisplayCode from ICD_DiagFile10 where isnull(Code, 0) = isnull(DiagnosisCode, 0)
		and AppID = 675		
		
	End


	Update #VHTEmp set [Visit Date] = [Discharge Date] where appid in (201, 101, 100, 200, 202, 102)
	Update #VHTEmp set ICDType = 'T' where appid in (650, 651, 652, 653, 654) and isnull(icdtype, '') = '' 

	set nocount off


	--If it is detail search
	
	Select UniversalID, AbstractID, AppID, ICDType, 
		[Hosp ID],
		HospitalIDD as [Hospital Desc],
		CareType as [Care], 
		[PType] as [Patient Type], --PR-01802
		[PTypeD] as [Patient Type Desc], --PR-01802
		Inst, 
		InstD as [Inst Desc], 
		[Admit Date], 
		[Discharge Date], 
		[Enc. Num.], 
		[Enc. Seq.], 
		RegisterNumber as [Reg Num], 
		MISCode as [MIS Code], 
		[AdmittingNurseArea] as [Nurse Unit],
		[AdmittingNurseAreaD] as [Nurse Unit Desc],
		[AttendingPhysician] as [Att. Provider],
		[AttendingPhysicianD] as [Att. Provider Desc],
		[RefPhysician] as [Ref. Provider],
		[RefPhysicianD] as [Ref. Provider Desc],
		[DiagnosisCode] as [Diag Code],
		[DiagnosisCodeD] as [Diag Code Desc],
		[IntervCode] as [Interv Code], 
		[IntervCodeD] as [Interv Code Desc], 
		Status, 
		Died, 
		Trans, 
		MDAS, 
		Lockdown as [Locked] 
	from #VHTEmp
	ORDER BY [Hosp ID], [Admit Date] DESC, [Discharge Date] DESC





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [P_CPIMerge_GetVisitForRelocate]
	@ChartNumber as VarChar(10), 
	@ChartNumber2 as VarChar(10),
	@HospID as int = 0
--	@SearchType as int = 0
AS  
	set nocount on

	SELECT	dbo.AB_Main.UniversalID, dbo.AB_Main.AbstractID, dbo.AB_Main.AppID, 
		dbo.AB_Main.ICDType, 
		dbo.LU_CareType.DisplayCode AS CareType, 
		dbo.H_InstitutionProfile.DisplayCode AS Inst, 
		dbo.H_InstitutionProfile.UserDescription AS InstD, 
		CONVERT(VarChar(10), dbo.AB_Main.AdmitDate, 111) AS [Admit Date], 
		CONVERT(VarChar(10), dbo.AB_Main.DischargeDate, 111) AS [Discharge Date], 
		dbo.AB_Main.EncounterNumber AS [Enc. Num.], 
		CAST(dbo.AB_Main.EncounterSequence AS varchar(3)) AS [Enc. Seq.], 
		dbo.LU_MISCode.DisplayCode AS MISCode, 
		dbo.LU_AbstractStatus.DisplayCode AS DCStatus, 
		dbo.LU_AbstractStatus.UserDescription AS Status, 
		dbo.LU_YesBlank.DisplayCode AS Died, 
		LU_YesBlank_1.DisplayCode AS Trans, 
		LU_YesBlank_2.DisplayCode AS MDAS, 
		dbo.H_InstitutionProfile.LockDownDate, CAST('Open' AS varchar(10)) AS Lockdown, 
		dbo.AB_Main.HospitalID, 
		(select top 1 UserDescription from H_HospitalProfile where isnull(Code, 0) = isnull(dbo.AB_Main.HospitalID, -1)) as [HospitalIDD],
		12345 AS AssType, 
		dbo.AB_Main.RegisterNumber, 
		CONVERT(VarChar(10), dbo.AB_Main.AdmitDate, 111) AS [Visit Date], 
		dbo.LU_CodeFile.DisplayCode AS AmcareCareType,
--	 	(select top 1 DisplayCode from H_HospitalProfile as H where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID] --NP-00025
		cast('' as varchar(12)) as [Hosp ID], --PR - 00901
		(select top 1 DisplayCode from LU_NurseArea where isnull(Code, 0) = isnull(AdmittingNurseArea, 0)) as [AdmittingNurseArea],
		(select top 1 UserDescription from LU_NurseArea where isnull(Code, 0) = isnull(AdmittingNurseArea, 0)) as [AdmittingNurseAreaD],
		(select top 1 DisplayCode from LU_Provider where isnull(Code, 0) = isnull(AttendingPhysician, 0)) as [AttendingPhysician],
		(select top 1 UserDescription from LU_Provider where isnull(Code, 0) = isnull(AttendingPhysician, 0)) as [AttendingPhysicianD],
		(select top 1 DisplayCode from LU_Provider where isnull(Code, 0) = isnull(RefPhysician, 0)) as [RefPhysician],
		(select top 1 UserDescription from LU_Provider where isnull(Code, 0) = isnull(RefPhysician, 0)) as [RefPhysicianD],
		(select top 1 DisplayCode from ICD_DiagFile10 where isnull(Code, 0) = isnull(DiagnosisCode, 0)) as [DiagnosisCode],
		(select top 1 UserDescription from ICD_DiagFile10 where isnull(Code, 0) = isnull(DiagnosisCode, 0)) as [DiagnosisCodeD],
		(select top 1 DisplayCode from ICD_ProcFile10 where isnull(Code, 0) = isnull(IntervCode, 0)) as [IntervCode],
		(select top 1 UserDescription from ICD_ProcFile10 where isnull(Code, 0) = isnull(IntervCode, 0)) as [IntervCodeD],
		(select top 1 DisplayCode from LU_PatientType where isnull(Code, 0) = isnull(AB_Main.PatientType, 0)) as [PType], --PR-01802
		(select top 1 UserDescription from LU_PatientType where isnull(Code, 0) = isnull(AB_Main.PatientType, 0)) as [PTypeD] --PR-01802
	Into #VHTemp
	FROM  dbo.LU_CareType RIGHT OUTER JOIN
	dbo.LU_AbstractStatus RIGHT OUTER JOIN
	dbo.LU_CodeFile RIGHT OUTER JOIN
	dbo.LU_MISCode ON dbo.LU_CodeFile.Code = dbo.LU_MISCode.AMCareType RIGHT OUTER JOIN
	dbo.AB_Main ON dbo.LU_MISCode.Code = dbo.AB_Main.MISCode ON dbo.LU_AbstractStatus.Code = dbo.AB_Main.IsValidated ON --PR-01866 IsCompleted
	dbo.LU_CareType.Code = dbo.AB_Main.AppType LEFT OUTER JOIN
	dbo.LU_YesBlank AS LU_YesBlank_2 ON dbo.AB_Main.HasDAS = LU_YesBlank_2.Code LEFT OUTER JOIN
	dbo.LU_YesBlank AS LU_YesBlank_1 ON dbo.AB_Main.HasTrans = LU_YesBlank_1.Code LEFT OUTER JOIN
	dbo.LU_YesBlank ON dbo.AB_Main.DeathIndicator = dbo.LU_YesBlank.Code LEFT OUTER JOIN
	dbo.H_InstitutionProfile ON dbo.AB_Main.InstitutionNumber = dbo.H_InstitutionProfile.Code
	WHERE (dbo.AB_Main.IsDeleted = 2) AND (dbo.AB_Main.AppType <> 0) AND (dbo.AB_Main.ChartNumber IN (@ChartNumber, @ChartNumber2))

	--Restrict by hospital
	if isnull(@HospID, 0) <> 0
		Delete #VHTemp where isnull(HospitalID, 0) <> @HospID and isnull(HospitalID, 0) <> 0 -- [RM - PR-00599] 2006/04/03

	Update #VHTemp set [Hosp ID] = DisplayCode from H_HospitalProfile where code = #VHTemp.hospitalid--PR - 00901
	--Format Encounter Number Sequence
	Update #VHTEmp set [Enc. Seq.] = REPLACE(SPACE(3-LEN(ISNULL(CONVERT(VARCHAR(3),[Enc. Seq.]), 0))) + ISNULL(CONVERT(VARCHAR(3),[Enc. Seq.]), 0), ' ', '0')
	where [Enc. Seq.] is not null
	--Set Lockdown Status Flag
	Update #VHTEmp set LockDown = 'Locked' where lockdowndate > [Admit Date] and appid in (301,401)
	Update #VHTEmp set LockDown = 'Locked' where lockdowndate > [Discharge Date] and appid not in (301,401)
	--Update non Abstracts
	Update #VHTEmp set abstractid = universalID where appid = 3
	--Update Care Type
	-- AMCARE - EMERG CASES 
	Update #VHTEmp set CareType = AmcareCareType where appid in (301, 401)
	Update #VHTEmp set CareType = 'B' where appid in (301, 401) and CareType is null

	-- REHAB ADMISSION
    Delete #VHTEmp where appid in (251, 252, 253)

	Update #VHTEmp 
    set [Discharge Date] = convert(varchar(20), DischargeDate, 111)
    from RH_ClientInfo r
        inner join #VHTemp z on r.LinkID = z.AbstractID
    where r.DischargeDate is not null
        and [Discharge Date] is null and z.Appid = 250

	-- OMHRS ADMISSION
    Delete #VHTEmp where appid between 652 and 654
	Update #VHTEmp set CareType = 'M' where appid = 650
	-- OMHRS Short Stay
	Update #VHTEmp set CareType = 'M-S' where appid = 651

	Update #VHTEmp 
    set [Discharge Date] = convert(varchar(20), s.X80, 111)
    from OMHRS_SecAA r
        inner join #VHTemp z on r.LinkID = z.AbstractID
        inner join dbo.OMHRS_SecS s on r.AbstractID = s.AbstractID
    where s.X80 is not null
        and [Discharge Date] is null and z.Appid = 650


	--CCRS Background
    Delete from #VHTEmp where appid in (471, 472, 473, 474, 475)

	Update #VHTEmp set AssType = AA8 from CRS_Demographic where CRS_Demographic.abstractid = 
	#VHTEmp.AbstractID and CareType = 'L'
	Update #VHTEmp 
    set [Discharge Date] = convert(varchar(20), DischargeDate, 111)
    from (select linkid, max(dischargedate) as dischargedate from CRS_Demographic where dischargedate is not null group by linkid) r
        inner join #VHTemp z on r.LinkID = z.AbstractID
    where r.DischargeDate is not null
        and [Discharge Date] is null and z.Appid = 470


	-- PR - 03302 - CCO
	--Get Diagnosis Code if there are any Cancer Care 
	If Exists (select * from #VHTEmp where AppID = 675)
	Begin
				
		Update #VHTEmp set #VHTEmp.DiagnosisCode  = case when CC_DiseaseRegister.DiagnosisCode = 0 then null else CC_DiseaseRegister.DiagnosisCode end 
		from CC_DiseaseRegister where CC_DiseaseRegister.abstractid = #VHTEmp.AbstractID and AppID = 675

		-- Diagnosis Code Description 
		Update #VHTEmp set DiagnosisCodeD = UserDescription  from ICD_DiagFile10 where isnull(Code, 0) = isnull(DiagnosisCode, 0)
		and AppID = 675
		Update #VHTEmp set #VHTEmp.DiagnosisCode  = DisplayCode from ICD_DiagFile10 where isnull(Code, 0) = isnull(DiagnosisCode, 0)
		and AppID = 675		
		
	End


	Update #VHTEmp set [Visit Date] = [Discharge Date] where appid in (201, 101, 100, 200, 202, 102)
	Update #VHTEmp set ICDType = 'T' where appid in (650, 651, 470, 250) and isnull(icdtype, '') = '' --PR - 00997

	set nocount off


	--If it is detail search
	--If @SearchType = 1
		Select UniversalID, AbstractID, AppID, ICDType, 
			[Hosp ID],
			HospitalIDD as [Hospital Desc],
			CareType as [Care], 
			[PType] as [Patient Type], --PR-01802
			[PTypeD] as [Patient Type Desc], --PR-01802
			Inst, 
			InstD as [Inst Desc], 
			[Admit Date], 
			[Discharge Date], 
			[Enc. Num.], 
			[Enc. Seq.], 
			RegisterNumber as [Reg Num], 
			MISCode as [MIS Code], 
			[AdmittingNurseArea] as [Nurse Unit],
			[AdmittingNurseAreaD] as [Nurse Unit Desc],
			[AttendingPhysician] as [Att. Provider],
			[AttendingPhysicianD] as [Att. Provider Desc],
			[RefPhysician] as [Ref. Provider],
			[RefPhysicianD] as [Ref. Provider Desc],
			[DiagnosisCode] as [Diag Code],
			[DiagnosisCodeD] as [Diag Code Desc],
			[IntervCode] as [Interv Code], 
			[IntervCodeD] as [Interv Code Desc], 
			Status, 
			Died, 
			Trans, 
			MDAS, 
			Lockdown as [Locked] 
		from #VHTEmp
		ORDER BY [Hosp ID], [Admit Date] DESC, [Discharge Date] DESC

--	--If it is main screen search
--	Else
--		--PR-01802: Added Patient Type
--		Select UniversalID, AbstractID, AppID, DCStatus, [Hosp ID], CareType as [Care], [PType] as [Patient Type], Inst, [Visit Date] 
--        from #VHTEmp
--		ORDER BY [Hosp ID], [Admit Date] DESC, [Discharge Date] DESC






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [P_CPIMerge_RecordFlag]
AS
	Declare @MergeID as uniqueidentifier
	Declare @ChartNumberTo as varchar(10)
	Declare @ChartNumberFrom as varchar(10)
	Declare @UpdateType as VarChar(10)

	select top 1 @MergeID = id, @ChartNumberTo = chartnumberTo, @UpdateType = UpdateType 
	from MRG_Main order by datemerged desc

	if isnull(@UpdateType, '') <> 'Merged'
		goto ProcedureFinish 
	Declare @CurserValue1 as int
	Declare @CurserValue2 as Varchar(2)
	Declare @CurserValue3 as varchar(2)
-----------------------
	create table #UID(
		universalID int
	)
	Create table #AID(
		abstractid int
	)

	insert #UID select universalid From MRG_Record where id = @MergeID
	create index IX_UID_universalid on #UID(universalid)
	insert #AID select ab_main.abstractid from ab_main 
		join #UID on #UID.universalid = ab_main.universalid
		where apptype in (1, 2, 5)
	create index IX_AID_Abstractid on #AID(Abstractid)
----------------------	
	Declare Cur_Temp cursor for
	SELECT dbo.AB_Abstract.AbstractID, dbo.AB_Abstract.ICDType,
	(SELECT DisplayCode FROM dbo.LU_CareType WHERE (Code = dbo.AB_Abstract.CareType)) AS Care
	FROM dbo.AB_Abstract LEFT OUTER JOIN dbo.H_InstitutionProfile ON 
	dbo.AB_Abstract.InstitutionNumber = dbo.H_InstitutionProfile.Code
	join #AID on AB_Abstract.AbstractID = #AID.AbstractID    ---New Change
-- 	where Abstractid in (select abstractid from ab_main where universalid in 
-- 	(select universalid From MRG_Record where id = @MergeID) and apptype in (1, 2, 5)) 
--	and  batchyear = cihiyear and IsSubmited = 1 and IsDeleted = 2
	where  batchyear = cihiyear and IsSubmited = 1 and IsDeleted = 2

 	OPEN Cur_Temp
	fetch next from Cur_Temp    
	into @CurserValue1, @CurserValue2, @CurserValue3
	while @@fetch_status = 0    
	begin    
		exec [P_updateAbstractForCorrection] @CurserValue1, @ChartNumberTo, @CurserValue2, @CurserValue3, 1
		fetch next from Cur_Temp    
		into @CurserValue1, @CurserValue2, @CurserValue3
	   
	end
	Close Cur_Temp
	Deallocate Cur_Temp

ProcedureFinish:
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [P_CPIMerge_RegionalPatientID]
	@ChartNumberFrom as VarChar(10),
	@RegionalPIDFrom as varchar(50) = null,
	@ChartNumberTo   as VarChar(10) = null,
	@RegionalPIDTo   as VarChar(50),
	@Coder       as int,
	@MergeChange as int = 0,    --0 = Merge, 1  = Unmerge
	@PIDFrom     as int = 0,    
	@PIDTo       as int = 0,    
	@HospIDFrom  as int = 0,
	@HospIDTo    as int = 0,
    @ID          as uniqueidentifier = null -- PR - 03348
AS
--  EN - 00508

	Declare @CurserValue as int
	Declare @CurserValue2 as int
	Declare @UpdateID as uniqueidentifier
    Declare @Error int -- PR - 03348
	
   
	
    set @Error = 1 -- PR - 03348
    if isnull(@PIDFrom, 0) = 0
    begin
        if isnull(@HospIDFrom, 0) = 0
    	    select top 1 @PIDFrom = patientid, @RegionalPIDFrom = RegionalPatientID , @HospIDFrom = isnull(HospitalID, 0) 
            from CM_CPI 
            where chartnumber = @ChartNumberFrom 
            order by isnull(HospitalID, 0)    
        else
    	    select top 1 @PIDFrom = patientid, @RegionalPIDFrom = RegionalPatientID
            from CM_CPI 
            where chartnumber = @ChartNumberFrom 
                and (isnull(HospitalID, 0) = 0 or @HospIDFrom = case @HospIDFrom when 0 then 0 else isnull(HospitalID, 0) end)			
            order by isnull(HospitalID, 0) desc   
    end

    if isnull(@PIDTo, 0) = 0
    begin
        if isnull(@HospIDTo, 0) = 0
			select top 1 @PIDTo = patientid, @ChartNumberTo = chartnumber, @HospIDTo = isnull(HospitalID, 0)
			from CM_CPI 
			where  RegionalPatientID = @RegionalPIDTo 
			order by isnull(HospitalID, 0)    
		else
			select top 1 @PIDTo = patientid, @ChartNumberTo = chartnumber
			from CM_CPI 
			where  RegionalPatientID = @RegionalPIDTo 
                and (isnull(HospitalID, 0) = 0 or @HospIDTo = case @HospIDTo when 0 then 0 else isnull(HospitalID, 0) end)			
			order by isnull(HospitalID, 0)    
    end
    
	Set @UpdateID = newid()

If isnull(@PIDFrom, 0) <> isnull(@PIDTo, 0) and isnull(@mergechange, 0) = 0 and isnull(@RegionalPIDTo, '') <> ''
Begin
	Update CM_CPI set RegionalPatientID = @RegionalPIDTo  where PatientID = @PIDFrom
	Update AB_Main set RegionalPatientID = @RegionalPIDTo  where PatientID = @PIDFrom and AppID = 0

	Update AB_Abstract set RegionalPatientID = @RegionalPIDTo
    where chartnumber = @ChartNumberFrom AND 
        (isnull(HospitalID, 0) = 0 or @HospIDFrom = case @HospIDFrom when 0 then 0 else isnull(HospitalID, 0) end)		

	Update AB_Main set RegionalPatientID = @RegionalPIDTo
	where chartnumber = @ChartNumberFrom and apptype <> 0
        and (isnull(HospitalID, 0) = 0 or @HospIDFrom = case @HospIDFrom when 0 then 0 else isnull(HospitalID, 0) end)		

	Insert into [dbo].[MRG_RegionalID](ID, PatientIDFrom, ChartNumberFrom, RegionPatientIDFrom, PatientIDTo, ChartNumberTo, RegionPatientIDTo, UpdateType, DateMerged, CoderNumber)
	select newid(), @PIDFrom, @ChartNumberFrom, @RegionalPIDFrom, @PIDTo, @ChartNumberTo, @RegionalPIDTo, 'Merged', getdate(), @Coder

end

else if isnull(@MergeChange, 0) = 1 --UnMerge
Begin
	if isnull(@RegionalPIDTo, '') = ''
	begin
		if @ID is null
			SELECT TOP 1 @RegionalPIDTo = RegionPatientIDFrom
			FROM [dbo].[MRG_RegionalID]
			WHERE (UpdateType = 'Merged') AND (ChartNumberFrom = @ChartNumberFrom) AND RegionPatientIDTo = @RegionalPIDFrom
			ORDER BY DateMerged DESC
		else 
			SELECT TOP 1 @RegionalPIDTo = RegionPatientIDFrom
			FROM [dbo].[MRG_RegionalID]
			WHERE [ID] = @ID and (UpdateType = 'Merged') AND (ChartNumberFrom = @ChartNumberFrom) 
			ORDER BY DateMerged DESC
	end
			
	Update CM_CPI set RegionalPatientID = @RegionalPIDTo  where PatientID = @PIDFrom
	Update AB_Main set RegionalPatientID = @RegionalPIDTo  where PatientID = @PIDFrom and AppID = 0

	Update AB_Abstract set RegionalPatientID = @RegionalPIDTo
    where chartnumber = @ChartNumberFrom AND 
        (isnull(HospitalID, 0) = 0 or @HospIDFrom = case @HospIDFrom when 0 then 0 else isnull(HospitalID, 0) end)		

	Update AB_Main set RegionalPatientID = @RegionalPIDTo
	where chartnumber = @ChartNumberFrom and apptype <> 0
        and (isnull(HospitalID, 0) = 0 or @HospIDFrom = case @HospIDFrom when 0 then 0 else isnull(HospitalID, 0) end)		

	Insert into [dbo].[MRG_RegionalID](ID, PatientIDFrom, ChartNumberFrom, RegionPatientIDFrom, PatientIDTo, ChartNumberTo, RegionPatientIDTo, UpdateType, DateMerged, CoderNumber)
	select newid(), @PIDFrom, @ChartNumberFrom, @RegionalPIDFrom, @PIDTo, @ChartNumberTo, @RegionalPIDTo, 'UnMerged', getdate(), @Coder
END

set @Error = 0  

ProcedureFinish:
    return (@Error)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_CPIMerge_Relocate] 
	@VisitsToMove as VarChar(500),
	@ChartNumberTo as VarChar(10),
	@Coder as int,
    @PIDTo as int = 0,
	@HospIDTo as int = 0
AS
	Declare @UpdateID as uniqueidentifier
	Declare @CountTo as int
	--Declare @PIDTo as int
	Declare @VolumeTo as int
	Declare @SQL as VarChar(1000)
    Declare @Error int
	Declare @NewULI varchar(20) --EN - 00511

	Set @UpdateID = newid()
	-- print @VisitsToMove

    set @Error = 1  --PR - 03348
    -- PR - 003348
    if isnull(@PIDTo, 0) = 0
    	select top 1 @PIDTo = patientid from CM_CPI where chartnumber = @ChartNumberTo and isnull(hospitalid, 0) in (0, @HospIDTo)
	if isnull(@PIDTo, 0) = 0
		goto ProcedureFinish 
	
	select top 1 @NewULI = RegionalPatientID from CM_CPI where PatientId = @PIDTo	--EN - 00511

    set @Error = 2  --PR - 03348
    set @CountTo = (select count(*) FROM dbo.CM_CPI_ChartLocked Where PatientID = @PIDTo)
--	set @CountTo = (select count(CM_CPI.patientid) FROM dbo.CM_CPI LEFT OUTER JOIN dbo.CM_CPI_ChartLocked 
--		ON dbo.CM_CPI.PatientID = dbo.CM_CPI_ChartLocked.PatientID WHERE CM_CPI.chartnumber = @ChartNumberTo
--		and isnull(hospitalid, 0) = isnull(@HospIDTo, 0) 
--        and MergeID IS NULL)
	if isnull(@CountTo, 0) > 0
		goto ProcedureFinish 

	CREATE TABLE #Relocate ( UID bigint, AID int, PIDFrom int, HID int, AType int,
		CN VarChar(10), VIDFrom int, VIDTo int, VDate Datetime)
	Set @SQL = 'select UniversalID, AbstractID, PatientID, isnull(hospitalid, 0), AppType, 
	Chartnumber, volumeid, cast(null as int), cast(dischargedate as datetime)
	from ab_main where universalid in (' + @VisitsToMove + ')'
	insert into #Relocate exec(@SQL)

--	select UniversalID as UID, AbstractID as AID, PatientID as PIDFrom, isnull(hospitalid, 0) as HID, AppType as AType, 
--	Chartnumber as CN, volumeid as VIDFrom, cast(null as int) as VIDTo, cast(dischargedate as datetime) as VDate
--	into #Relocate2 from ab_main where universalid in (@VisitsToMove)


	set @VolumeTo = (select top 1 volumeid from CM_CPI_Volume where patientid = @PIDTo order by volumenumber desc)
	set @VolumeTo = isnull(@VolumeTo, 0)
	
	if isnull(@PIDTo, 0) <> 0 
	Begin
		--
		--Get all the existing volumes of the chart to be merged into
		select volumeid, patientid, VolumeNumber, VolumeDateFrom, volumenDateTo, isnull(hospitalid, 0) as HospID
		into #VolumeTo From CM_CPI_Volume where patientid = @PIDTo
		--Figure out which volumes to move the vists to
		Update #Relocate set VIDTo = VolumeID from #VolumeTo 
		where VDate between VolumeDateFrom and volumenDateTo and HospID = HID

		--Audit Volume Changes
		Insert into MRG_Volume2 select @UpdateID, VIDFrom, VIDTo, UID from #Relocate

		--Rehab
		Update RH_ClientInfo 
		set Chartnumber = @ChartNumberTo, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)    --PR - 06021
		from #Relocate 
		where LinkID = AID and AType = 3
        --PR - 04076 use admission assessment
   		--where abstractid = AID and AType = 3
		Update AB_Main 
        set PatientID = @PIDTo, Chartnumber = @ChartNumberTo, VolumeID = z.VIDTo, RegionalPatientID = @NewULI ,
            FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)    --PR - 06021 
        from #Relocate z
            inner join RH_ClientInfo r on z.AID = r.LinkID and z.AType = 3
            inner join AB_Main m on r.AbstractID = m.AbstractID and m.AppType = 3
		--where UniversalID = UID

		--CCRS
		Update CRS_Demographic 
		set Chartnumber = @ChartNumberTo, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)    --PR - 06021 
		from #Relocate 
		where LinkID = AID and AType = 4
        --PR - 04076 use admission background
		--where abstractid = AID and AType = 4
		Update AB_Main 
        set PatientID = @PIDTo, Chartnumber = @ChartNumberTo, VolumeID = z.VIDTo, RegionalPatientID = @NewULI,
            FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)    --PR - 06021   
        from #Relocate z
            inner join CRS_Demographic r on z.AID = r.LinkID and z.AType = 4
            inner join AB_Main m on r.AbstractID = m.AbstractID and m.AppType = 4

		--OMHRS
		Update OMHRS_SecAA 
		set Chartnumber = @ChartNumberTo, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)    --PR - 06021 
		from #Relocate 
		where LinkID = AID and AType = 7
        --PR - 04076 use admission asessement only
		--where abstractid = AID and AType = 7
		Update AB_Main 
        set PatientID = @PIDTo, Chartnumber = @ChartNumberTo, VolumeID = z.VIDTo, RegionalPatientID = @NewULI,
            FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)    --PR - 06021   
        from #Relocate z
            inner join OMHRS_SecAA r on z.AID = r.LinkID and z.AType = 7
            inner join AB_Main m on r.AbstractID = m.AbstractID and m.AppType = 7

		--Cancer Care
		Update CC_Demographic 
		set Chartnumber = @ChartNumberTo, FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)    --PR - 06021 
		from #Relocate 
		where abstractid = AID and AType = 8
		--DAD, NACRS, SDS, CCR
		Update ab_abstract 
		set Chartnumber = @ChartNumberTo, VolumeID = VIDTo, RegionalPatientID = @NewULI,
		    FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)    --PR - 06021 
		from #Relocate 
		where abstractid = AID and AType in (1, 2, 5, 101, 102, 105) 
		--Visit History
		Update AB_Main 
		set PatientID = @PIDTo, Chartnumber = @ChartNumberTo, VolumeID = VIDTo, RegionalPatientID = @NewULI,
		    FixedChartNumber = [dbo].[GetFixedChartNumber](@ChartNumberTo)    --PR - 06021 
		from #Relocate 
		where UniversalID = UID
		--Chart Deficiency
--		Update def_slipmain set defvolumeid = VIDTo from #Relocate where defvolumeid = VIDFrom
		--Audit Trail
		Insert into MRG_Relocate select @UpdateID, CN, @ChartNumberTo, UID,  getdate(), @Coder from #Relocate

	end
    set @Error = 0  --PR - 03348

ProcedureFinish:
    return (@Error)








GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



-- This is called by DAD ICD 10 to display the List of Errors CIHI returns.
--Ticket 10666
CREATE  PROCEDURE [P_DADCIHIErrorList]
	@AbstractID AS INT,
    @Coder      as int
AS 
SELECT [ ] = AB_CIHIErrors.AbstractID
, [Err #] = dbo.M_DADErrors.ErrorNumber
, [Occurrence] = right(AB_CIHIErrors.GroupFieldOcc, 2)
, [Error] = (case (select top 1 LanguageID from U_Users where code = @Coder) when 10000 then M_DADErrors.FrenchDescription else dbo.M_DADErrors.EnglishDescription end)
, [CIHI File] = dbo.AB_CIHIErrors.ErrorFileName
FROM dbo.AB_CIHIErrors 
    join AB_Abstract on AB_CIHIErrors.AbstractID = AB_Abstract.AbstractID
    left JOIN dbo.M_DADErrors 
    ON (left(RTRIM(LTRIM(dbo.AB_CIHIErrors.GroupFieldOcc)), 4) + AB_CIHIErrors.ErrorNumber) = substring(RTRIM(LTRIM(dbo.M_DADErrors.ErrorNumber)), 2, 10)
        and AB_Abstract.BatchYear = M_DADErrors.BatchYear 
WHERE dbo.AB_CIHIErrors.AbstractID = @AbstractID



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [P_ELOSCalculate]
	@CMGYear as int
AS
	--Modify me after AgeLevel is set
	SELECT dbo.AB_CMG.CMG as TCMG, dbo.AB_CMG.Complexity as TPLX, 
	cast(avg(cast(dbo.AB_Abstract.LOSDays as decimal(8,1))) as decimal(8,1)) as TELOS, 
	3 as TAgeCode
	Into #TELOSCalc
	FROM dbo.AB_CMG LEFT OUTER JOIN
	dbo.AB_Abstract ON dbo.AB_CMG.AbstractID = dbo.AB_Abstract.AbstractID
	WHERE (dbo.AB_CMG.CMG_Year = @CMGYear) AND (dbo.AB_Abstract.AgeCode = 3) AND (dbo.AB_Abstract.AgeNumber > 68) AND 
	(dbo.AB_CMG.OccurrenceNumber = 1)
	group by cmg, complexity
	
	--Delete me after AgeLevel is set
	insert Into #TELOSCalc
	SELECT dbo.AB_CMG.CMG as TCMG, dbo.AB_CMG.Complexity as TPLX, 
	cast(avg(cast(dbo.AB_Abstract.LOSDays as decimal(8,1))) as decimal(8,1)) as TELOS, 
	2 as TAgeCode
	FROM dbo.AB_CMG LEFT OUTER JOIN
	dbo.AB_Abstract ON dbo.AB_CMG.AbstractID = dbo.AB_Abstract.AbstractID
	WHERE (dbo.AB_CMG.CMG_Year = @CMGYear) AND (dbo.AB_Abstract.AgeCode = 3) AND (dbo.AB_Abstract.AgeNumber BETWEEN 18 AND 68)
	and (dbo.AB_CMG.OccurrenceNumber = 1)
	group by cmg, complexity
	
	--Delete me after AgeLevel is set
	insert Into #TELOSCalc
	SELECT dbo.AB_CMG.CMG as TCMG, dbo.AB_CMG.Complexity as TPLX, 
	cast(avg(cast(dbo.AB_Abstract.LOSDays as decimal(8,1))) as decimal(8,1)) as TELOS, 
	1 as TAgeCode
	FROM dbo.AB_CMG LEFT OUTER JOIN
	dbo.AB_Abstract ON dbo.AB_CMG.AbstractID = dbo.AB_Abstract.AbstractID
	WHERE (dbo.AB_CMG.CMG_Year = @CMGYear) AND (dbo.AB_Abstract.AgeCode = 3) AND (dbo.AB_Abstract.AgeNumber BETWEEN 0 AND 17) AND 
	(dbo.AB_CMG.OccurrenceNumber = 1) OR
	(dbo.AB_CMG.CMG_Year = @CMGYear) AND (dbo.AB_Abstract.AgeCode <> 3) AND (dbo.AB_CMG.OccurrenceNumber = 1)
	group by cmg, complexity
	
	--The other 3 Hosp fields still need logic that I don't have
	Update CMG_CustomELOS set HospELOS= TElos from #TELOSCalc
	where cecmg = tcmg and ceplx = tplx and ceagelevel = tagecode and CEYear = @CMGYear

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- This is called by CCRS to default Qtr & Full Assessments based on the last Qtr or Full Assessment
CREATE   PROCEDURE [P_FetchAssessDefaults]
	@LinkID AS INT
AS 
	DECLARE @AbstractID AS INT

	SELECT TOP 1 @AbstractID = AbstractID FROM CRS_Demographic WHERE LinkID = @LinkID AND (AA8 = 14502 OR AA8 = 14503 OR AA8 = 14504 OR AA8 = 14505 OR AA8 = 14506 OR AA8 = 14511)  ORDER BY A3 DESC

	SELECT * FROM CRS_Demographic WHERE AbstractID = @AbstractID
	SELECT * FROM CRS_AssessFull1 WHERE AbstractID = @AbstractID
	SELECT * FROM CRS_AssessFull2 WHERE AbstractID = @AbstractID
	SELECT * FROM CRS_AssessShare1 WHERE AbstractID = @AbstractID
	SELECT * FROM CRS_AssessShare2 WHERE AbstractID = @AbstractID
	SELECT * FROM CRS_AssessShare3 WHERE AbstractID = @AbstractID
	SELECT * FROM CRS_AssessShare4 WHERE AbstractID = @AbstractID
	SELECT * FROM CRS_AssessShare5 WHERE AbstractID = @AbstractID
	SELECT * FROM CRS_Diagnosis WHERE AbstractID = @AbstractID
	SELECT * FROM CRS_Medication WHERE AbstractID = @AbstractID
--	SELECT * FROM CRS_Signature WHERE AbstractID = @AbstractID



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This returns the CareType (system code) for a given Inst Number (system code)
CREATE   PROCEDURE [P_FetchCareTypeByInstNo]
	@Institution as INT
AS 

	SELECT AssociationID FROM H_InstitutionProfile WHERE Code = @Institution




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- This is called by CCRS to default Assessment
CREATE    PROCEDURE [P_FetchCCRSDefaults]
	@AbstractID AS INT
AS 

--EN-00439: Added "Responsiblity for Payment" Fields
select 
	d.AbstractID, 
	AdmitDate AS [VisitDate], 
	AA1, 
	ChartNumber, 
	InstitutionNumber, 
	SiteNumber, 
	CoderNumber, 
	RegisterNumber, 
	MaidenName, 
	LastName, 
	MiddleName, 
	FirstName, 
	HealthCareNumber, 
	HCNVersion, 
	HCNProvince, 
	Gender, 
	BirthDate, 
	BirthDateEstimated, 
	MaritalStatus, 
	Secret,
	A7a,
	A7b,
	A7c,
	A7d,
	A7e,
	A7f,
	A7g,
	A7h,
	A7i,
	A7j,
	A7k,
	AA4a,
	AA4b,
	AA4c,
	AB4, --PR - 05841
    ResidenceCode,  --2.x-1569
	UniversalEpisodeIdentifier	--2.x-1355
from CRS_Demographic d
left outer join CRS_AssessFull1 f on d.AbstractID = f.AbstractID 
left join CRS_Admission a on d.AbstractID = a.AbstractID 
where d.AbstractID = @AbstractID

union 

--PR-02836: Changed Marital Status for Re-Entry
select 
	d.AbstractID, 
	AdmitDate AS [VisitDate], --AB1b
	AA1, ChartNumber, 
	InstitutionNumber, 
	SiteNumber, 
	CoderNumber, 
	RegisterNumber, 
	MaidenName, 
	LastName, 
	MiddleName, 
	FirstName, 
	HealthCareNumber, 
	HCNVersion, 
	HCNProvince, 
	Gender, 
	BirthDate, 
	BirthDateEstimated, 
	(select MaritalStatus from CRS_Demographic where AbstractID =  @AbstractID) as MaritalStatus, 
	Secret,
	A7a,
	A7b,
	A7c,
	A7d,
	A7e,
	A7f,
	A7g,
	A7h,
	A7i,
	A7j,
	A7k,
	AA4a,
	AA4b,
	AA4c,
	AB4,
    ResidenceCode,  --2.x-1569
	UniversalEpisodeIdentifier	--2.x-1355
from CRS_Demographic d
left outer join CRS_AssessFull1 f on d.AbstractID = f.AbstractID 
left join CRS_Admission a on d.AbstractID = a.AbstractID 
where LinkID = @AbstractID and AA8 = 14510 

order by [VisitDate] desc

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_FetchCharLockInformation](
    @ChartNumber varchar(100), @HospitalID int, 
    @PatientID  int = 0
)
AS 
    declare @lock int
    if @PatientID > 0
        set @lock = (select count(*)
            from cm_cpi cm
                inner join CM_CPI_ChartLocked l on cm.chartNumber = l.ChartNumber and cm.PatientID = l.PatientID
            where cm.ChartNumber = @ChartNumber 
                AND cm.PatientID = @PatientID)
    else
        set @lock = (select count(*)
            from cm_cpi cm
                inner join CM_CPI_ChartLocked l on cm.chartNumber = l.ChartNumber and cm.PatientID = l.PatientID
            where cm.ChartNumber = @ChartNumber 
                AND (ISNULL(cm.HospitalID, 0) = 0 OR @HospitalID = case @HospitalID when 0 then 0 else ISNULL(cm.HospitalID, 0) end)
                    )

    return( isnull(@lock, 0) 	)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE     procedure [P_FetchChartFamily]
	@PatientID	     [int] 
as

set nocount on

declare @selected int
set @selected = @PatientID

declare @searchid int
set @searchid = @selected


declare @results table 
(	
	orderby int identity(1,1), 
	patientid int, 
	childid int, 
	chartC varchar(10),
	link varchar(100),
	relation int -- 1: Selected -- 2: Ancestor -- 3: Descendants
)
--TVail - I changed the routine to only access CM_CPI once to get all the data and then
--access the temp table after that. It improves efficiency by about 23 times.
select distinct Chartnumber, patientid, masterchart into #Temp from CM_CPI where patientid = @PatientID
or masterchart = @PatientID 
insert  into #Temp
select Chartnumber, patientid, masterchart from CM_CPI where patientid in (select masterchart from #Temp)

select distinct * into #TempCPI from #Temp
--PR-00838 - If the selected Chart is the top most AND there is a child, then this will allow it to fill
if exists (select * from #TempCPI where PatientID = @searchid and isnull(MasterChart, 0) = 0)
and exists (select * from #TempCPI where isnull(MasterChart, 0) = @searchid ) begin
	insert @results ( patientid, childid, chartC, relation ) select 0, @searchid, (select ChartNumber from #TempCPI where PatientID = @searchid), 2  	
end

--1: Get the top most ancestor
while exists (select * from #TempCPI where PatientID = @searchid and isnull(MasterChart, 0) > 0) begin
	select @searchid = isnull(MasterChart, 0) from #TempCPI where PatientID = @searchid
end
--PR-00838 - Don't do this if the retrieved record is the same as the selected there isn't a child (first part handles that).
if @PatientID <> @searchid
	insert @results ( patientid, childid, chartC, relation ) select 0, @searchid, (select ChartNumber from #TempCPI where PatientID = @searchid), 2  
print @PatientID
print @searchid
--2: Find the other links and add them
while exists (
    select * 
    from #TempCPI search
    where exists (
        select * from @results children 
        where childid = search.MasterChart 
        and not exists (
            select * from @results where patientid = children.childid))
) begin
    insert @results ( patientid, childid, chartC, link )
    select 
	MasterChart, 
	PatientID,
	ChartNumber,
    0
	--(select IsNull(CIHIValue, '') + ' - ' + IsNull(UserDescription, '') from LU_ChartLinkType where code = LinkType) as [LinkType]
    from CM_CPI search
    where exists (
        select * from @results children 
        where childid = search.MasterChart 
        and not exists (
            select * from @results where patientid = children.childid))
end

--3: identify the relationships to the selected patient
    update @results 
    set relation = 1 
    where childid = @selected

    update @results 
    set relation = 2
    where orderby < (
        select orderby 
        from @results 
        where childid = @selected)
    and orderby <> 1
   
    update @results 
    set relation = 3
    where orderby > (
        select orderby
        from @results 
        where childid = @selected)
    


--4: Final selection
select 	patientid, childid, chartC, link, relation, orderby
from @results 
order by orderby

set nocount off

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is called by Chart Change/Merge form to return the Abstracts that have been submited.
CREATE PROCEDURE [P_FetchChartSubmitAbstracts]
	@ChartNumber [varchar](50),
	@HospID	     [int] = 0,
	@RecordCount int output
AS 

--*** NOTE ***
-- If this changes update cDataAccess.FetchChartSubmitAbstracts_Relocate
-- PR - 04020 to support Rehab, CCRS and OMHRS

select AbstractID, 
	ICDType,
	(select DisplayCode from LU_CareType where Code = CareType) as [Care],
	(select DisplayCode from H_InstitutionProfile where Code = InstitutionNumber) as [Inst],		
	EncounterNumber as [Encounter #], 
    	right('000' + isnull(cast(EncounterSequence as varchar(3)), 0), 3) as [Encounter Seq.], 
	convert (varchar(10), AdmitDate, 111) as [Admit Date], 
	convert (varchar(10), DischargeDate, 111) as [Discharge Date],
	convert (varchar(10), CIHIDateSent, 111) as [Sent Date],
    BatchYear as [Batch Year],
    (select DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [Batch Period]
from dbo.AB_Abstract 
where ChartNumber = @ChartNumber 
	and (IsSubmited = 1 or (caretype = 5 and IsSubmitLevel1 = 1 and IsSubmited = 2)) --PR - 07375 add level 1 submission
	and IsDeleted = 2 
	and ICDType = 'T'
	and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
-- PR - 04020
union
select AbstractID, 
	'T' as ICDType,
	(select DisplayCode from LU_CareType where Code = 3) as [Care],
	(select DisplayCode from H_InstitutionProfile where Code = InstitutionNumber) as [Inst],		
	EncounterNumber as [Encounter #], 
    '' as [Encounter Seq.], 
	convert (varchar(10), AdmitDate, 111) as [Admit Date], 
	convert (varchar(10), DischargeDate, 111) as [Discharge Date],
	convert (varchar(10), CIHIDateSent, 111) as [Sent Date],
  	BatchYear as [Batch Year],
   	(select DisplayCode from LU_CodeFile where Code = BatchPeriod) as [Batch Period]
from dbo.RH_ClientInfo
where ChartNumber = @ChartNumber 
	and IsSubmited = 1  
	and IsDeleted = 2 
	and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
    and AbstractID = LinkID
union
select aa.AbstractID, 
	'T' as ICDType,
	(select DisplayCode from LU_CareType where Code = 7) as [Care],
	(select DisplayCode from H_InstitutionProfile where Code = InstitutionNumber) as [Inst],		
	AA3 as [Encounter #], 
    '' as [Encounter Seq.], 
	convert (varchar(10), AdmitDate, 111) as [Admit Date], 
	convert (varchar(10), s.X80, 111) as [Discharge Date],
	convert (varchar(10), CIHIDateSent, 111) as [Sent Date],
  	BatchYear as [Batch Year],
   	(select DisplayCode from LU_CodeFile where Code = BatchPeriod) as [Batch Period]
from dbo.OMHRS_SecAA aa
    inner join dbo.OMHRS_RecInfo r on aa.AbstractID = r.AbstractID
    left  join dbo.OMHRS_SecS s on aa.AbstractID = s.AbstractID
    left  join dbo.OMHRS_SecA a on aa.AbstractID = a.AbstractID
where ChartNumber = @ChartNumber 
	and IsSubmited = 1  
	and IsDeleted = 2 
	and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
    and aa.AbstractID = aa.LinkID
--union
--select AbstractID, 
--	'T' as ICDType,
--	(select DisplayCode from LU_CareType where Code = 4) as [Care],
--	(select DisplayCode from H_InstitutionProfile where Code = InstitutionNumber) as [Inst],		
--	EncounterNumber as [Encounter #], 
--    '' as [Encounter Seq.], 
--	convert (varchar(10), AdmitDate, 111) as [Admit Date], 
--	convert (varchar(10), DischargeDate, 111) as [Discharge Date],
--	convert (varchar(10), CIHIDateSent, 111) as [Sent Date],
--  	BatchYear,
--   	(select DisplayCode from LU_BatchPeriod where Code = BatchPeriod) as [Batch Period]
--from dbo.CRS_Demographic
--where ChartNumber = @ChartNumber 
--	and IsSubmited = 1  
--	and IsDeleted = 2 
--	and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
--    and AbstractID = LinkID
--union
--select cc.AbstractID, 
--	'T' as ICDType,
--	(select DisplayCode from LU_CareType where Code = 8) as [Care],
--	(select DisplayCode from H_InstitutionProfile where Code = InstitutionNumber) as [Inst],		
--	'' as [Encounter #], 
--    '' as [Encounter Seq.], 
--	convert (varchar(10), RegisterDate, 111) as [Admit Date], 
--	convert (varchar(10), DischargeDate, 111) as [Discharge Date],
--	convert (varchar(10), CCRegFileDate, 111) as [Sent Date],
--  	null as [Batch Year],
--   	'' as [Batch Period]
--from dbo.CC_Demographic cc
--    inner join dbo.CC_RecordInfo i on cc.AbstractID = i.AbstractID
--    left join dbo.CC_DiseaseRegister r on cc.abstractid = r.abstractid
--    left join dbo.CC_DischargeInfo d on cc.AbstractID = d.AbstractID
--where ChartNumber = @ChartNumber 
--	and IsSubmited = 1  
--	and IsDeleted = 2 
--	and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)

order by [Care], [Admit Date] desc

set @RecordCount = @@rowcount
-- select * from LU_CareType


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is called by the FillCtrlPropList Method of the ControlFileMain Control. It provides a sneak peak to the Ctrl Sub Details.
CREATE   PROCEDURE [P_FetchCtrlDetail]
	@AppID AS VARCHAR(50), 
	@UserID AS VARCHAR(50),
	@FKey AS VARCHAR(50)
AS 


	DECLARE @SQL as VarChar(2000)
	DECLARE @LookUpTable as VarChar(50)

	SELECT @LookUpTable = (SELECT (case when datatype = 60 then 'ICD_DiagFile10'
                                        when datatype = 61 then 'ICD_ProcFile10'
                                        else ISNULL(LookUpTable, '') 
                                   end) FROM U_UsersFields  
					WHERE AppID = @AppID AND FieldID = @FKey AND UserID = @UserID)

	IF @LookUpTable = 'LLU_ProviderServices'
		BEGIN
		SELECT @SQL = '
		SELECT CASE WHEN MandatoryStatus = 2 OR MandatoryStatus = 4 THEN 
			(SELECT DisplayCode FROM LU_MandStatusFirm WHERE Code = MandatoryStatus)
		ELSE
			(SELECT DisplayCode FROM LU_MandStatusFlex WHERE Code = MandatoryStatus)
		END AS [MandStat],
		U_UsersFields.Header_User AS [Header],
		(SELECT DisplayCode FROM LU_YesNoSystem WHERE Code = FieldEnabled) AS [FEnabled],
		(SELECT DisplayCode FROM LU_YesNoSystem WHERE Code = FieldVisible) AS [FVisible], 
		(SELECT DisplayCode FROM LU_ProviderService WHERE Code = 
			(SELECT DISTINCT Code FROM LLU_ProviderServices WHERE Code = DefaultValue)) AS [DefVal]
		FROM dbo.U_UsersFields 
		WHERE (U_UsersFields.FieldID = ' + @FKey + ') 
		AND (U_UsersFields.AppID = ' + @AppID + ') 
		AND (U_UsersFields.UserID = ' + @UserID + ')'
		EXECUTE(@SQL)		
		RETURN 0
		END
	
	ELSE IF @LookUpTable = 'LLU_ProviderSpecialty'
		BEGIN
		SELECT @SQL = '
		SELECT CASE WHEN MandatoryStatus = 2 OR MandatoryStatus = 4 THEN 
			(SELECT DisplayCode FROM LU_MandStatusFirm WHERE Code = MandatoryStatus)
		ELSE
			(SELECT DisplayCode FROM LU_MandStatusFlex WHERE Code = MandatoryStatus)
		END AS [MandStat],
		U_UsersFields.Header_User AS [Header],
		(SELECT DisplayCode FROM LU_YesNoSystem WHERE Code = FieldEnabled) AS [FEnabled],
		(SELECT DisplayCode FROM LU_YesNoSystem WHERE Code = FieldVisible) AS [FVisible], 
		(SELECT DisplayCode FROM LU_ProviderService WHERE Code = 
			(SELECT DISTINCT Code FROM LLU_ProviderSpecialty WHERE Code = DefaultValue)) AS [DefVal]
		FROM dbo.U_UsersFields 
		WHERE (U_UsersFields.FieldID = ' + @FKey + ') 
		AND (U_UsersFields.AppID = ' + @AppID + ') 
		AND (U_UsersFields.UserID = ' + @UserID + ')'
		EXECUTE(@SQL)		
		RETURN 0
		END

	ELSE IF @LookUpTable = 'LU_PostalCode'
		BEGIN
		SELECT @SQL = '
		SELECT CASE WHEN MandatoryStatus = 2 OR MandatoryStatus = 4 THEN 
			(SELECT DisplayCode FROM LU_MandStatusFirm WHERE Code = MandatoryStatus)
		ELSE
			(SELECT DisplayCode FROM LU_MandStatusFlex WHERE Code = MandatoryStatus)
		END AS [MandStat],
		U_UsersFields.Header_User AS [Header],
		(SELECT DisplayCode FROM LU_YesNoSystem WHERE Code = FieldEnabled) AS [FEnabled],
		(SELECT DisplayCode FROM LU_YesNoSystem WHERE Code = FieldVisible) AS [FVisible], 
		U_UsersFields.DefaultValue AS [DefVal]
		FROM dbo.U_UsersFields 
		WHERE (U_UsersFields.FieldID = ' + @FKey + ') 
		AND (U_UsersFields.AppID = ' + @AppID + ') 
		AND (U_UsersFields.UserID = ' + @UserID + ')'
		EXECUTE(@SQL)		
		RETURN 0
		END

	ELSE IF ISNUMERIC(@LookUpTable)  = 1
		BEGIN
		SELECT @SQL = '
		SELECT CASE WHEN MandatoryStatus = 2 OR MandatoryStatus = 4 THEN 
			(SELECT DisplayCode FROM LU_MandStatusFirm WHERE Code = MandatoryStatus)
		ELSE
			(SELECT DisplayCode FROM LU_MandStatusFlex WHERE Code = MandatoryStatus)
		END AS [MandStat],
		U_UsersFields.Header_User AS [Header],
		(SELECT DisplayCode FROM LU_YesNoSystem WHERE Code = FieldEnabled) AS [FEnabled],
		(SELECT DisplayCode FROM LU_YesNoSystem WHERE Code = FieldVisible) AS [FVisible], 
		(SELECT DisplayCode FROM LU_CodeFile WHERE LookUpID = ' + @LookUpTable + ' AND Code = DefaultValue) AS [DefVal]
		FROM dbo.U_UsersFields 
		WHERE (U_UsersFields.FieldID = ' + @FKey + ') 
		AND (U_UsersFields.AppID = ' + @AppID + ') 
		AND (U_UsersFields.UserID = ' + @UserID + ')'
		EXECUTE(@SQL)		
		RETURN 0
		END

	ELSE IF  @LookUpTable <> '' 
		BEGIN
		SELECT @SQL = '
		SELECT CASE WHEN MandatoryStatus = 2 OR MandatoryStatus = 4 THEN 
			(SELECT DisplayCode FROM LU_MandStatusFirm WHERE Code = MandatoryStatus)
		ELSE
			(SELECT DisplayCode FROM LU_MandStatusFlex WHERE Code = MandatoryStatus)
		END AS [MandStat],
		U_UsersFields.Header_User AS [Header],
		(SELECT DisplayCode FROM LU_YesNoSystem WHERE Code = FieldEnabled) AS [FEnabled],
		(SELECT DisplayCode FROM LU_YesNoSystem WHERE Code = FieldVisible) AS [FVisible], 
		(SELECT DisplayCode FROM ' + @LookUpTable + ' WHERE Code = DefaultValue) AS [DefVal]
		FROM dbo.U_UsersFields 
		WHERE (U_UsersFields.FieldID = ' + @FKey + ') 
		AND (U_UsersFields.AppID = ' + @AppID + ') 
		AND (U_UsersFields.UserID = ' + @UserID + ')'
		EXECUTE(@SQL)		
		RETURN 0
		END

	ELSE
		BEGIN
		SELECT @SQL = '
		SELECT CASE WHEN MandatoryStatus = 2 OR MandatoryStatus = 4 THEN 
			(SELECT DisplayCode FROM LU_MandStatusFirm WHERE Code = MandatoryStatus)
		ELSE
			(SELECT DisplayCode FROM LU_MandStatusFlex WHERE Code = MandatoryStatus)
		END AS [MandStat],
		U_UsersFields.Header_User AS [Header],
		(SELECT DisplayCode FROM LU_YesNoSystem WHERE Code = FieldEnabled) AS [FEnabled],
		(SELECT DisplayCode FROM LU_YesNoSystem WHERE Code = FieldVisible) AS [FVisible], 
		U_UsersFields.DefaultValue AS [DefVal]
		FROM dbo.U_UsersFields 
		WHERE (U_UsersFields.FieldID = ' + @FKey + ') 
		AND (U_UsersFields.AppID = ' + @AppID + ') 
		AND (U_UsersFields.UserID = ' + @UserID + ')'
		EXECUTE(@SQL)
		RETURN 0
		END
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- This is called by Provider Number to return the Provider Billing Specialty
CREATE   PROCEDURE [P_FetchDefaultProvBillSpec]
	@ProviderNumber 	[int]
AS 
	DECLARE @I AS INT
	SELECT @I = ProvdrBillSpecialty FROM LU_Provider WHERE Code = @ProviderNumber

	RETURN @I



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is called by Provider Number to return the Default MIS Code
CREATE   PROCEDURE [P_FetchDefaultProvMIS]
	@ProviderNumber 	[int],
	@SearchDate datetime,
	@ProvdrMISCode  int output
AS 
    --PR - 05954 add searchdate to remove invalid miscode
	set @ProvdrMISCode = (SELECT top 1 ProvdrMISCode FROM LU_Provider WHERE Code = @ProviderNumber)

    if @ProvdrMISCode is null set @ProvdrMISCode = 0
    if @ProvdrMISCode > 0 
    begin
        if not exists (select * from LU_MISCode where code = @ProvdrMISCode and @SearchDate between validfrom and validto)
            set @ProvdrMISCode = 0
    end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- This is called by Provider Number to return the Default Provider Service
CREATE   PROCEDURE [P_FetchDefaultProvServ]
	@ProviderNumber 	[int],
	@UseDate 		[datetime]
AS 
declare @Types int
set @Types = (select count(*) from LLU_ProviderServices 
	where AssociationID = @ProviderNumber
	--and Type = 1 --PR-04071
	and (([ValidFrom] <=  @UseDate) and (@UseDate <= [ValidTo]))
	and isnull(AssociationID, 0) <> 0
	and Code in (select Code from LU_ProviderService where (([ValidFrom] <=  @UseDate) and (@UseDate <= [ValidTo])))
	)

	select Code
	from LLU_ProviderServices 
	where AssociationID = @ProviderNumber
	--and Type = 1 --PR-04071
	and (([ValidFrom] <=  @UseDate) and (@UseDate <= [ValidTo]))
	and ([Type] > 0 or @Types = 1) --PR - 05632
	and isnull(AssociationID, 0) <> 0
	--PR-04071
	and Code in (select Code from LU_ProviderService where (([ValidFrom] <=  @UseDate) and (@UseDate <= [ValidTo])))
	order by [Type]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- This is called by Provider Number to return the Default Provider Specialty
CREATE   PROCEDURE [P_FetchDefaultProvSpec]
	@ProviderNumber 	[int],
	@UseDate 		[datetime]
AS 
declare @Types int
set @Types = (select count(*) from LLU_ProviderSpecialty 
	where AssociationID = @ProviderNumber
	and (([ValidFrom] <=  @UseDate) and (@UseDate <= [ValidTo]))
	and isnull(AssociationID, 0) <> 0
	and Code in (select Code from LU_ProviderService where (([ValidFrom] <=  @UseDate) and (@UseDate <= [ValidTo])))
	)

	select Code
	from LLU_ProviderSpecialty
	where AssociationID = @ProviderNumber
	--and Type = 1 --PR-04071
	and (([ValidFrom] <=  @UseDate) and (@UseDate <= [ValidTo]))
  	and isnull(AssociationID, 0) <> 0
	and ([Type] > 0 or @Types = 1) --PR - 05632
	--PR-04071
	and Code in (select Code from LU_ProviderSpecialty where (([ValidFrom] <=  @UseDate) and (@UseDate <= [ValidTo])))
	order by [Type]
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [P_FetchDefaultResidenceCode]
	@SearchString as VarChar(50),
	@UseDate as VarChar(10)
AS 

print ''

--PR-01258
if len(@SearchString) = 2 
	select top 1 LinkCode 
	from LU_PostalCode 
	where ([ValidFrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
	and CIHIValue = @SearchString
	and LinkCode is not null 
	order by len(CIHIValue) desc
else
	select top 1 LinkCode 
	from LU_PostalCode 
	where ([ValidFrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
	and CIHIValue in ( 
			    left( @SearchString, 6 ), left( @SearchString, 5 ), 
			    left( @SearchString, 4 ), left( @SearchString, 3 ), 
			    left( @SearchString, 2 ), left( @SearchString, 1 )
			 )
	and LinkCode is not null 
	order by len(CIHIValue) desc


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



-- This is called by Deficiency Letters to load the ones that are past a user specified level
CREATE  PROCEDURE [P_FetchDeficiencyHeaderByProviders]
	@SearchString varchar(8000) = null,
    @HospitalID   int = 0
AS 
set nocount on
	DECLARE @Sql varchar(8000)
    Declare @Doctor varchar(100)
--    declare @HospitalCount int

    declare @i int, @j int
    declare @Provider table (
            Provider  int)

    set @sql = @SearchString

    if @sql is null set @sql = ''
    while(len(@sql) > 0)
    begin
        set @j = charindex(',', @Sql)            
        if @j > 0
        begin 
            set @Doctor = left(@Sql, @j - 1)
            set @sql = right(@Sql, len(@sql) - @j)
        end
        else
        begin
            set @Doctor = @sql
            set @sql = ''
        end
        insert @Provider values(@Doctor)
    end
    --EN-00183
    --Email by Beth. Beth think we should keep exists client no change. 
    --set @HospitalCount = isnull((select count(*) from H_HospitalProfile), 1)
--     if @HospitalCount > 1
--         select Distinct
--             DefeciencyID
--         from @Provider D 
--             inner join Def_SlipMain on D.Provider = Def_SlipMain.DefDrNumber
--     		inner JOIN DefLU_ChartStatus S ON Def_SlipMain.DefMainStatus = S.Code
--     --        inner join CM_CPI on CM_CPI.PatientID = Def_SlipMain.DefPatientID
--             left  join CM_CPI_Volume V on Def_SlipMain.DefVolumeID = V.VolumeID
--             left  join LoanLU_Location Loc on V.CLCurrentLocation = Loc.Code
--             left  join LU_YesNoSystem YN on Loc.InHospital = YN.Code
--         where S.DisplayCode in ('0', 'A', '1', '2', '3', '4', '5') 
--                 and Def_SlipMain.DefDays > 0 
--                 and (YN.CIHIValue = '1' or isnull(Loc.Code, 0) = 0)
--                 and (isnull(@HospitalID, 0) = 0 or (case when isnull(Def_SlipMain.HospitalID, 0) = 0 then @HospitalID else Def_SlipMain.HospitalID end) = @HospitalID) 
--     	--ORDER BY DefeciencyID
--     else 
        select Distinct DefeciencyID
        from @Provider D 
            inner join Def_SlipMain on D.Provider = Def_SlipMain.DefDrNumber
    		inner JOIN DefLU_ChartStatus S ON Def_SlipMain.DefMainStatus = S.Code
    --        inner join CM_CPI on CM_CPI.PatientID = Def_SlipMain.DefPatientID
            left  join CM_CPI_Volume V on Def_SlipMain.DefVolumeID = V.VolumeID
            left  join LoanLU_Location Loc on V.CLCurrentLocation = Loc.Code
            left  join LU_YesNoSystem YN on Loc.InHospital = YN.Code
        where S.DisplayCode in ('0', 'A', '1', '2', '3', '4', '5') 
                and Def_SlipMain.DefDays > 0 
                and (YN.CIHIValue = '1' or isnull(Loc.Code, 0) = 0)
                and (isnull(@HospitalID, 0) = 0 or (case when isnull(Def_SlipMain.HospitalID, 0) = 0 then @HospitalID else Def_SlipMain.HospitalID end) = @HospitalID) 
    	--ORDER BY DefeciencyID

    set nocount off





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


-- This is called by Deficiency Letters to load the ones that are past a user specified level
CREATE PROCEDURE [P_FetchDeficiencyLetters]
	@Level 	[varchar](10),
	@HospID [int] = 0
AS 
	
	DECLARE @Days AS int
	DECLARE @Status AS int
	Declare @VID as int
	Declare @VType as int
	Declare @VIDTemp as int
set nocount on
	SELECT @Days = ISNULL(NumberDays, 0), @Status = Code FROM DefLU_ChartStatus WHERE DisplayCode = @Level
	if @Status = 2
	Begin
		SELECT 
            Def_SlipMain.DefID, 
            Def_SlipMain.DefeciencyID, 
			(SELECT ChartNumber FROM CM_CPI WHERE PatientID = DefPatientID) AS [Chart],
			LU_Provider.Code AS [ProvID],
			LU_Provider.DisplayCode AS [Provider],
			LU_Provider.UserDescription AS [ProviderName], defvolumeid into #DefLetters
		FROM Def_SlipMain 
		LEFT OUTER JOIN LU_Provider ON Def_SlipMain.DefDrNumber = LU_Provider.Code
		WHERE (DefDays >= @Days AND DefMainStatus = 7) 
		AND (ISNULL(LU_Provider.ProvdrMaxLetter, 0) <= @Level)
		AND (ISNULL(LU_Provider.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(LU_Provider.HospitalID, 0) end)
		ORDER BY DefeciencyID
		Set @VIDTemp = 0
		
		declare  cur_Btables cursor for
		SELECT Volumeid, ActivityType FROM CL_Activity WHERE volumeid in (SELECT VolumeID FROM dbo.CM_CPI_Volume WHERE (PermLocation <> CLCurrentLocation) and isnull(CLCurrentLocation, '') <> '' and 
		volumeid in (select defvolumeid from #DefLetters))
		order by volumeid, activitydateout Desc
		Open cur_Btables
		fetch next from cur_Btables
		into @VID, @VType
		while @@fetch_status = 0
		begin
			If @VIDTemp <> @VID and @VType = 1
				Delete #DefLetters where defvolumeid = @VID
			set @VIDTemp = @VID
			fetch next from cur_Btables 
			into @VID, @VType
		end
		Close cur_Btables
		Deallocate cur_Btables
	End
	else
	Begin
		SELECT 
            Def_SlipMain.DefID, 
            Def_SlipMain.DefeciencyID, 
			(SELECT ChartNumber FROM CM_CPI WHERE PatientID = DefPatientID) AS [Chart],
			LU_Provider.Code AS [ProvID],
			LU_Provider.DisplayCode AS [Provider],
			LU_Provider.UserDescription AS [ProviderName], defvolumeid into #DefLetters2
		FROM Def_SlipMain 
		LEFT OUTER JOIN LU_Provider ON Def_SlipMain.DefDrNumber = LU_Provider.Code
		WHERE (DefDays >= @Days AND DefMainStatus = @Status - 1) 
		AND (ISNULL(LU_Provider.ProvdrMaxLetter, 0) <= @Level)
		ORDER BY DefeciencyID
		Delete #DefLetters2 where provid in (select ProviderID FROM LLU_Provider_Vacation 
		Where ProviderID in (select provid from #DefLetters2) and DateFrom < getdate() and DateTo > getdate())
		
		Set @VIDTemp = 0
		
		declare  cur_Btables cursor for
		SELECT Volumeid, ActivityType FROM CL_Activity WHERE volumeid in (SELECT VolumeID FROM dbo.CM_CPI_Volume WHERE (PermLocation <> CLCurrentLocation) and isnull(CLCurrentLocation, '') <> '' and 
		volumeid in (select defvolumeid from #DefLetters2))
		order by volumeid, activitydateout desc
		Open cur_Btables
		fetch next from cur_Btables
		into @VID, @VType
		while @@fetch_status = 0
		begin
			If @VIDTemp <> @VID and @VType = 1
				Delete #DefLetters2 where defvolumeid = @VID
			set @VIDTemp = @VID
			fetch next from cur_Btables 
			into @VID, @VType
		end
		Close cur_Btables
		Deallocate cur_Btables
	End

set nocount off

	if @Status = 2
		Select DefID, DefeciencyID, Chart, ProvID, Provider, ProviderName From #DefLetters
	else
		Select DefID, DefeciencyID, Chart, ProvID, Provider, ProviderName From #DefLetters2








GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- This is called by Deficiency Letters to load the ones that are past a user specified level
CREATE PROCEDURE [P_FetchDeficiencyLettersByProvider]
	@Level 	[varchar](10) = 0,
	@HospID [int] = 0
AS 

-- declare 	@HospID [int]
-- set @HospID = 0
	
	DECLARE @Day1 int, @Day2 int, @Day3 int, @Day4 int, @Day5 int
	DECLARE @Status1 int, @Status2 int, @Status3 int, @Status4 int, @Status5 int
    declare @UseDate as datetime
    set @usedate = cast(convert(varchar(20), getdate(), 111) as datetime)
set nocount on
-- 	SELECT @Day1 = ISNULL(NumberDays, 0), @Status1 = Code FROM DefLU_ChartStatus WHERE DisplayCode = '1'
-- 	SELECT @Day2 = ISNULL(NumberDays, 0), @Status2 = Code FROM DefLU_ChartStatus WHERE DisplayCode = '2'
-- 	SELECT @Day3 = ISNULL(NumberDays, 0), @Status3 = Code FROM DefLU_ChartStatus WHERE DisplayCode = '3'
-- 	SELECT @Day4 = ISNULL(NumberDays, 0), @Status4 = Code FROM DefLU_ChartStatus WHERE DisplayCode = '4'
-- 	SELECT @Day5 = ISNULL(NumberDays, 0), @Status5 = Code FROM DefLU_ChartStatus WHERE DisplayCode = '5'
--     if @Day1 = 0 
--     begin
--         set @Day2 = 0
--         set @Day3 = 0
--         set @Day4 = 0
--         set @Day5 = 0
--     end
--     else if @Day2 = 0 or @Day2 <= @Day1
--     begin
--         set @Day2 = 0
--         set @Day3 = 0
--         set @Day4 = 0
--         set @Day5 = 0
--     end
--     else if @Day3 = 0 or @Day3 <= @Day2
--     begin
--         set @Day3 = 0
--         set @Day4 = 0
--         set @Day5 = 0
--     end
--     else if @Day4 = 0 or @Day4 <= @Day3
--     begin
--         set @Day4 = 0
--         set @Day5 = 0
--     end
--     else if @Day5 = 0 or @Day5 <= @Day4
--         set @Day5 = 0 
-- 
--    --PR - 02245
--     select distinct DefID into #DefDetail
--     from dbo.Def_Activity a
--         inner join dbo.DefLU_DeficiencyCode d on a.DefCode = d.code
--         inner join LU_YesNoSystem YN on d.DefCountDays = YN.Code
--     where YN.CIHIValue = '1' and DefStatus = 7
-- 
--     CREATE  INDEX [IX_DefDetail_DefID] ON #DefDetail(DefID) 

    ----PR - 01841 eliminate deficiency hospital 
    select ProvID, Provider, ProviderName, ProviderLanguage, 
        ProviderMaxLetter, ProviderCurrentLevel, 
        sum(Level0) as Level0,
        sum(Level1) as Level1, 
        sum(Level2) as Level2, 
        sum(Level3) as Level3, 
        sum(Level4) as Level4, 
        sum(Level5) as Level5 
    from 
    ( 
    select distinct ProvID, Provider, ProviderName, ProviderLanguage, 
        ProviderMaxLetter, ProviderCurrentLevel, 
        Level0, Level1, Level2, Level3, Level4, Level5, isnull(D.HospitalID, 0) as HospitalID
    from       
    (select 
		LU_Provider.Code AS [ProvID],
		LU_Provider.DisplayCode AS [Provider],
		LU_Provider.UserDescription AS [ProviderName], 
        isnull(Lang.DisplayCode, 'E') as ProviderLanguage,
        isnull(DefLU_LetterLevel.DisplayCode, '5') as ProviderMaxLetter,
        (case when (case when Level5 > 0 then 5 
                         when Level4 > 0 then 4
                         when Level3 > 0 then 3
                         when Level2 > 0 then 2
                         when Level1 > 0 then 1
                         else 0 end) > isnull(DefLU_LetterLevel.Code, 5)
              then (case when isnull(DefLU_LetterLevel.Code, 5) > isnull(ProvdrCurLetter, 0)
                         then isnull(ProvdrCurLetter, 0) + 1
                         else isnull(DefLU_LetterLevel.Code, 5) end)
              when (case when Level5 > 0 then 5 
                         when Level4 > 0 then 4
                         when Level3 > 0 then 3
                         when Level2 > 0 then 2
                         when Level1 > 0 then 1
                         else 0 end) > isnull(ProvdrCurLetter, 0)
              then (case when isnull(DefLU_LetterLevel.Code, 5) > isnull(ProvdrCurLetter, 0)
                         then isnull(ProvdrCurLetter, 0) + 1
                         else isnull(DefLU_LetterLevel.Code, 5) end)
              else (case when Level5 > 0 then 5 
                         when Level4 > 0 then 4
                         when Level3 > 0 then 3
                         when Level2 > 0 then 2
                         when Level1 > 0 then 1
                         else 0 end)
              end) as ProviderCurrentLevel,
        Level0, 
        Level1, Level2, Level3, Level4, 
--         Level1 - Level2 as Level1,
--         Level2 - Level3 as Level2,
--         Level3 - Level4 as Level3,
--         Level4 - Level5 as Level4,
        Level5,
        L.HospitalID, 
        LU_Provider.MinDeficiency
    from LU_Provider
        left join LLU_Provider_Language Lang on LU_Provider.ProvDrLanguage = Lang.Code
        left join DefLU_LetterLevel on LU_Provider.ProvdrMaxLetter = DefLU_LetterLevel.Code
        inner join 
	    (SELECT M.DefDrNumber, M.HospitalID,  
--             sum((case when z.DefID is null or DefDays < @Day1 then 1 else 0 end)) as Level0,
--             sum((case when z.DefID is not null and @Day1 > 0 and DefDays >= @Day1 then 1 else 0 end)) as Level1,
--             sum((case when z.DefID is not null and @Day2 > 0 and DefDays >= @Day2 then 1 else 0 end)) as Level2,
--             sum((case when z.DefID is not null and @Day3 > 0 and DefDays >= @Day3 then 1 else 0 end)) as Level3,
--             sum((case when z.DefID is not null and @Day4 > 0 and DefDays >= @Day4 then 1 else 0 end)) as Level4,
--             sum((case when z.DefID is not null and @Day5 > 0 and DefDays >= @Day5 then 1 else 0 end)) as Level5
            sum((case when S.DisplayCode in ('0', 'A', 'N', 'X') then 1 else 0 end)) as Level0,
            sum((case when S.DisplayCode = '1' then 1 else 0 end)) as Level1,
            sum((case when S.DisplayCode = '2' then 1 else 0 end)) as Level2,
            sum((case when S.DisplayCode = '3' then 1 else 0 end)) as Level3,
            sum((case when S.DisplayCode = '4' then 1 else 0 end)) as Level4,
            sum((case when S.DisplayCode = '5' then 1 else 0 end)) as Level5
 	     FROM Def_SlipMain M 
		     inner JOIN DefLU_ChartStatus S ON M.DefMainStatus = S.Code
             --PR - 02245
             --left join #DefDetail z on M.DefID = z.DefID
             left  join CM_CPI_Volume V on M.DefVolumeID = V.VolumeID
             left  join LoanLU_Location Loc on V.CLCurrentLocation = Loc.Code
             left  join LU_YesNoSystem YN on Loc.InHospital = YN.Code
         where S.DisplayCode in ('0', 'A', '1', '2', '3', '4', '5') 
            --PR - 02245 and DefDays > 0 --and M.HospitalID = @HospID 
            and (YN.CIHIValue = '1' or isnull(Loc.Code, 0) = 0)
         group by M.DefDrNumber, M.HospitalID 
    ) L on LU_Provider.Code = L.DefDrNumber
	WHERE L.DefDrNumber not in (select ProviderID from LLU_Provider_Suspention where @usedate between DateFrom and DateTo)
--EN-00183
--      and L.DefDrNumber not in (select ProviderID from LLU_Provider_Vacation where @usedate between DateFrom and DateTo)
      and L.DefDrNumber not in (select ProviderID from LLU_Provider_UnAvailable where @usedate between DateFrom and DateTo)
      --and isnull(DefLU_LetterLevel.DisplayCode, '0') <> '0'
      and (ISNULL(L.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(L.HospitalID, 0) end)  

      and (isnull(@Level, 0) = 0 or (Level0 + Level1 + Level2 + Level3 + Level4 + Level5) >= isnull(LU_Provider.MinDeficiency, 1))
      and (Level1 + Level2 + Level3 + Level4 + Level5) > 0
    ) D inner join H_HospitalProfile H on H.code = (case when isnull(D.HospitalID, 0) = 0 then (case when @HospID = 0 then H.Code else @HospID end) else D.HospitalID end)
    where ProviderCurrentLevel > 0
        and (isnull(@Level, 0) = 0 or ProviderCurrentLevel = @Level)
        and @HospID = (case @HospID when 0 then 0 else (case when ISNULL(D.HospitalID, 0) = 0 then @HospID else D.HospitalID end) end)  
--Disabled by 2005/03/03 Project meeting        and (isnull(@Level, 0) = 0 or (Level1 + Level2 + Level3 + Level4 + Level5) >= isnull(D.MinDeficiency, isnull(H.MinDeficiency, 1)))
        and ((Level0 + Level1 + Level2 + Level3 + Level4 + Level5) >= 
        (case when isnull(D.MinDeficiency, 0) = 0 
              then isnull(H.MinDeficiency, 1)
              else D.MinDeficiency end) )
    ) S
    group by ProvID, Provider, ProviderName, ProviderLanguage, ProviderMaxLetter, ProviderCurrentLevel

	ORDER BY ProviderCurrentLevel, Provider
---






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


-- This is called by Deficiency Letters to load the ones that are past a user specified level
CREATE PROCEDURE [P_FetchDeficiencyLettersForReport]
	@SearchString varchar(8000) = null,
    @HospitalID   int = 0
AS 
set nocount on
	DECLARE @Sql varchar(8000)
    Declare @Doctor varchar(100)
    declare @i int, @j int
    declare @Provider table (
            Provider  int,
            [Level]     int)
    set @i = 1
    while(@i <= 5)
    begin
        if @i < 5 
        begin
            set @j = charindex(';', @SearchString)
            if @j = 1 set @sql = ''
            else set @sql = left(@SearchString, @j - 1)

            set @SearchString = right(@SearchString, len(@SearchString) - @j)
        end
        else
        begin
            set @sql = @SearchString
            set @SearchString = ''
        end
        if @sql is null set @sql = ''
        while(len(@sql) > 0)
        begin
            set @j = charindex(',', @Sql)            
            if @j > 0
            begin 
                set @Doctor = left(@Sql, @j - 1)
                set @sql = right(@Sql, len(@sql) - @j)
            end
            else
            begin
                set @Doctor = @sql
                set @sql = ''
            end
            insert @Provider values(@Doctor, @i)
        end
        set @i = @i + 1 
    end

    select Distinct
		LU_Provider.DisplayCode AS [Provider],
		LU_Provider.UserDescription AS [ProviderName], 
        isnull(Lang.DisplayCode, 'E') as ProviderLanguage,
        ProvdrTitle as ProviderTitle, 
        ProvdrCredentials as ProviderCredentials, 
        ProvdrAddress as ProviderAddress, 
        ProvdrCity as ProviderCity, 
        ProvdrProvince as ProviderProvince, 
        ProvdrPostal as ProviderPostalCode,
        ProvdrEMail as ProviderEMail,
        D.Level,
        Def_SlipMain.DefeciencyID as HeaderReferenceIDNumber, 
        DefOccurrence as DeficiencyOccurrence, 
        CM_CPI.ChartNumber, CM_CPI.LastName, CM_CPI.FirstName, CM_CPI.MiddleName, 
        DEF.DisplayCode as DeficiencyCode, DEF.UserDescription as DeficiencyCodeDesc,
        DEFT.DisplayCode as DeficiencyCodeType, DEFT.UserDescription as DeficiencyCodeTypeDesc,
        S.DisplayCode as DeficiencyMainStatus, S.UserDescription as DeficiencyMainStatusDesc,
        Def_Activity.JobNumber,
        C.DisplayCode as DeficiencyColor, C.UserDescription as DeficiencyColorDesc,
        Def_SlipMain.DefDays, 
        Def_Activity.DefNote,
        Def_SlipMain.DefStartDate
    from LU_Provider 
        inner join @Provider D on LU_Provider.Code = D.Provider
        inner join Def_SlipMain on LU_Provider.Code = Def_SlipMain.DefDrNumber
--EN-00183
--        left  join Def_Activity on Def_SlipMain.DefeciencyID = Def_Activity.HeaderDefID
        left  join Def_Activity on Def_SlipMain.DefID = Def_Activity.DefID
        inner join DefLU_DeficiencyCode DEF on Def_Activity.DefCode = DEF.Code
        left  join DefLU_DeficiencyType DEFT on Def_Activity.DefCodeType = DEFT.Code
		inner JOIN DefLU_ChartStatus S ON Def_SlipMain.DefMainStatus = S.Code
        inner join CM_CPI on CM_CPI.PatientID = Def_SlipMain.DefPatientID
        left  join LLU_Provider_Language Lang on LU_Provider.ProvDrLanguage = Lang.Code
        left  join CM_CPI_Volume V on Def_SlipMain.DefVolumeID = V.VolumeID
        left  join LoanLU_Location Loc on V.CLCurrentLocation = Loc.Code
        left  join LU_YesNoSystem YN on Loc.InHospital = YN.Code
        left  join DefLU_DocColourCode C on Def_SlipMain.DefColour = C.Code
        left  join DefLU_ChartStatus DS on Def_Activity.DefStatus = DS.Code
    where S.DisplayCode in ('0', 'A', '1', '2', '3', '4', '5') 
            and isnull(DS.Displaycode, '') not in ('C', 'X')
            and Def_SlipMain.DefDays > 0 
            and isnull(YN.CIHIValue, '1') = '1' 
            and (isnull(@HospitalID, 0) = 0 or Def_SlipMain.HospitalID = @HospitalID) 
	ORDER BY LU_Provider.DisplayCode, Def_SlipMain.DefDays 

    set nocount off







GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This is called by Deficiency Letters to load the different Levels
CREATE   PROCEDURE [P_FetchDeficiencyLevels]
AS 
	SELECT DefLU_LetterLevel.DisplayCode, DefLU_LetterLevel.UserDescription, ISNULL(DefLU_ChartStatus.NumberDays, 0)
	FROM DefLU_LetterLevel, DefLU_ChartStatus  
	WHERE DefLU_LetterLevel.DisplayCode =  DefLU_ChartStatus.DisplayCode
	ORDER BY DefLU_LetterLevel.DisplayCode




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE   PROCEDURE [P_FetchDeficiencyLinkCode]
	@DefCodeID [int]
AS 
	DECLARE @DefLinkID AS INTEGER

	SELECT @DefLinkID = LinkDefCode FROM DefLU_DeficiencyCode WHERE Code = @DefCodeID
	RETURN @DefLinkID





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This is called by Deficiency Provider Code to default the Status.
CREATE   PROCEDURE [P_FetchDeficiencyProvStatus]
	@ProviderID [int],
	@Status [varchar](10) output
AS 
	SELECT @Status = ProvdrState FROM LU_Provider WHERE Code = @ProviderID




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



-- This is called by Deficiency Letters to load the ones that are past a user specified level
CREATE  PROCEDURE [P_FetchDeficiencyRollback]
	@Level 	[int],
	@HospID [int] = 0
AS 
-- The system code for the levels here is one more than the value entered by the User. e.g. 0 value is sys code 1, 1 value is sys code 2
SELECT 
    Def_SlipMain.DefID, 
    Def_SlipMain.DefeciencyID, 
	(SELECT ChartNumber FROM CM_CPI WHERE PatientID = DefPatientID) AS [Chart],
	LU_Provider.Code AS [ProvID],
	LU_Provider.DisplayCode AS [Provider],
	LU_Provider.UserDescription AS [ProviderName] 
FROM Def_SlipMain 
LEFT OUTER JOIN LU_Provider ON Def_SlipMain.DefDrNumber = LU_Provider.Code
WHERE (ISNULL(DefMainStatus, 0) = @Level + 1) 
AND (ISNULL(LU_Provider.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(LU_Provider.HospitalID, 0) end)
ORDER BY DefeciencyID



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This is called by Deficiency Code to default the Type.
CREATE   PROCEDURE [P_FetchDeficiencyType]
	@DefCodeID [int]
AS 

	DECLARE @DefTypeID AS INTEGER

	SELECT @DefTypeID = AssociationID FROM DefLU_DeficiencyCode WHERE Code = @DefCodeID
	RETURN @DefTypeID




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE                  PROCEDURE [P_FetchEnCoderICD]
	@SearchType as VarChar(1),
	@ICDType as VarChar(1),
	@SearchString as VarChar(250) = '',
	@SearchCode as varchar(10) = '0',
	@Gender AS VarChar(1)='', 
	@UseDate as VarChar(10)='',
	@UseAge as VarChar(3) = '0',
	@OccNo as VarChar(3) = '0',
	@CareType as VarChar(1) = '0'
AS 

DECLARE @Return as VarChar(3)
Declare @SQL as nVarChar(4000)
Declare @SQL2 as nVarChar(4000)
Declare @SQL3 as nVarChar(4000)
Declare @MostR as VarChar(20)
Declare @ReturnCode as VarChar(6)

declare @GenderS as varchar(50) --PR-02786

if @Gender = '2' set @Gender = 'F'
if @Gender = '1' set @Gender = 'M'

set @GenderS = '(''A'', ''N'', ''G'')' --PR-02786
if @Gender = 'F' set @GenderS = '(''A'', ''F'', ''G'')' --PR-02786
if @Gender = 'M' set @GenderS = '(''A'', ''M'', ''N'')' --PR-02786

Set @SQL = 'SELECT @ReturnCode = [Code]  '

If @CareType = '5' and @ICDType = 'T'
	Set @MostR = '(''Y'', ''A'')'
Else
	Set @MostR = '(''Y'')'

If @SearchType = 'D'
	Set @SQL2 = 'FROM dbo.ICD_DiagFile'
Else
	Set @SQL2 = 'FROM dbo.ICD_ProcFile'

If @ICDType = '9'
Begin
	Set @SQL2 = @SQL2 + '9 '
	Set @SQL3 = ' Where (isnull(DiagnosisGender, '''') = '''' OR DiagnosisGender = ''' + @Gender + ''') And '
End
Else If @ICDType = 'C'
Begin
	Set @SQL2 = @SQL2 + '9cm '
	Set @SQL3 = ' Where (isnull(DiagnosisGender, '''') = '''' OR DiagnosisGender = ''' + @Gender + ''') And '
End
Else If @ICDType = 'T'
Begin
	Set @SQL2 = @SQL2 + '10 '
	--Set @SQL3 = ' Where (isnull(DiagnosisGender, '''') = ''A'' OR DiagnosisGender = ''' + @Gender + ''') And '
	set @SQL3 = ' where (isnull(DiagnosisGender, '''') in ' + @GenderS + ') and ' --PR-02786
End

if @OccNo = 1 and @SearchType = 'D'
	Set @SQL3 = @SQL3 + '(AgeLow <= ' + @UseAge + ') AND (' + @UseAge + ' <= AgeHigh) And (MRDxFlag in ' + @MostR + ') AND 
	([ValidFrom] <= ''' + @UseDate + ''') AND (''' + @UseDate + ''' <= [ValidTo]) AND ([CIHIValue] = ''' + @SearchString + ''') '
Else
	Set @SQL3 = @SQL3 + '(AgeLow <= ' + @UseAge + ') AND (' + @UseAge + ' <= AgeHigh) AND 
	([ValidFrom] <= ''' + @UseDate + ''') AND (''' + @UseDate + ''' <= [ValidTo]) AND ([CIHIValue] = ''' + @SearchString + ''') '

	Set @SQL = @SQL + @SQL2 + @SQL3
	exec sp_executesql @sql, N'@ReturnCode VarChar(6) output', @ReturnCode output
	set @ReturnCode = isnull(@ReturnCode, 0)
	RETURN @ReturnCode





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



create PROCEDURE [P_FetchFullVisit]
	@AppID as int,
	@RecordID as int,
	@PatientID as int output,
	@UniversalID as int output
AS 
	
	select @PatientID = PatientID, @UniversalID = UniversalID from AB_Main where AppID = @AppID and AbstractID = @RecordID



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This is called by the Session Object. To Load Hospital Info, there is only one record..
CREATE   PROCEDURE [P_FetchHospital]
	@Code as int = 0
AS	
	--2.x-0470
	if @Code = 0 select h.*, m.PrivacyMessage from H_HospitalProfile h left join H_HospitalProfile_Message m on h.code = m.code
	if @Code <> 0 select h.*, m.PrivacyMessage from H_HospitalProfile h left join H_HospitalProfile_Message m on h.code = m.code where h.code = @Code
	--if @Code = 0 select * from H_HospitalProfile
	--if @Code <> 0 select * from H_HospitalProfile where code = @Code



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE   PROCEDURE [P_FetchICDInfo]
	@SearchTable as VarChar(50),
	@SearchCode as VarChar(10) = '0'
AS 

	DECLARE @SQL VarChar(800)
	
	SELECT @SQL = 'SELECT * FROM ' + @SearchTable + 
			  ' WHERE [CIHIValue] = ''' + @SearchCode + ''''
	EXECUTE (@SQL)
	print @SQL



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This returns the ICD 9 CM Live Date & ICD 10 Live Date
CREATE   PROCEDURE [P_FetchICDTypeDates]
	@Institution AS INTEGER
AS 

	SELECT ICDCMLive, ICDTLive FROM H_InstitutionProfile WHERE Code = @Institution




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO







-- This is called by the Preferences Object. To Load Institution Info..
CREATE     PROCEDURE [P_FetchInstitution]
	@InstCode as Int,
	@InstNum as VarChar(50),
	@HospID as int = 0
AS 

	IF @InstCode <> 0 
		BEGIN		
			SELECT * FROM H_InstitutionProfile WHERE Code = @InstCode
		END
	ELSE
		BEGIN
			SELECT * FROM H_InstitutionProfile WHERE DisplayCode = @InstNum 
			AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)			
		END






GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- This is called by Intervention Code to determine if it's an Operative Procedure.
CREATE   PROCEDURE [P_FetchInterventionOperative]
	@ICDType [varchar](1),
	@InterventionCode [varchar](20)
AS 
	IF @ICDType = '9' OR @ICDType = 'C'
		SELECT TranslateFrom FROM CMG_Main WHERE ICDType = @ICDType AND ProcDiagCode = @InterventionCode AND TranslateFrom LIKE 'APPDH%'
	ELSE
		SELECT TranslateFrom FROM CMG_Main2001 WHERE DiagProcCode = @InterventionCode AND TranslateFrom LIKE 'APPDH%'

	RETURN @@RowCount



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This is called by Intervention Code to determine if it's a Surgical Procedure.
CREATE   PROCEDURE [P_FetchInterventionSDS]
	@ICDType [varchar](1),
	@IntervCode [int],
	@ChkSDS [int] output
AS 
	IF @ICDType = '9' 
		SELECT @ChkSDS = ChkSDS FROM dbo.ICD_ProcFile9 WHERE Code = @IntervCode
	ELSE IF @ICDType = 'C'
		SELECT @ChkSDS = ChkSDS FROM dbo.ICD_ProcFile9cm WHERE Code = @IntervCode




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This is called by Intervention Code to determine if it's a Surgical Procedure.
CREATE   PROCEDURE [P_FetchInterventionSurgical]
	@ICDType [varchar](1),
	@InterventionCode [int],
	@SurgicalCode [varchar](1) OUTPUT
AS 
	IF @ICDType = '9' 
		SELECT @SurgicalCode = SurgicalCode FROM ICD_ProcFile9 WHERE Code = @InterventionCode

	ELSE IF @ICDType = 'C'
		SELECT @SurgicalCode = SurgicalCode FROM ICD_ProcFile9cm WHERE Code = @InterventionCode




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE  PROCEDURE [P_FetchLastDBUpdate]
	@LastDBUpdate as VarChar(10) output
AS

	Set @LastDBUpdate = (Select top 1 convert(VarChar(10), [LastUpdate], 111) 
		from dbo.M_DBUpdates order by LastUpdate Desc)




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE      PROCEDURE [P_FetchLocatorVolume]
	@VolumeID as Int
AS 
-- 	SELECT VolumeID AS [VolID],
-- 		VolumeNumber AS [VolNum],
-- 		(select DisplayCode from LoanLU_VolumeType where Code = CM_CPI_Volume.VolumeType) as [VolType], 	
-- 		(SELECT REPLACE(SPACE(10 - LEN(dbo.CM_CPI.ChartNumber)) + dbo.CM_CPI.ChartNumber, ' ', '0') FROM CM_CPI WHERE PatientID = dbo.CM_CPI_Volume.PatientID) AS [ChrtNum],
-- 		(SELECT UserDescription FROM dbo.LoanLU_Location WHERE Code = CLCurrentLocation) AS [CurLoc]
-- 	FROM CM_CPI_Volume 
-- 	WHERE VolumeID = @VolumeID
    --EN-00183
    select v.VolumeID AS [ ], 
        isnull(ch.DisplayCode, '') as [Chart Hospital Link],
		REPLACE(SPACE(10 - LEN(c.ChartNumber)) + c.ChartNumber, ' ', '0') AS ChartNumber, 
		(select DisplayCode from LoanLU_VolumeType where Code = v.VolumeType) as [Volume Type], 
        vh.DisplayCode as [Volume Hospital Link],
		v.VolumeNumber AS [Volume], 
		ISNULL(c.LastName, '') + ', ' + ISNULL(c.FirstName, '') + ' ' + ISNULL(c.MiddleName, '') AS [Full Name], 
        isnull(D.DisplayCode, '') as [Expirted],
		CONVERT(VarChar(10), c.BirthDate, 111) AS [Birth Date], 
		cl.DisplayCode AS [Current Location],
        FL.DisplayCode AS [Previous Location], 
		PL.DisplayCode AS [Permanent Location],
        v.CLBoxNumber as [Box Number],
		CONVERT(VarChar(10), c.LastVisitDate, 111) AS [Last Visit Date], 
		v.VolumeDateFrom AS [Date From],
		v.VolumenDateTo AS [Date To],
		isnull(Digit.DisplayCode, '') as [Digital]  --TS-222
	FROM dbo.CM_CPI_Volume v inner join
         dbo.CM_CPI c ON v.PatientID = c.PatientID LEFT OUTER JOIN
         dbo.LoanLU_Location CL ON v.CLCurrentLocation = CL.Code LEFT OUTER JOIN
         dbo.LoanLU_Location PL ON v.PermLocation = PL.Code LEFT OUTER JOIN
         dbo.LoanLU_Location FL ON v.CLPreviousLocation = FL.Code LEFT OUTER JOIN
         H_HospitalProfile CH on c.HospitalID = CH.Code LEFT OUTER JOIN
         H_HospitalProfile VH on v.HospitalID = VH.Code left join
         LU_YesNoSystem D on c.DeathIndicator = D.Code left join
         dbo.LoanLU_DigitalIndicator Digit on v.DigitalIndicator = Digit.code 
	WHERE v.VolumeID = @VolumeID
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is called by the Log In Window. of the Container.
CREATE   PROCEDURE [P_FetchLogIn]
	@UserName as varchar(50),
	@Password as varchar(50),
	@CLDate as datetime, -- Client Machine Date
	@DaysLeft as int output,
	@LogAttempt as int output,
    @AuditOff as int = 0, -- if 1 then don't audit it's the _wrXXX.exe atempting
    @ApplicationLogin as int = 0, --EN - 00412
    @LogID as int = 0 output    --EN - 00412
AS 

	declare @UseDate as datetime
	declare @updateDate as datetime
	declare @EnteredPassword as varchar(50)

	declare @HospID as int
	declare @LogMax as int
	declare @LogCnt as int
	
    set @DaysLeft = 360 --2.x-1628 -   Program Expired  --Never expired 
	set @LogID = 1
	set @EnteredPassword = @Password
	set @UseDate = cast(convert(varchar(20), getdate(), 111) as datetime)   --PR - 03858 GetDate()
	--PR-03040
	set @Password = replace(isnull(char(ASCII(SUBSTRING(reverse(@Password), 1, 1)) - 10), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@Password), 2, 1)) - 11), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@Password), 3, 1)) - 12), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@Password), 4, 1)) - 13), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@Password), 5, 1)) - 14), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@Password), 6, 1)) - 15), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@Password), 7, 1)) - 16), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@Password), 8, 1)) - 17), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@Password), 9, 1)) - 18), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@Password), 10, 1)) - 19), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@Password), 11, 1)) - 20), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@Password), 12, 1)) - 21), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@Password), 13, 1)) - 22), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@Password), 14, 1)) - 23), '') +
					isnull(char(ASCII(SUBSTRING(reverse(@Password), 15, 1)) - 24), ''), '               ', '')
	
	set @HospID = isnull((select top 1 HospitalID from dbo.U_Users where UserName = @UserName), 0) --Get the Hospital ID (if it's 0 then there is none)
	set @LogMax = isnull((select top 1 PasswordAttempt from dbo.H_HospitalProfile where (@HospID = case @HospID when 0 then 0 else Code end)), 0)     
    if isnull(@LogMax, 0) = 0 --PR - 04007
        set @LogMax = isnull((select top 1 PasswordAttempt from dbo.H_RegionProfile), 0)
    
	if @LogMax <> 0  -- Log Out Max is not 0, do this check
	begin
		--Retrieve the Attempts for this User, if the value is greater than the Max, don't allow log in.
		set @LogCnt = isnull ((select top 1 PasswordAttempt from dbo.U_Users where UserName = @UserName and UserPassword = @Password), 0)
		if @LogMax < @LogCnt 
		begin 			
			set @LogAttempt = -1 -- set it to negative; will note that the User is locked
			return 1
		end
	end

	select * from U_Users where Code <> 1 and UserName = @UserName and UserPassword = @Password and ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo])  and len(@UserName) > 0  and len(@Password) > 0
	if @@RowCount > 0  -- Found a match
	begin
		delete M_NCoder where Userid = (select top 1 code from U_Users where Code <> 1 and UserName = @UserName and UserPassword = @Password and ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]))
		update dbo.U_Users set PasswordAttempt = 0 where UserName = @UserName
	
		--9741	        
		declare @SC as int  --NP-00025
		declare @DC as varchar(50) --NP-00025
		declare @UD as varchar(255) --NP-00025
		
		select @SC = Code, @DC = DisplayCode, @UD = UserDescription from U_Users where Code <> 1 and UserName = @UserName and UserPassword = @Password and ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) --NP-00025
		delete M_CurrentLogIn where Code = @SC --NP-00025
		insert into M_CurrentLogIn values(@UserName, getdate(), @SC, @DC, @UD, @HospID) --NP-00025

        --if @AuditOff = 1 --EN - 00412 WinRecs.exe send @AuditOff = 0, WinRecs run time exe send @AuditOff = 1. Change from 0 to 1
        --begin
        --    insert into M_Login(UserName, PasswordEntered, LoginTime, Successful, Coder) Values (@UserName, '********', GetDate(), 'Y')
        --    set @LogID = @@Identity --EN 00412
        --end
        --0903 
        if @ApplicationLogin > 0 --Login exe will not add the log. Application exe to add the log
        begin
            insert into M_Login(UserName, PasswordEntered, LoginTime, Successful, Coder) Values (@UserName, '********', GetDate(), 'Y', @SC)
            set @LogID = @@Identity --EN 00412
        end
	end
	else -- No match found
	begin
		if @AuditOff = 0 
        begin
            --insert into M_Login(UserName, PasswordEntered, LoginTime, Successful) Values (@UserName, @EnteredPassword, GetDate(), 'N')
            insert into M_Login(UserName, PasswordEntered, LoginTime, Successful) Values (@UserName, '********', GetDate(), 'N')
            set @LogID = @@Identity --EN 00412
        end

		if @LogMax = 0  -- if Max is 0 then turn off this check
			set @LogAttempt = 0
		else
		begin
			update dbo.U_Users set PasswordAttempt = PasswordAttempt + 1 where UserName = @UserName
			set @LogCnt = isnull ((select PasswordAttempt from dbo.U_Users where UserName = @UserName and ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo])), 100)
		
			if @LogMax >= @LogCnt set @LogAttempt = @LogCnt -- set to Count; will note that User failed log in
			if @LogMax < @LogCnt set @LogAttempt = -1 -- set it to negative; will note that the User is locked
			if @LogCnt = 100 set @LogAttempt = 100 --set to 100; will note that User Name was not found
		end
	end

	--Check Expiry Date
    set @DaysLeft = 360 --2.x-1628 -   Program Expired  --Never expired 
	declare @Code as int 
	--declare @Year as int --Determines the CD Key expiry date year (value depends on the ascii char)
	--declare @CDKeyDate as datetime --CD Key expiry date
	--declare @SysDate as datetime --Server's Current System Date
	declare @LockOutDate as datetime --Lock-Out Date
		
	--set @Code = (select top 1 code from H_HospitalProfile where (@HospID = case @HospID when 0 then 0 else Code end))
	--set @Code = (select top 1 code from H_HospitalProfile where (@HospID = case @HospID when 0 then 0 else Code end))
	--set @Year = (select ascii(substring(cdkey, 27,1)) from H_HospitalProfile where Code = @Code)
	--if @Year between 65 and 90 set @Year = 2099 - @Year
	--else if @Year between 48 and 57 set @Year = 2057 - @Year

	--set @CDKeyDate = (select cast(@Year as varchar(4)) + '/' + cast((ascii(substring(cdkey, 28,1)) - 65) as varchar(2)) + '/01' from H_HospitalProfile where Code = @Code)
	--set @SysDate = getdate()
	select @LockOutDate = cast(Cdwr as datetime) from H_HospitalProfile where Code = @Code
	----The system date is more than 31 days before the CD Key date, it's good
	--if datediff(dd, @SysDate, @CDKeyDate) > 31
	--	set @DaysLeft = 32
	----There isn't a lock out date (this would be the first log in since < 31 days)
	--else if isnull(@LockOutDate, 0) = 0
	--begin
	--	--Month from now is after the CD Key date, make that the lock out date
	--	if dateadd(mm, 1, @SysDate) > @CDKeyDate set @LockOutDate = dateadd(mm, 1, @SysDate)
	--	--Otherwise make the lock out date the CD Key date
	--	else set @LockOutDate = @CDKeyDate			
		
	--	update H_HospitalProfile set cdwr = cast(@LockOutDate as int) where Code = @Code
	--	set @DaysLeft = datediff(dd, @SysDate, @LockOutDate)		
	--end
	----Lock out date is "1923/12/25", it's already locked out
	--else 
    if @LockOutDate = '1923/12/25'  --2.x-1628 - only the lock out date is set.
		set @DaysLeft = 0		
	----2.x-1628 -   Program Expired  --Never expired 
	----[RM] Not sure why we bother to use this, if it's all Server System Date driven everywhere else?????
	----The Client machine date is after the Server system date then use the Client machine
	----else if @CLDate >= @SysDate
	--	--set @DaysLeft = datediff(dd, @CLDate, @LockOutDate)
		
	----Days left before lock out, based on the Server system date
	--else
	--	set @DaysLeft = datediff(dd, @SysDate, @LockOutDate)
    
    --print @HospID
	--The number of days left is not greater than zero, lock out the User
	if @DaysLeft <= 0
	begin
		set @DaysLeft = 0
		set @LockOutDate = '1923/12/25'
		update H_HospitalProfile set cdwr = cast(@LockOutDate as int) where Code = @Code
	end
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [P_FetchLUCIHICodeBySystemCode]
	@SearchTable as VarChar(50),
	@SearchCode as VarChar(50)
AS 

	DECLARE @SQL VarChar(800)
    --PR - 04397
    if isnull(@SearchCode, '') = '' set @SearchCode = '0'

	SELECT @SQL = 'SELECT [CIHIValue] 
				FROM ' + @SearchTable + '
				WHERE [Code] = ' + @SearchCode
	EXECUTE (@SQL)
	RETURN 1



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE   PROCEDURE [P_FetchLUCodeBySystemCode]
	@SearchTable as VarChar(50),
	@SearchCode as VarChar(50)
AS 

	DECLARE @SQL VarChar(800)

	SELECT @SQL = 'SELECT [DisplayCode] 
				FROM ' + @SearchTable + '
				WHERE [Code] = ' + @SearchCode
	EXECUTE (@SQL)
	RETURN 1



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE   PROCEDURE [P_FetchLUCodeByValidCode]
	@SearchTable as VarChar(50),
	@SearchString as VarChar(50),
	@UseDate as VarChar(10)
AS 

	DECLARE @SQL VarChar(800)

    if isnumeric(@SearchTable) = 0
	    SELECT @SQL = 'SELECT [Code] 
				    FROM ' + @SearchTable + '
				     WHERE ([ValidFrom] <= ''' + @UseDate + ''') 
				    AND (''' + @UseDate + ''' <= [ValidTo]) 
				    AND [CIHIValue] = ''' + @SearchString + ''''
    else
	    SELECT @SQL = 'SELECT [Code] 
				    FROM lu_codefile
				     WHERE LookupID = ' + @SearchTable + ' and ([ValidFrom] <= ''' + @UseDate + ''') 
				    AND (''' + @UseDate + ''' <= [ValidTo]) 
				    AND [CIHIValue] = ''' + @SearchString + ''''
	EXECUTE (@SQL)
	RETURN 1



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [P_FetchMergedAbstract](
    @MergeID uniqueidentifier)
AS 
    select c.DisplayCode as [Care Type],
        a.DisplayCode as [Module],
        h.DisplayCode as [Institution Number],
        m.ChartNumber, 
        convert(varchar(20), Admitdate, 111) as [Admit/Register Date], 
        convert(varchar(20), Dischargedate, 111) as [Dischargedate Date], 
        m.FirstName as [First Name],
        m.LastName as [Last Name]
    from dbo.MRG_Record r
        inner join dbo.ab_main m on r.UniversalID = m.UniversalID
        left join dbo.H_InstitutionProfile h on m.InstitutionNumber = h.code
        left  join dbo.Lu_CareType c on m.AppType = c.code
        left  join dbo.LU_AppIDs a on m.AppID = a.Code
    where r.[ID] = @MergeID and AppID <> 0
    order by isnull(DischargeDate, AdmitDate)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [P_FetchMergeDuplicateVisit]
    @SourceChart varchar(20),
    @TargetChart varchar(20),
    @HospitalID  int,
    @DuplicateCount int output    
as
    set nocount on
    declare @create table (
        InstitutionNumber varchar(20),
        AdmitDate         varchar(20),
        AdmitTime         varchar(20),
        DischargeDate     varchar(20),
        DischargeTime     varchar(20),
        CareType          varchar(20)
    )
    --DAD 
    Insert into @create(InstitutionNumber, AdmitDate, AdmitTime, DischargeDate, DischargeTime, CareType)
    select h.CIHIValue, AdmitDate = convert(varchar(20), a.AdmitDate, 111), a.AdmitTime, DischargeDate = convert(varchar(20), a.DischargeDate, 111), a.DischargeTime, c.DisplayCode
    from    
    (select InstitutionNumber, AdmitDate, AdmitTime = dbo.Get4DigitTime(AdmitTime), DischargeDate, DischargeTime = dbo.Get4DigitTime(DischargeTime), AppType 
    from AB_Main 
    where ChartNumber = @SourceChart 
        and (isnull(AB_Main.HospitalID, 0) = 0 or @HospitalID = case @HospitalID when 0 then 0 else isnull(AB_Main.HospitalID, 0) end) 
        and AppID not in (0, 251, 252, 253, 254, 471, 472, 473, 474, 475, 476, 651, 652, 653, 654, 676)) a
    inner join 
    (select InstitutionNumber, AdmitDate, AdmitTime = dbo.Get4DigitTime(AdmitTime), DischargeDate, DischargeTime = dbo.Get4DigitTime(DischargeTime), AppType 
    from AB_Main 
    where ChartNumber = @TargetChart 
        and (isnull(AB_Main.HospitalID, 0) = 0 or @HospitalID = case @HospitalID when 0 then 0 else isnull(AB_Main.HospitalID, 0) end) 
        and AppID not in (0, 251, 252, 253, 254, 471, 472, 473, 474, 475, 476, 651, 652, 653, 654, 676)) b
    on isnull(a.InstitutionNumber, -1) = isnull(b.InstitutionNumber, -1) and 
        ((isnull(a.AdmitDate, '1900/01/01') = isnull(b.AdmitDate, '1900/01/01') and a.AdmitTime = b.AdmitTime)
         or (isnull(a.DischargeDate, '1950/01/01') = isnull(b.DischargeDate, '1900/01/01') and a.DischargeTime = b.DischargeTime)) and
         a.AppType = b.AppType
    left  join H_InstitutionProfile h on a.InstitutionNumber = h.code
    left  join LU_CareType c on a.AppType = c.code

    set @DuplicateCount = @@rowcount
    set nocount off

    select * from  @create order by AdmitDate, AdmitTime   
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_FetchMergeInformation](
    @ChartNumber varchar(10), 
    @HospitalID int,
    @MergeType int,
    @PatientID int = 0
)
AS 
--@MergeType = 0 for the merge
--@MergeType = 1 for the unmerge
--@MergeType = 2 for the unChange   PR - 04076
--@MergeType = 3 for the unRelocate PR - 04076
set nocount on
declare @ID uniqueidentifier,
    	@PatientIDFrom int,
    	@ChartNumberFrom varchar(10),
    	@PatientIDTo int,
    	@ChartNumberTo varchar(10),
    	@OrgFirstName varchar(100),
    	@OrgLastName varchar(100),
    	@UpdateType varchar(15),
    	@DateMerged datetime,
    	@CoderNumber int 

    CREATE TABLE #MRG_Main(
    	[ID] [uniqueidentifier] NULL ,
    	[PatientIDFrom] [int] NULL ,
    	[ChartNumberFrom] [varchar] (10) COLLATE Latin1_General_CI_AS NULL ,
    	[PatientIDTo] [int] NULL ,
    	[ChartNumberTo] [varchar] (10) COLLATE Latin1_General_CI_AS NULL ,
    	[OrgFirstName] [varchar] (100) COLLATE Latin1_General_CI_AS NULL ,
    	[OrgLastName] [varchar] (100) COLLATE Latin1_General_CI_AS NULL ,
    	[UpdateType] [varchar] (15) COLLATE Latin1_General_CI_AS NULL ,
    	[DateMerged] [datetime] NULL ,
    	[CoderNumber] [int] NULL 
    ) 
    
    if @MergeType = 0
    begin
        if @PatientID = 0
            insert into #MRG_Main([ID], PatientIDFrom, ChartNumberFrom, PatientIDTo, ChartNumberTo, OrgFirstName, OrgLastName, UpdateType, DateMerged, CoderNumber)
            select m.[ID], m.PatientIDFrom, m.ChartNumberFrom, m.PatientIDTo, m.ChartNumberTo, m.OrgFirstName, m.OrgLastName, m.UpdateType, m.DateMerged, m.CoderNumber
            from dbo.MRG_Main m
                inner join dbo.CM_CPI cm on  m.PatientIDFrom = cm.PatientID and m.ChartNumberFrom = cm.ChartNumber
            where cm.ChartNumber = @ChartNumber
                and m.UpdateType in ('Merged', 'Unmerged')
                AND (ISNULL(cm.HospitalID, 0) = 0 OR @HospitalID = case @HospitalID when 0 then 0 else ISNULL(cm.HospitalID, 0) end) 	
        else    --PR - 03348
            insert into #MRG_Main([ID], PatientIDFrom, ChartNumberFrom, PatientIDTo, ChartNumberTo, OrgFirstName, OrgLastName, UpdateType, DateMerged, CoderNumber)
            select m.[ID], m.PatientIDFrom, m.ChartNumberFrom, m.PatientIDTo, m.ChartNumberTo, m.OrgFirstName, m.OrgLastName, m.UpdateType, m.DateMerged, m.CoderNumber
            from dbo.MRG_Main m
                inner join dbo.CM_CPI cm on  m.PatientIDFrom = cm.PatientID and m.ChartNumberFrom = cm.ChartNumber
            where cm.ChartNumber = @ChartNumber
                and m.UpdateType in ('Merged', 'Unmerged')
                and cm.PatientID = @PatientID
    end
    else if @MergeType = 1 --Unmerged
    begin
        if @PatientID = 0
            insert into #MRG_Main([ID], PatientIDFrom, ChartNumberFrom, PatientIDTo, ChartNumberTo, OrgFirstName, OrgLastName, UpdateType, DateMerged, CoderNumber)
            select m.[ID], m.PatientIDFrom, m.ChartNumberFrom, m.PatientIDTo, m.ChartNumberTo, m.OrgFirstName, m.OrgLastName, m.UpdateType, m.DateMerged, m.CoderNumber
            from dbo.MRG_Main m
                inner join dbo.CM_CPI cm on  m.PatientIDTo = cm.PatientID and m.ChartNumberTo = cm.ChartNumber
            where cm.ChartNumber = @ChartNumber
                and m.UpdateType in ('Merged', 'Unmerged')
                AND (ISNULL(cm.HospitalID, 0) = 0 OR @HospitalID = case @HospitalID when 0 then 0 else ISNULL(cm.HospitalID, 0) end) 	
        else
            insert into #MRG_Main([ID], PatientIDFrom, ChartNumberFrom, PatientIDTo, ChartNumberTo, OrgFirstName, OrgLastName, UpdateType, DateMerged, CoderNumber)
            select m.[ID], m.PatientIDFrom, m.ChartNumberFrom, m.PatientIDTo, m.ChartNumberTo, m.OrgFirstName, m.OrgLastName, m.UpdateType, m.DateMerged, m.CoderNumber
            from dbo.MRG_Main m
                inner join dbo.CM_CPI cm on  m.PatientIDTo = cm.PatientID and m.ChartNumberTo = cm.ChartNumber
            where cm.ChartNumber = @ChartNumber
                and m.UpdateType in ('Merged', 'Unmerged')
                and cm.PatientID = @PatientID
    end
    else if @MergeType = 2 --Unchanged PR - 04076
    begin
        if @PatientID = 0
            insert into #MRG_Main([ID], PatientIDFrom, ChartNumberFrom, PatientIDTo, ChartNumberTo, OrgFirstName, OrgLastName, UpdateType, DateMerged, CoderNumber)
            select m.[ID], m.PatientIDFrom, m.ChartNumberFrom, m.PatientIDTo, m.ChartNumberTo, m.OrgFirstName, m.OrgLastName, m.UpdateType, m.DateMerged, m.CoderNumber
            from dbo.MRG_Main m
                inner join dbo.CM_CPI cm on  m.PatientIDTo = cm.PatientID and m.ChartNumberTo = cm.ChartNumber
            where cm.ChartNumber = @ChartNumber
                and m.UpdateType in ('Changed', 'Changed')
                AND (ISNULL(cm.HospitalID, 0) = 0 OR @HospitalID = case @HospitalID when 0 then 0 else ISNULL(cm.HospitalID, 0) end) 	
        else
            insert into #MRG_Main([ID], PatientIDFrom, ChartNumberFrom, PatientIDTo, ChartNumberTo, OrgFirstName, OrgLastName, UpdateType, DateMerged, CoderNumber)
            select m.[ID], m.PatientIDFrom, m.ChartNumberFrom, m.PatientIDTo, m.ChartNumberTo, m.OrgFirstName, m.OrgLastName, m.UpdateType, m.DateMerged, m.CoderNumber
            from dbo.MRG_Main m
                inner join dbo.CM_CPI cm on  m.PatientIDTo = cm.PatientID and m.ChartNumberTo = cm.ChartNumber
            where cm.ChartNumber = @ChartNumber
                and m.UpdateType in ('Changed', 'UnChanged')
                and cm.PatientID = @PatientID
    end
    else if @MergeType = 3 --UnRelocate PR - 04076
    begin

        select UniversalID, CNFrom, ChartTo, max(UniversalID) maxDate into #Relocate 
        from dbo.MRG_Relocate
        where ChartTo = @ChartNumber
        group by UniversalID, CNFrom, ChartTo    
        
        insert into #MRG_Main([ID], PatientIDFrom, ChartNumberFrom, PatientIDTo, ChartNumberTo, OrgFirstName, OrgLastName, UpdateType, DateMerged, CoderNumber)
        select distinct null, 0, m.CNFrom, 0, m.ChartTo, '', '', 'Relocate', null, null
        from dbo.MRG_Relocate m
            inner join dbo.ab_main ab on m.UniversalID = ab.UniversalID and ab.ChartNumber = m.ChartTo
            inner join #Relocate z on m.UniversalID = z.UniversalID and m.RelocateDate = z.maxDate
        where ab.ChartNumber = @ChartNumber
            AND (ISNULL(ab.HospitalID, 0) = 0 OR @HospitalID = case @HospitalID when 0 then 0 else ISNULL(ab.HospitalID, 0) end) 	
        
    end
    if @MergeType <> 3
    begin
        declare Unmerge cursor SCROLL for
            select PatientIDFrom, PatientIDTo, UpdateType, DateMerged   --, ChartNumberFrom --, ChartNumberTo, 
            from #MRG_Main
            order by DateMerged desc
        open Unmerge

        fetch next from unmerge into @PatientIDFrom, @PatientIDTo, @UpdateType, @DateMerged --,  @ChartNumberFrom --, @ChartNumberTo, 

        while(@@fetch_status = 0)
        begin
            if @UpdateType in ('Unmerged', 'UnChanged')
            begin
                close unmerge
                --select * from #MRG_Main
                --print @ChartNumberFrom + ',  ' +  @ChartNumberTo + ',  ' + @UpdateType + ', ' + cast(@DateMerged as varchar(50))
                delete from #MRG_Main where PatientIDFrom = @PatientIDFrom and PatientIDTo = @PatientIDTo and DateMerged <= @DateMerged
                --delete from #MRG_Main where ChartNumberFrom = @ChartNumberFrom and ChartNumberTo = @ChartNumberTo and DateMerged <= @DateMerged
                open unmerge
                --fetch first from unmerge into @ChartNumberFrom, @ChartNumberTo, @UpdateType, @DateMerged
            end
           
            fetch next from unmerge into @PatientIDFrom, @PatientIDTo, @UpdateType, @DateMerged --, @ChartNumberFrom --, @ChartNumberTo, 
        end
        close unmerge
        deallocate unmerge
    end

    if @MergeType = 0 
        select m.[ID], cm.PatientID, m.ChartNumberTo, isnull(cm.LastName + ', ', '') + isnull(cm.FirstName, '') + ' - Merged on ' + convert(varchar(20), m.DateMerged, 111) + isnull(', ' + h.DisplayCode, '') as PatientInformation, isnull(cm.HospitalID , 0) as Hospital -- PR - 03348
        from #MRG_Main m
            inner join dbo.CM_CPI cm on  m.PatientIDTo = cm.PatientID and m.ChartNumberTo = cm.ChartNumber
            left  join H_HospitalProfile h on cm.HospitalID = h.code
        where [UpdateType] = 'Merged'
        order by DateMerged desc
    else if @MergeType = 1
        select m.[ID], cm.PatientID, m.ChartNumberFrom, isnull(cm.LastName + ', ', '') + isnull(cm.FirstName, '') + ' - Merged on ' + convert(varchar(20), m.DateMerged, 111) + isnull(', ' + h.DisplayCode, '') as PatientInformation, isnull(cm.HospitalID , 0) as Hospital -- PR - 03348 
        from #MRG_Main m
            inner join dbo.CM_CPI cm on  m.PatientIDFrom = cm.PatientID and m.ChartNumberFrom = cm.ChartNumber
            left  join H_HospitalProfile h on cm.HospitalID = h.code
        where [UpdateType] = 'Merged'
        order by DateMerged desc
    else if @MergeType = 2
        select m.[ID], cm.PatientID, m.ChartNumberFrom, isnull(cm.LastName + ', ', '') + isnull(cm.FirstName, '') + ' - Merged on ' + convert(varchar(20), m.DateMerged, 111) + isnull(', ' + h.DisplayCode, '') as PatientInformation, isnull(cm.HospitalID , 0) as Hospital -- PR - 03348 
        from #MRG_Main m
            inner join dbo.CM_CPI cm on  m.PatientIDFrom = cm.PatientID and m.ChartNumberFrom = cm.ChartNumber
            left  join H_HospitalProfile h on cm.HospitalID = h.code
        where [UpdateType] = 'Changed'
        order by DateMerged desc
    else if @MergeType = 3
        select m.[ID], cm.PatientID, m.ChartNumberFrom, isnull(cm.LastName + ', ', '') + isnull(cm.FirstName, '') + ' - Merged on ' + convert(varchar(20), m.DateMerged, 111) + isnull(', ' + h.DisplayCode, '') as PatientInformation, isnull(cm.HospitalID , 0) as Hospital -- PR - 03348 
        from #MRG_Main m
            inner join dbo.CM_CPI cm on  m.ChartNumberFrom = cm.ChartNumber
            left  join H_HospitalProfile h on cm.HospitalID = h.code
        where [UpdateType] = 'Relocate' 
        order by DateMerged desc

    set nocount off
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_FetchMergeRegionalInformation](
    @PatientID int 
)
AS 

set nocount on


    CREATE TABLE #MRG_RegionalID(
		[ID] [uniqueidentifier] not null primary key,
		[PatientIDFrom] [int] NULL,
		[ChartNumberFrom] [varchar](10) NULL,
		[RegionPatientIDFrom] [varchar](50) NULL,
		[PatientIDTo] [int] NULL,
		[ChartNumberTo] [varchar](10) NULL,
		[RegionPatientIDTo] [varchar](50) NULL,
		[UpdateType] [varchar](15) NULL,
		[DateMerged] [datetime] NULL,
		[CoderNumber] [int] NULL
	)
    

    insert into #MRG_RegionalID(ID, PatientIDFrom, ChartNumberFrom, RegionPatientIDFrom, PatientIDTo, ChartNumberTo, RegionPatientIDTo, UpdateType, DateMerged, CoderNumber)
    select TOP 1 ID, PatientIDFrom, ChartNumberFrom, RegionPatientIDFrom, PatientIDTo, ChartNumberTo, RegionPatientIDTo, UpdateType, DateMerged, CoderNumber
    from dbo.MRG_RegionalID
    where PatientIDFrom = @PatientID
	ORDER BY  DateMerged DESC            
    
	delete from #MRG_RegionalID where UpdateType <> 'Merged'
	
	select * from #MRG_RegionalID
	
    set nocount off
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE  PROCEDURE [P_FetchNTUser]
	@NTUser as Varchar(100),
	@UserID as int = 0 --PR-03082
AS
	select * from U_Users where ntauthority = @NTUser and Code <> @UserID 
	return @@rowcount


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- This is called by OMHRS to default Assessment
CREATE   PROCEDURE [P_FetchOMHRSDefaults]
	@AbstractID as int
AS 

select AA.AbstractID, ChartNumber, AA3, InstitutionNumber, AA5, LastName, MiddleName, FirstName, Secret 
from OMHRS_SecAA AA inner join OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
where AA.AbstractID = @AbstractID


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This is called by the Pull List Maker Form to retieve the Patient ID for Loading the Activity.
CREATE   PROCEDURE [P_FetchPatientIDByVolumeID]
	@VolumeID AS INTEGER
AS 

	DECLARE @PatID AS INTEGER

	SELECT @PatID = PatientID FROM CM_CPI_Volume WHERE VolumeID = @VolumeID
	RETURN @PatID




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is called by Submission to return Previous Amcare Submission.
CREATE PROCEDURE [P_FetchPrevAmcareSubmit]
    @InstNumber [int],
    @BatchYear  [int],
    @BatchPeriod [int],
    @LevelCode [int]    --NP - 00125

AS 
    if isnull(@LevelCode, -1) not in (0, 1, 2)
        SELECT DISTINCT CIHIDateSent = convert(varchar(20), CIHIDateSent, 100 ) 
        FROM AB_Abstract 
        WHERE InstitutionNumber = @InstNumber AND BatchYear = @BatchYear AND BatchPeriod = @BatchPeriod
			and CIHIDateSent is not null
    else if isnull(@LevelCode, -1) in (1, 2) --NP - 00125
        SELECT DISTINCT CIHIDateSentLevel1 = convert(varchar(20), CIHIDateSentLevel1, 100 ) 
        FROM AB_Abstract 
            inner join LU_MISCode on MISCode = LU_MISCode.Code
        WHERE InstitutionNumber = @InstNumber AND BatchYear = @BatchYear AND BatchPeriod = @BatchPeriod
			and CIHIDateSentLevel1 is not null
            and LU_MISCode.AmcareGroup = 'ED'
    else if @LevelCode = 0 --2.x-1683 -   Clear Submission - Care Type B-C-Lite
        SELECT DISTINCT CIHIDateSentLevel1 = convert(varchar(20), CIHIDateSentLevel1, 100 ) 
        FROM AB_Abstract 
            inner join LU_MISCode on MISCode = LU_MISCode.Code
        WHERE InstitutionNumber = @InstNumber AND BatchYear = @BatchYear AND BatchPeriod = @BatchPeriod
			and CIHIDateSentLevel1 is not null
            and [ClinicLite] = 1
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- This is called by Projects to return the Question Captions.
CREATE   PROCEDURE [P_FetchProject]
	@ProjectNumber [int]
AS 

	SELECT Question1, QuestionDefault1,
		Question2, QuestionDefault2,
		Question3, QuestionDefault3, 
		Question4, QuestionDefault4,
		Question5, QuestionDefault5,
		Question6, QuestionDefault6,
		Question7, QuestionDefault7,
		Question8, QuestionDefault8,
		Question9, QuestionDefault9,
		Question10, QuestionDefault10,
		Question11, QuestionDefault11,
		Question12, QuestionDefault12,
		Question13, QuestionDefault13,
		Question14, QuestionDefault14,
		Question15, QuestionDefault15,
		Question16, QuestionDefault16,
		Question17, QuestionDefault17,
		Question18, QuestionDefault18,
		Question19, QuestionDefault19,
		Question20, QuestionDefault20,
		Question21, QuestionDefault21,
		Question22, QuestionDefault22,
		Question23, QuestionDefault23,
		Question24, QuestionDefault24
	FROM LU_Project 
	WHERE Code = @ProjectNumber



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO





-- This is called by Deficiency to send back the Resident Flag for a Provider
CREATE   PROCEDURE [P_FetchProviderResidentFlag]
	@Code AS INTEGER
AS
	DECLARE @Flag AS INTEGER

	SELECT @Flag = ProvdrResident FROM LU_Provider WHERE Code = @Code
	RETURN @Flag




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- Called by the Visit History Grid to get the Assessment Type of a Rehab Record
CREATE     PROCEDURE [P_FetchRehabAssessmentType]
	@RecordID AS INTEGER
AS 
	DECLARE @Type AS INTEGER
	SELECT @Type = AssessmentType FROM RH_ClientInfo WHERE AbstractID =  @RecordID
	RETURN @Type



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- This is called by Rehab to default Discharge or Follow Up records
CREATE   PROCEDURE [P_FetchRehabDefaults]
	@AbstractID AS INT
AS 

SELECT C.ProgramType, C.ChartNumber, C.HealthCareNumber, C.HCNVersion, C.HCNProvince, C.AdmitDate, C.DischargeDate, C.InstitutionNumber, C.SiteNumber, C.CoderNumber, C.EncounterNumber, C.RegisterNumber, C.Secret,
 	D.MaidenName, D.LastName, D.MiddleName, D.FirstName, D.Gender, D.BirthDate, D.BirthDateEstimated, D.LanguageCode, D.ResidenceCountry, D.PostalCode, D.Province, 
	D.LivingSpouse, D.LivingFamily, D.LivingUnPaid, D.LivingPaid, D.LivingAlone, D.LivingHospital, D.LivingOther, D.LivingTemp, D.LivingSetting, D.PaidFullTime, D.PaidPartTime, 
	D.PaidAdjusted, D.UnPaidFullTime, D.UnPaidPartTime, D.UnPaidAdjusted, D.StudentFullTime, D.StudentPartTime, D.StudentAdjusted, D.UnEmployed, D.RetiredAge, D.RetiredDisable, D.VocationNone,
	A.AdmitClass, A.RP_ProvincePlan, A.RP_WCB_WSIB, A.RP_OtherProvince, A.RP_Fed_DVA, A.RP_Fed_FNIHB, A.RP_Fed_Other, A.RP_CanadaSelf, A.RP_CanadaInsure, A.RP_OtherSelf, A.RP_ProvinceDefinition, 
	H.ClientGroup, H.Height, H.Weight, H.WrittenConditionMain, 
	DX.DiagnosisCode, DX.DiagnosisType
FROM 	dbo.RH_Health H RIGHT OUTER JOIN
     	dbo.RH_Demographic D RIGHT OUTER JOIN
	dbo.RH_ClientInfo C ON D.AbstractID = C.AbstractID LEFT OUTER JOIN
        dbo.RH_Administrative A ON C.AbstractID = A.AbstractID ON 
        H.AbstractID = C.AbstractID LEFT OUTER JOIN
        dbo.RH_Diagnosis DX ON C.AbstractID = DX.AbstractID
WHERE	(C.AbstractID = @AbstractID) AND (ISNULL(DX.DiagnosisOccurrence, 1) = 1)

SELECT C.DischargeDate, H.ClientGroup
FROM 	dbo.RH_Health H RIGHT OUTER JOIN
     	dbo.RH_ClientInfo C ON H.AbstractID = C.AbstractID 
WHERE (C.LinkID = @AbstractID AND C.AssessmentType = 135)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO






-- This is called by ROI to retieve the Requester Type Linked to the Requester.
CREATE    PROCEDURE [P_FetchRequesterType]
	@Code AS INTEGER --,
--	@ReqType AS INTEGER OUTPUT,
--	@CostLevel AS INTEGER OUTPUT
AS
	
--	SELECT @ReqType = RequesterType, @CostLevel = CostLevel FROM LU_ROI_Requesters WHERE Code = @Code
	select [RequesterType], [CostLevel],
		[Address], [PostalCode], [City], [Province],[Country], 
		[BillingAddress], [BillingPostalCode], [BillingCity], [BillingProvince], [BillingCountry], 
		[Phone], [PhoneExt], [Fax]
	from LU_ROI_Requesters where Code = @Code

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO





-- This is called by ROI to retieve the Chargeable & Auth Required status of a Reques Type.
CREATE   PROCEDURE [P_FetchRequestInfo]
	@Code AS INTEGER,
	@Chargeable AS INTEGER OUTPUT,
	@AuthRequired AS INTEGER OUTPUT
AS
	SELECT @Chargeable = Chargeable, @AuthRequired = AuthRequired FROM LU_ROI_RequestTypes WHERE Code = @Code




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- This is called by ROI. To Load Contact Info
CREATE   PROCEDURE [P_FetchROIContact]
	@Code AS INT
AS 
	SELECT * FROM LU_ROI_Contacts WHERE Code = @Code



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This is called by ROI to retieve the Requester Type Linked to the Requester.
CREATE   PROCEDURE [P_FetchROISentItemPriceTax]
	@Code AS INTEGER,
	@CostLevel AS INTEGER,
	@ItemPrice AS MONEY OUTPUT,
	@ItemTax AS INTEGER OUTPUT
AS
	
	IF @CostLevel = 0 OR @CostLevel = 1 
		SELECT @ItemPrice = ROIPrice, @ItemTax = TaxType FROM LU_ROI_SentItemTypes WHERE Code = @Code
	ELSE IF @CostLevel = 2 
		SELECT @ItemPrice = ROIPrice2, @ItemTax = TaxType FROM LU_ROI_SentItemTypes WHERE Code = @Code
	ELSE IF @CostLevel = 3
		SELECT @ItemPrice = ROIPrice3, @ItemTax = TaxType FROM LU_ROI_SentItemTypes WHERE Code = @Code
	ELSE IF @CostLevel = 4
		SELECT @ItemPrice = ROIPrice4, @ItemTax = TaxType FROM LU_ROI_SentItemTypes WHERE Code = @Code
	ELSE IF @CostLevel = 5
		SELECT @ItemPrice = ROIPrice5, @ItemTax = TaxType FROM LU_ROI_SentItemTypes WHERE Code = @Code



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- This is called by OHIP Service Number to return the Billing Info
CREATE   PROCEDURE [P_FetchSerivceBillInfo]
	@SNum 	[int]
AS 

SELECT (GeneralFee + AssistantFee + SpecialistFee + AnaesthetistFee + NonAnaesthetistFee) AS [Fee],
	MAN_REV,
	MRI_EXCL,
	DIAG_REQ,
	REF_PHYS,
	HOSP_REQ,
	ADMIT_DT,
	IO_REQ
FROM LU_OhipFeeCodes
WHERE Code = @SNum



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


-- This is called by Transcription to default Chart & Abstract shared fields
CREATE   PROCEDURE [P_FetchTransSharedDefaults]
	@CareType as int, 
	@PatientID as int ,
	@AbstractID as int 
AS
	select AlternateAddress, BirthPlace, PhysicianNumber, PhysicianPhone, PrimaryAddress, PrimaryPhone 
	from dbo.CM_CPI where PatientID = @PatientID
	
	if @CareType = 1 or @CareType = 2 or @CareType = 5 -- AbCare / SDS / AmCare
	    select AdmitDate, AttendingPhysician, AgeNumber, BirthDate, 
	        ChartNumber, DischargeDate, EncounterNumber, 
	        FirstName, LastName, AdmittingNurseArea, RegisterNumber, ProviderNumber
	    from dbo.AB_Abstract left join dbo.AB_Provider on dbo.AB_Abstract.AbstractID = dbo.AB_Provider.AbstractID
	    where isnull(ProviderOccurrence, 1) = 1
	    and dbo.AB_Abstract.AbstractID = @AbstractID
	
	else if @CareType = 3 -- Rehab
	    select AdmitDate, 0 as AttendingPhysician, AgeNumber, BirthDate, 
	        ChartNumber, DischargeDate, EncounterNumber, 
	        FirstName, LastName, 0 as AdmittingNurseArea, RegisterNumber, 0 as ProviderNumber
	    from RH_ClientInfo inner join RH_Demographic on RH_ClientInfo.AbstractID = RH_Demographic.AbstractID
	    where RH_ClientInfo.AbstractID = @AbstractID
	
	else if @CareType = 4 -- CCRS
	    select A3 as AdmitDate, 0 as AttendingPhysician, 0 as AgeNumber, BirthDate, 
	        ChartNumber, null as DischargeDate, AA1 as EncounterNumber, 
	        FirstName, LastName, 0 as AdmittingNurseArea, RegisterNumber, 0 as ProviderNumber
	    from CRS_Demographic
	    where AbstractID = @AbstractID
	
	else if @CareType = 7 -- OMHRS
	    -- TEMP (REPLACE LATER
	    select null as AdmitDate, 0 as AttendingPhysician, 0 as AgeNumber, null as BirthDate, 
	        null as ChartNumber, null as DischargeDate, null as EncounterNumber, 
	        null as FirstName, null as LastName, 0 as AdmittingNurseArea, null as RegisterNumber, 0 as ProviderNumber
	
	else --  @CareType = 9 -- NON Abstract
	    select null as AdmitDate, 0 as AttendingPhysician, 0 as AgeNumber, null as BirthDate, 
	        null as ChartNumber, null as DischargeDate, null as EncounterNumber, 
	        null as FirstName, null as LastName, 0 as AdmittingNurseArea, null as RegisterNumber, 0 as ProviderNumber    

-- OLD PROC
/*
	@PatientID AS INT,
	@AbstractID AS INT
AS

SELECT AlternateAddress, 
	BirthPlace, 
	PhysicianNumber, 
	PhysicianPhone, 
	PrimaryAddress, 
	PrimaryPhone
FROM dbo.CM_CPI 
WHERE PatientID = @PatientID
	
SELECT AdmitDate, 
	AttendingPhysician, 
	AgeNumber, 
        	BirthDate, 
	ChartNumber, 
	DischargeDate, 
	EncounterNumber, 
        	FirstName, 
	LastName, 
	AdmittingNurseArea, 
	RegisterNumber,
	ProviderNumber
FROM dbo.AB_Abstract LEFT JOIN dbo.AB_Provider ON dbo.AB_Abstract.AbstractID = dbo.AB_Provider.AbstractID
WHERE ISNULL(ProviderOccurrence, 1) = 1
AND dbo.AB_Abstract.AbstractID = @AbstractID
*/

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- This is called by Apps that need to know about other User's that have the System ID for her.
CREATE   PROCEDURE [P_FetchUserInfo]
	@UserID [int]
AS 

	SELECT * FROM U_Users WHERE Code = @UserID











GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO





-- This is called by the Session Object. To Load User Screen Edit String, There is only one record..
CREATE   PROCEDURE [P_FetchUserScreenEdit]
AS 

	SELECT * FROM P_UserScreenEdit




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- This is called by Load of Apps that need to get User Defined Screen Data
CREATE   PROCEDURE [P_FetchUserScreenValues]
   @AbstractID [int]
AS 

   IF EXISTS(SELECT * FROM Information_Schema.Tables WHERE Table_Name = 'AB_UserDefined') 
           SELECT * FROM AB_UserDefined WHERE AbstractID = @AbstractID
   IF EXISTS(SELECT * FROM Information_Schema.Tables WHERE Table_Name = 'AB_UserMulti1') 
           SELECT * FROM AB_UserMulti1 WHERE AbstractID = @AbstractID ORDER BY Occurrence
   IF EXISTS(SELECT * FROM Information_Schema.Tables WHERE Table_Name = 'AB_UserMulti2') 
           SELECT * FROM AB_UserMulti2 WHERE AbstractID = @AbstractID ORDER BY Occurrence
   IF EXISTS(SELECT * FROM Information_Schema.Tables WHERE Table_Name = 'AB_UserMulti3') 
           SELECT * FROM AB_UserMulti3 WHERE AbstractID = @AbstractID ORDER BY Occurrence
   IF EXISTS(SELECT * FROM Information_Schema.Tables WHERE Table_Name = 'AB_UserMulti4') 
           SELECT * FROM AB_UserMulti4 WHERE AbstractID = @AbstractID ORDER BY Occurrence
   IF EXISTS(SELECT * FROM Information_Schema.Tables WHERE Table_Name = 'AB_UserMulti5') 
           SELECT * FROM AB_UserMulti5 WHERE AbstractID = @AbstractID ORDER BY Occurrence




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- This is called by CPI Volume to default Chart & Abstract shared fields
CREATE  PROCEDURE [P_FetchVolumeDefaults]
	@PatientID as int,
    @HospID as int
AS

    select 
    DateFrom      = min((case when AppType in (1, 2, 3, 4, 7) then isnull(DischargeDate, AdmitDate) 
                          else AdmitDate end)),
    DateTo        = max((case when AppType in (1, 2, 3, 4, 7) then isnull(DischargeDate, AdmitDate)
                          else AdmitDate end)),
    HasAmcare     = sum((case when AppType = 5 then 1 else 0 end)),
    HasInpatient  = sum((case when AppType in (1, 3, 4, 7) then 1 else 0 end)),
    HasSDS        = sum((case when AppType = 2 then 1 else 0 end)),
    HasOutpatient = sum((case when AppType in (6, 9) then 1 else 0 end)),
    VolumeCount   = isnull((select count(*) from CM_CPI_Volume where PatientID = @PatientID AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)), 0)
    from AB_Main AB
        inner join CM_CPI CM on AB.ChartNumber = CM.ChartNumber 
            and (isnull(CM.HospitalID, 0) = 0
            or isnull(AB.HospitalID, 0) = isnull(CM.HospitalID, isnull(AB.HospitalID, 0)))
    where appid <> 0 and AdmitDate is not null
        and CM.PatientID = @PatientID
        AND (ISNULL(AB.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(AB.HospitalID, 0) end)





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO






CREATE   PROCEDURE [P_FetchWRExpiry]
	@CLDate as datetime,
	@DaysLeft as int output
AS
	Declare @ExpiryDate as datetime
	Declare @WRExpiry as Datetime
	Declare @SDate as datetime

	Set @WRExpiry = (select Cast((2000 + ascii(substring(cdkey, 27,1)) - 72) as varchar(4)) + 
		'/' + cast((ascii(substring(cdkey, 28,1)) - 66) as varchar(2)) + '/01'  from H_HospitalProfile)

	Set @SDate = cast(convert(varchar(20), getdate(), 111) as datetime) --PR - 03858 getdate()
	select @ExpiryDate = cast(Cdwr as datetime) from H_HospitalProfile
	If DateDiff(dd, @SDate, @WRExpiry) > 31
	Begin
		Set @DaysLeft = 32
	End
	Else If isnull(@ExpiryDate, 0) = 0
	Begin
		If Dateadd(mm, 1, @Sdate) > @WRExpiry
		Begin
			Set @ExpiryDate = Dateadd(mm, 1, @Sdate)
			Update H_HospitalProfile set cdwr = cast(@ExpiryDate as int)
			Set @DaysLeft = DateDiff(dd, @SDate, @ExpiryDate)
		End
		Else
		Begin
			Set @ExpiryDate = @WRExpiry
			Update H_HospitalProfile set cdwr = cast(@ExpiryDate as int)
			Set @DaysLeft = DateDiff(dd, @SDate, @ExpiryDate)
		End
	End
	Else If @ExpiryDate = '1923/12/25'
		Set @DaysLeft = 0
	Else If @CLDate >= @SDate
		Set @DaysLeft = datediff(dd, @CLDate, @ExpiryDate)
	Else
		Set @DaysLeft = datediff(dd, @SDate, @ExpiryDate)

	If @DaysLeft <= 0
	Begin
		Set @DaysLeft = 0
		Set @ExpiryDate = '1923/12/25'
		Update H_HospitalProfile set cdwr = cast(@ExpiryDate as int)
	End	





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [P_FindPreviousMerge]
	@ChartNumberFrom as VarChar(10),
	@ChartNumberTo as VarChar(10),
    @Action int   --0 -- Merge 1 -- Change PR - 04076
AS

	SELECT TOP 1 *
	FROM dbo.MRG_Main 
    WHERE ((UpdateType = 'Merged' and @Action = 0) or (UpdateType = 'Changed' and @Action = 1))
        AND (ChartNumberFrom = @ChartNumberFrom) AND (ChartNumberTo = @ChartNumberTo)
	ORDER BY DateMerged DESC

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


Create PROCEDURE [P_Get_HighPriorityFromLocAndBorrow]
	(@Location 		[int],
     @Borrower      [int],
    @RequestPriority int output)
AS 
    declare @LocationPriority int
    declare @BorrowPriority int
    declare @LocationRate int
    declare @BorrowRate   int
    
    select top 1 @LocationPriority = LoanLU_Location.CLRequestPriority,
         @LocationRate = LoanLu_RequestPriority.PriorityRate
    from LoanLU_Location left join
        LoanLu_RequestPriority on LoanLU_Location.CLRequestPriority = LoanLu_RequestPriority.Code
    where LoanLU_Location.Code = @Location

    select top 1 @BorrowPriority = LoanLU_Borrower.CLRequestPriority, 
         @BorrowRate = LoanLu_RequestPriority.PriorityRate
    from LoanLU_Borrower left join
        LoanLu_RequestPriority on LoanLU_Borrower.CLRequestPriority = LoanLu_RequestPriority.Code
    where LoanLU_Borrower.Code = @Borrower

    if @LocationRate is null and @BorrowRate is null
        set @RequestPriority = 0
    else if @LocationRate is null and @BorrowRate is not null
        set @RequestPriority = @BorrowPriority
    else if @LocationRate is not null and @BorrowRate is null
        set @RequestPriority = @LocationPriority
    else if @LocationRate >= @BorrowRate
        set @RequestPriority = @LocationPriority
    else  
        set @RequestPriority = @BorrowPriority
        




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


Create PROCEDURE [P_Get_PriorityFromBorrower]
	(@Code 		[int],
    @RequestPriority int output)
AS 

set @RequestPriority = isnull((select top 1 CLRequestPriority from LoanLU_Borrower where Code = @Code), 0)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


Create PROCEDURE [P_Get_PriorityFromLocation]
	(@Code 		[int],
    @RequestPriority int output)
AS 

set @RequestPriority = isnull((select top 1 CLRequestPriority from LoanLU_Location where Code = @Code), 0)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE       PROCEDURE [P_GetAbstVolumeID]	
	@RecordID as int,
	@AppID as int = 0 --NP-00025
AS 
declare @VolID as int

--select @VolID = VolumeID from AB_Abstract where AbstractID = @RecordID -- NP-00025
select @VolID = VolumeID from AB_Main where AppID = @AppID and AbstractID = @RecordID --NP-00025
return @VolID



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE  PROCEDURE [P_GetBasicOptionText]
	@InstitutionNumber AS INT,
	@BOPNumber AS INT
AS 

	IF @BOPNumber = 1 
		SELECT BOP_Text1 FROM H_InstitutionProfile WHERE Code = @InstitutionNumber
	ELSE IF @BOPNumber = 2
		SELECT BOP_Text2 FROM H_InstitutionProfile WHERE Code = @InstitutionNumber
	ELSE IF @BOPNumber = 3
		SELECT BOP_Text3 FROM H_InstitutionProfile WHERE Code = @InstitutionNumber
	ELSE IF @BOPNumber = 4
		SELECT BOP_Text4 FROM H_InstitutionProfile WHERE Code = @InstitutionNumber
	ELSE IF @BOPNumber = 5
		SELECT BOP_Text5 FROM H_InstitutionProfile WHERE Code = @InstitutionNumber
	ELSE IF @BOPNumber = 6
		SELECT BOP_Text6 FROM H_InstitutionProfile WHERE Code = @InstitutionNumber
	ELSE IF @BOPNumber = 7
		SELECT BOP_Text7 FROM H_InstitutionProfile WHERE Code = @InstitutionNumber
	ELSE IF @BOPNumber = 8
		SELECT BOP_Text8 FROM H_InstitutionProfile WHERE Code = @InstitutionNumber
	ELSE IF @BOPNumber = 9
		SELECT BOP_Text9 FROM H_InstitutionProfile WHERE Code = @InstitutionNumber
	ELSE IF @BOPNumber = 10 
		SELECT BOP_Text10 FROM H_InstitutionProfile WHERE Code = @InstitutionNumber
	ELSE IF @BOPNumber = 11 
		SELECT BOP_Text11 FROM H_InstitutionProfile WHERE Code = @InstitutionNumber
	ELSE IF @BOPNumber = 12 
		SELECT BOP_Text12 FROM H_InstitutionProfile WHERE Code = @InstitutionNumber
	ELSE IF @BOPNumber = 13 
		SELECT BOP_Text13 FROM H_InstitutionProfile WHERE Code = @InstitutionNumber
	ELSE IF @BOPNumber = 14 
		SELECT BOP_Text14 FROM H_InstitutionProfile WHERE Code = @InstitutionNumber
	ELSE IF @BOPNumber = 15 
		SELECT BOP_Text15 FROM H_InstitutionProfile WHERE Code = @InstitutionNumber
	ELSE IF @BOPNumber = 16 
		SELECT BOP_Text16 FROM H_InstitutionProfile WHERE Code = @InstitutionNumber
	ELSE IF @BOPNumber = 17 
		SELECT BOP_Text17 FROM H_InstitutionProfile WHERE Code = @InstitutionNumber
	ELSE IF @BOPNumber = 18
		SELECT BOP_Text18 FROM H_InstitutionProfile WHERE Code = @InstitutionNumber
	ELSE IF @BOPNumber = 19 
		SELECT BOP_Text19 FROM H_InstitutionProfile WHERE Code = @InstitutionNumber




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- Called by the Billing Error to get a Encounters AbstractID based on the Bill Number
CREATE     PROCEDURE [P_GetBillingAbstract]
	@BillNum as varchar(8)
AS 
	DECLARE @RecID AS INTEGER
	SELECT @RecID = AbstractID FROM CR_Demographic WHERE BillNumber =  @BillNum
	RETURN @RecID



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- Called by the Chart Requester to get a borrower's default Location..
CREATE     PROCEDURE [P_GetBorrowerLocation]
	@BorrowID AS INTEGER	
AS 

	DECLARE @Loc AS INTEGER
	SELECT @Loc = PullLocation FROM LoanLU_Borrower WHERE Code =  @BorrowID
	RETURN @Loc




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- Called by CCRS if a record is Deleted or Recovered we will need to reset the IsCurrent flag
CREATE     PROCEDURE [P_GetCCRSIsCurrentList]
	@AbstractID AS INT
AS 

	DECLARE @LinkID AS INT
	SELECT @LinkID = LinkID FROM CRS_Demographic WHERE AbstractID = @AbstractID

	SELECT AbstractID, AA8, AdmitDate AS [VisitDate]
	FROM CRS_Demographic 
	WHERE LinkID = @LinkID AND IsDeleted = 2 AND AA8 = 14501
	UNION 
	SELECT AbstractID, AA8, Z7 AS [VisitDate]
	FROM CRS_Demographic
	WHERE LinkID = @LinkID AND IsDeleted = 2 AND AA8 = 14500
	UNION 
	SELECT AbstractID, AA8, A3 AS [VisitDate]
	FROM CRS_Demographic
	WHERE LinkID = @LinkID AND IsDeleted = 2 AND (AA8 = 14502 OR AA8 = 14503 OR AA8 = 14504 OR AA8 = 14505 OR AA8 = 14506 OR AA8 = 14511)
	UNION 
	SELECT AbstractID, AA8, DischargeDate AS [VisitDate]
	FROM CRS_Demographic
	WHERE LinkID = @LinkID AND IsDeleted = 2 AND (AA8 = 14507 OR AA8 = 14508 OR AA8 = 14509)
	UNION 
	SELECT AbstractID, AA8, AdmitDate AS [VisitDate]    --2.x-00066 Need to use AdmitDate instead of AB1b
	FROM CRS_Demographic
	WHERE LinkID = @LinkID AND IsDeleted = 2 AND AA8 = 14510
	ORDER BY [VisitDate] DESC, AA8 DESC
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE  PROCEDURE [P_GetCIHIPeriodByDate]
	@GetSystem as int,
	@CIHIDate as datetime
AS 
	IF @GetSystem = 1 
		SELECT Code FROM LU_BatchPeriod WHERE (CIHIDateFrom <= @CIHIDate AND @CIHIDate <= CIHIDateTo) AND (ValidFrom <= @CIHIDate AND @CIHIDate <= ValidTo)
	ELSE
		SELECT CIHIValue FROM LU_BatchPeriod WHERE (CIHIDateFrom <= @CIHIDate AND @CIHIDate <= CIHIDateTo) AND (ValidFrom <= @CIHIDate AND @CIHIDate <= ValidTo)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE  PROCEDURE [P_GetCIHIPeriodDate]
	@IsDateFrom as bit, 
	@Period as varchar(2),
	@UseDate as datetime
AS 

	IF @IsDateFrom = 0 
		SELECT CIHIDateTo 
		FROM LU_BatchPeriod
		WHERE DisplayCode = @Period AND (([ValidFrom] <= @UseDate) AND (@UseDate <= [ValidTo]))
	ELSE
		SELECT CIHIDateFrom 
		FROM LU_BatchPeriod
		WHERE DisplayCode = @Period AND (([ValidFrom] <= @UseDate) AND (@UseDate <= [ValidTo]))



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE  PROCEDURE [P_GetCIHIValue]
	@AppID as int, 
	@FieldKey as int,
	@SearchCode as int
AS 

--NO Longer used... just commenting out to make sure

--	DECLARE @SearchTable AS VarChar(100)
	
--	SELECT @SearchTable = 
--	(
		SELECT LookUpTable 
		FROM U_UsersFields 
		WHERE AppID = @AppID 
		AND FieldID = @FieldKey
--	)
	
--	EXECUTE P_LookUpMain @SearchTable, '', @SearchCode, ''



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




--This will be used to get HCN to create the OBEC file.
CREATE    PROCEDURE [P_GetClinicOBECClaims]
	@ProviderNumber as int
AS 
	SELECT   HealthCareNumber AS [HCN], HCNVersion AS [HCNV]
	FROM dbo.CR_Demographic INNER JOIN dbo.CR_Visit ON dbo.CR_Demographic.AbstractID = dbo.CR_Visit.AbstractID
	WHERE IsDeleted = 2 AND IsSubmited <> 1 AND ProviderNumber = @ProviderNumber
	
RETURN 0



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO







CREATE     PROCEDURE [P_GetCorrectionCount]
	@BatchYear 	[int],
	@BatchPeriod 	[int],
	@HospID		[int] = 0
AS 

	SELECT AbstractID FROM AB_Abstract WHERE IsCorrected = 2 AND BatchYear = @BatchYear AND BatchPeriod = @BatchPeriod
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
	RETURN @@RowCount





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- Called by the Purge to make sure that the Record isn't flagged for Correction.
CREATE PROCEDURE [P_GetCorrectionStatus]
	@AbstractID [int]
AS 
--NP - 00125
SELECT IsCorrected = (case when IsCorrectLevel1 = 2 and caretype = 5 then IsCorrectLevel1 else IsCorrected end)
FROM AB_Abstract 
WHERE AbstractID =  @AbstractID




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO







CREATE    PROCEDURE [P_GetCPIDeathDate]
	@ChartNumber AS VARCHAR(10),
	@HospID as int = 0
AS 

	SELECT DeathDate FROM CM_CPI WHERE ChartNumber = @ChartNumber AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE    PROCEDURE [P_GetCPIDeathIndicator]
	@ChartNumber AS VARCHAR(10),
	@HospID as int = 0
AS 

	SELECT DeathIndicator FROM CM_CPI WHERE ChartNumber = @ChartNumber AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- Called by the Chart Locator to get the Current Location Code to make sure that the User is not sending a volume to the same place.
Create PROCEDURE [P_GetCurrentLocation]
	@VolumeID AS INTEGER,	
	@CurrentLocation as VarChar(255) Output
AS 

	Set @CurrentLocation = (SELECT Top 1 isnull(dbo.LoanLU_Location.DisplayCode, '') AS CurrentLocation
	FROM dbo.CM_CPI_Volume LEFT OUTER JOIN
	dbo.LoanLU_Location ON dbo.CM_CPI_Volume.CLCurrentLocation = dbo.LoanLU_Location.Code
	WHERE dbo.CM_CPI_Volume.VolumeID = @VolumeID)

	If @CurrentLocation is null
		Set @CurrentLocation = ''


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- Called by the Chart Locator to get the Current Location Code to make sure that the User is not sending a volume to the same place.
CREATE     PROCEDURE [P_GetCurrentLocationCode]
	@VolumeID AS INTEGER	
AS 

	DECLARE @LocCode AS INTEGER
	SELECT @LocCode = CLCurrentLocation FROM CM_CPI_Volume WHERE VolumeID =  @VolumeID
	RETURN @LocCode




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



--ticket 10222, Add log from Inpatient Separate file form
Create Procedure [P_GetDADAbstractCount](
    @InstNoCIHI   varchar(5),
    @BatchYear    int,
    @BatchPeriod  int,
    @Count        int output)
as

declare 
    @DateFr varchar(10),
    @DateTo varchar(10),
    @InstNoCode int,
    @BatPerCIHI varchar(2)
    
set @BatPerCIHI = right('00' + cast(@BatchPeriod as varchar(2)), 2)

set @DateFr = cast( cast(@BatchYear as varchar(4)) + '/04/01' as datetime)
set @DateTo = cast( cast(@BatchYear + 1 as varchar(4)) + '/03/31' as datetime)


if exists ( select * from H_HospitalProfile where ProvinceNumber = 14 ) begin
    set @BatchPeriod = (select top 1 code from LU_BatchPeriod 
            where CIHIValue = @BatPerCIHI 
                and CIHIDateFrom between @DateFr and @DateTo
                and CIHIDateTo between @DateFr and @DateTo)
end

select 
    @DateFr = dbo.SUF_GetPeriodDateFr( @BatchYear, @BatchPeriod ), 
    @DateTo = dbo.SUF_GetPeriodDateTo( @BatchYear, @BatchPeriod )

set @InstNoCode = (select top 1 code from H_InstitutionProfile 
                   where CIHIValue = @InstNoCIHI 
                       and associationid in (1, 2)
                       and @DateFr between ValidFrom and ValidTo
                       and @DateTo between ValidFrom and ValidTo )


set @Count = isnull((select count(*) from AB_Abstract 
        where institutionnumber = @InstNoCode
            and dischargedate between @DateFr and @DateTo
            and isnull(isdeleted, 0) <> 1 ), 0)

return 0



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE procedure [P_GetDeficiencyCodeFromTemplate]
    @Code int,
    @DefCode   int output
as
    set @DefCode = isnull((select top 1 DefCode
        from LU_TranscriptDocument
        where Code = @Code), 0)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--PR-01667 to add hospital link
-- Called by the Chart Deficiency to get the most recent Abstrat Visit for a given chart.
CREATE  PROCEDURE [P_GetDeficiencyVisit]
	@PatientID AS INTEGER,
    @HospID as int	
AS 

	DECLARE @AbstID AS INTEGER

	SELECT TOP 1 @AbstID = AB_Main.UniversalID 
	FROM AB_MAIN    -- AB_Abstract 
	INNER JOIN CM_CPI ON AB_MAIN.ChartNumber = CM_CPI.ChartNumber
	WHERE (CM_CPI.PatientID = @PatientID) and AppType <> 0
    and (ISNULL(AB_MAIN.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(AB_MAIN.HospitalID, 0) end)
	ORDER BY ISNULL(AB_MAIN.DischargeDate, GETDATE()) DESC, AB_MAIN.AdmitDate Desc
--11641 
-- 	SELECT TOP 1 @AbstID = AB_Abstract.AbstractID 
-- 	FROM AB_Abstract 
-- 	INNER JOIN CM_CPI ON AB_Abstract.ChartNumber = CM_CPI.ChartNumber
-- 	WHERE (CM_CPI.PatientID = @PatientID) 
-- 	ORDER BY ISNULL(AB_Abstract.DischargeDate, GETDATE()) DESC

	RETURN @AbstID



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Called by the Purge to make sure that the Record isn't flagged for Deletion Type 3.
CREATE     PROCEDURE [P_GetDeleteStatus]
	@AbstractID [int]
AS 
--2.x-0150 Modify to allow purge the merge chart deletion issue
declare @Institution int
declare @CareType int
declare @IsLevel3 int
declare @SubmissionLevel3 int
declare @SubmissionLevel1 int
declare @IsDeleted int
declare @VisitDate datetime
declare @From datetime
declare @End datetime

set @IsLevel3 = 0
select top 1 @CareType = caretype, @Institution = InstitutionNumber, 
    @VisitDate = (case when caretype = 5 then admitdate else isnull(DischargeDate, Admitdate) end),
    @SubmissionLevel3 = IsSubmited, @SubmissionLevel1 = IsSubmitLevel1, @IsDeleted = IsDeleted
from AB_Abstract 
WHERE AbstractID =  @AbstractID

if @CareType = 5 and @SubmissionLevel3 = 2 and @SubmissionLevel1 = 1 and @IsDeleted = 3
begin
    set @From = left(convert(varchar(50), @VisitDate, 111), 8) + '01'
    set @End = Dateadd(day, -1, dateadd(month, 1, @From))
    if exists (select top 1 abstractid from ab_abstract where admitdate between @From and @End
                and InstitutionNumber = @Institution
                and IsSubmited = 1)
        set @IsDeleted = 1
end

select @IsDeleted

--SELECT IsDeleted 
--FROM AB_Abstract 
--WHERE AbstractID =  @AbstractID



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [P_GetFacilityFileInformation](
    @Inst varchar(10),     @AppID int,
    @Year int,          @FileName varchar(250)
)
as
----select @Inst
--    if isnull(@FileName, '') = ''
--        select BatchYear, max(SequenceNumber) as MaxSequence
--        from dbo.SU_ExecProperties  --_Facility
--        where InstNoCIHI = @Inst and AppID = @AppID and GroupID = 0
--            and (@Year = 0 or BatchYear = @Year)
--        group by BatchYear
--    else
        select *
        from dbo.SU_ExecProperties --_Facility
        where InstNoCIHI = @Inst and AppID = @AppID and GroupID = 0
            and NameOfFile like '%' + @FileName
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This returns the Field's Audit information.
CREATE      PROCEDURE [P_GetFieldAudit]
	@AppID as int,
	@RecordID as int,
	@FieldID as int,
	@OccNo as int,
	@Extra as varchar(255), --EN - 00553
    @CurrentUserID as int   --0897
AS 
if(@AppID = 1200 or @AppID = 1201)
    select
	    (select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_UpdateAudit.HospitalID, 0)) as [Hosp ID],
	    (select top 1 DisplayCode from U_Users where Code = Coder) as [Coder],
	    convert(varchar(10), Updated, 111) + ' ' + convert(varchar(5), Updated, 14) as [Updated], 
	    OldValue as [Old Value],
	    NewValue as [New Value]
    from AB_UpdateAudit
    where AbstractID = @RecordID and AppID = @AppID and FieldID = @FieldID and Occurrence = @OccNo
    and (isnull(Extra, '') = '' or (Extra like @Extra + '%' and (Extra like '% - Save All' or Extra like '% - ' + cast(@CurrentUserID as varchar(10))))) --0897 -   Save All - Audit Trail
    --and isnull(Extra, '') = @Extra ----EN - 00553
    --order by Updated desc
    order by [Hosp ID], Updated desc
else
    select
	    (select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(AB_UpdateAudit.HospitalID, 0)) as [Hosp ID],
	    (select top 1 DisplayCode from U_Users where Code = Coder) as [Coder],
	    convert(varchar(10), Updated, 111) + ' ' + convert(varchar(5), Updated, 14) as [Updated], 
	    OldValue as [Old Value],
	    NewValue as [New Value]
    from AB_UpdateAudit
    where AbstractID = @RecordID and AppID = @AppID and FieldID = @FieldID and Occurrence = @OccNo
        and isnull(Extra, '') = @Extra ----EN - 00553
    --order by Updated desc
    order by [Hosp ID], Updated desc
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [P_GetFieldByKey]
    @UserID	int = 0,
    @FKey	int = 0
AS 

SELECT 	FieldSize, 
		LookUpTable, 
		FieldEnabled, 
		FieldVisible, 
		Header_CIHI_English, 
		DefaultValue, 
		Header_User,  
		Needed
FROM 		U_UsersFields 
WHERE 	U_UsersFields.FieldID = @FKey
AND 		U_UsersFields.UserID = @UserID




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--EN-00183
CREATE PROCEDURE [P_GetHospitalDisplayCode]
	@HospitalID as int,
	@HospitalDisplayCode as varchar(20) output
AS 
    set @HospitalDisplayCode = (select top 1 DisplayCode from H_HospitalProfile where Code = @HospitalID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE PROCEDURE [P_GetInterfaceErrors]
AS 

SELECT 	*
FROM 		BI_Audit




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [P_GetLinkVolume]
	@VolumeID AS INTEGER,
    @LinkVolume AS INTEGER output,
    @ChartNumber varchar(10) output,
    @VolumeNumber varchar(8) output,
    @PermLocation varchar(20) output,
    @CurLocation varchar(20) output	
AS 

	SELECT top 1 
        @LinkVolume = isnull(V.CLLinkedVolume, 0),
        @ChartNumber = isnull(C.ChartNumber, ''),
        @VolumeNumber = isnull(Link.VolumeNumber, ''),
        @PermLocation = isnull(P.DisplayCode, ''),
        @CurLocation = isnull(L.DisplayCode, '')	        
    FROM CM_CPI_Volume V 
        inner join CM_CPI C on V.PatientID = C.PatientID
        left join CM_CPI_Volume Link on v.CLLinkedVolume = Link.VolumeID
        left join LoanLU_Location P on Link.PermLocation = P.Code
        left join LoanLU_Location L on Link.CLCurrentLocation = L.Code
    WHERE V.VolumeID =  @VolumeID
	RETURN @@rowcount


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- Called by the Chart Requester to calculate the expected date of return.
CREATE     PROCEDURE [P_GetLocationLoanDays]
	@LocationID AS INTEGER	
AS 

	DECLARE @LoanDays AS INTEGER
	SELECT @LoanDays = LoanDays FROM LoanLU_Location WHERE Code =  @LocationID
	RETURN @LoanDays




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO






-- Called by the Chart Requester to calculate the expected date of return.
create PROCEDURE [P_GetLocationTypeDays]
	@LocationID AS INTEGER	
AS 

	DECLARE @LoanDays AS INTEGER
	SELECT @LoanDays = LoanDays FROM LoanLU_LocationType WHERE Code =  @LocationID
	RETURN @LoanDays


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- Called by the CCRS
CREATE     PROCEDURE [P_GetNextCCRSUniqueID]
	@InstitutionNumber AS VarChar(5),
	--@AdmitDate AS Varchar(8),
	@UniqueID AS VarChar(20) OUTPUT
AS 

-- declare @UDate as varchar(8)
-- set @UDate = convert(varchar(8), getdate(), 112)
-- 
-- select @UniqueID = @InstitutionNumber + @UDate +
-- 	replace(space(7-len(isnull(convert(varchar(7), max(substring(AA1, 14, len(AA1) - 13)) + 1), 0))), ' ', '0') + 
-- 	convert(varchar(7), isnull(max(substring(AA1, 14, len(AA1) - 13)), 0) + 1) 
-- from CRS_Demographic 
-- where left(AA1, 5) = @InstitutionNumber AND isnumeric(isnull(AA1, 0)) = 1

declare @UDate as varchar(8)

declare @HUID as int
declare @AUID as int
declare @UID as int 

set @UDate = convert(varchar(8), getdate(), 112)

set @HUID = (select top 1 isnull(StartUniqueCCRS, 0) from H_HospitalProfile) + 1 
set @AUID = (select convert(int, isnull(max(substring(AA1, 14, len(AA1) - 13)), 0) + 1) from CRS_Demographic where isnumeric(isnull(AA1, 0)) = 1)

-- If the Start Number is Greater than the Max, use it instead.
set @UID = @HUID
if isnull(@AUID, -1)  > isnull(@HUID, -1) set @UID = @AUID
if isnull(@UID, -1) < 0 set @UID = 1

set @UniqueID = @InstitutionNumber + @UDate + replace(space(7-len(convert(varchar(7), @UID))), ' ', '0') + convert(varchar(7), @UID) 
update [H_HospitalProfile] set [StartUniqueCCRS] = @UID 

return 0

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO






-- Called by the Amcare when a same Encounter is being Cloned
CREATE       PROCEDURE [P_GetNextEncounterSequence]
	 @ChartNumber 		[varchar](10),
	 @EncounterNumber 	[varchar](20),
	 @HospID		[int] = 0
AS 
	DECLARE @EncSeq as int
	SELECT @EncSeq = (SELECT ISNULL(MAX([EncounterSequence]), 1) FROM AB_ABSTRACT 
	WHERE [ChartNumber] = @ChartNumber AND [EncounterNumber] = @EncounterNumber
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)) + 1 
	
	RETURN @EncSeq





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--13008
CREATE  Procedure [P_GetNextPullListID]
    @PullDate   datetime,
    @Location   varchar(20),
    @Borrower   varchar(20),
    @PullFormat int,
    @PullListID varchar(50) output
as

declare @Now        varchar(10)
declare @Seq        int

set @PullListID = ''

if @PullFormat = 1     --Date + Sequence
begin
    set @Now = replace(replace(convert(varchar(10), getdate(), 111), '/', ''), '-', '')
    
    set @Seq = 1
    while(@Seq < 10000)
    begin
        set @PullListID = @Now + right('0000' + cast(@Seq as varchar(10)), 4)
        if not exists (select * from dbo.CL_PullList where PullListID = @PullListID)
            break
        set @Seq = @Seq + 1
    end
    
    if @Seq >= 10000 set  @PullListID = ''
end
else if @PullFormat = 2 and isnull(@Location, '') <> '' --Date + Loc + Borrower
begin
    if @PullDate is null set @PullDate = getdate()
    set @PullListID = replace(replace(replace(convert(varchar(10), @PullDate, 111), '/', ''), '-', ''), '-', '') + isnull(@Location, '') + isnull(@Borrower, '')
end
else if @PullFormat = 3 and isnull(@Location, '') <> '' --Date + Loc 
begin
    if @PullDate is null set @PullDate = getdate()
    set @PullListID = replace(replace(convert(varchar(10), @PullDate, 111), '/', ''), '-', '') + @Location
end
--Disable by Judy 13426 
-- else if @PullFormat = 4 and isnull(@Borrower, '') <> '' --Date + Borrower
-- begin
--     if @PullDate is null set @PullDate = getdate()
--     set @PullListID = replace(replace(convert(varchar(10), @PullDate, 111), '/', ''), '-', '') + @Borrower
-- end        
-- else if @PullFormat = 5    --Loc + Borrower + Date
-- begin
--     if @PullDate is null set @PullDate = getdate()
--     set @PullListID = isnull(@Location, '') + isnull(@Borrower, '') + replace(replace(replace(convert(varchar(10), @PullDate, 111), '/', ''), '-', ''), '-', '') 
-- end
-- else if @PullFormat = 6 and isnull(@Location, '') <> ''    --Loc + Date
-- begin
--     if @PullDate is null set @PullDate = getdate()
--     set @PullListID = isnull(@Location, '') + replace(replace(replace(convert(varchar(10), @PullDate, 111), '/', ''), '-', ''), '-', '') 
-- end
-- else if @PullFormat = 7 and isnull(@Borrower, '') <> ''    --Borrower + Date
-- begin
--     if @PullDate is null set @PullDate = getdate()
--     set @PullListID = isnull(@Borrower, '') + replace(replace(replace(convert(varchar(10), @PullDate, 111), '/', ''), '-', ''), '-', '') 
-- end



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Called by the ROI if there is not a Request ID entered at the time of Saving
CREATE PROCEDURE [P_GetNextRequestID]
	@RequestYear AS VarChar(4),
	@RequestID AS VarChar(15) OUTPUT
AS 
--PR - 05159 
--SELECT @RequestID = @RequestYear + 
--	REPLACE(SPACE(10-LEN(ISNULL(CONVERT(VARCHAR(10), MAX(SUBSTRING(RequestNumber, 5, LEN(RequestNumber) - 4)) + 1), 0))), ' ', '0') + 
--	CONVERT(VARCHAR(10), ISNULL(MAX(SUBSTRING(RequestNumber, 5, LEN(RequestNumber) - 4)), 0) + 1) 
--FROM ROI_Main 
--WHERE LEFT(RequestNumber, 4) = @RequestYear AND ISNUMERIC(ISNULL(RequestNumber, 0)) = 1
declare @NewID bigint
declare @Year int
if isnumeric(@RequestYear) = 1
begin
    set @Year = cast(@RequestYear as int)
    begin transaction RequestID
    set @NewID = @Year * 10000000000 + 1
    if not exists (select RequestNumber from dbo.ROI_RequestID where RequestYear = @Year)
    begin
        insert into dbo.ROI_RequestID(RequestYear, RequestNumber) values(@Year, @NewID)
        set @RequestID = cast(@NewID as varchar(15))
    end
    else
    begin
        update dbo.ROI_RequestID set RequestNumber = RequestNumber + 1 where RequestYear = @Year 
        set @NewID = (select RequestNumber from dbo.ROI_RequestID where RequestYear = @Year)
    end
    commit transaction RequestID
    set @RequestID = cast(@NewID as varchar(15))
end
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO


-- Ticket 12580
CREATE PROCEDURE [P_GetNextVolumeID]	
	@RecordID as int, @VolumeNumber AS varchar(8) output
AS 
Declare @i int

set @VolumeNumber = (select max(ltrim(rtrim(VolumeNumber))) from CM_CPI_Volume 
    where PatientID = @RecordID and isnumeric(ltrim(rtrim(VolumeNumber))) = 1)

if @VolumeNumber is null
    set @VolumeNumber = '  000001'
else
begin
    set @i = cast( @VolumeNumber as int) + 1
    set @VolumeNumber = cast(@i as varchar(10))
    set @VolumeNumber = ( case when len(@VolumeNumber) >= 8 then right(@VolumeNumber, 8)
                               when len(@VolumeNumber) = 7 then ' ' + @VolumeNumber
                               else '  ' + right('00000' + @VolumeNumber, 6)
                          end)   
end



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Called by OMHRS if a record is Deleted or Recovered we will need to reset the IsCurrent flag
CREATE PROCEDURE [P_GetOMHRSIsCurrentList]
	@AbstractID AS INT
AS 

	declare @LinkID as int
	select @LinkID = LinkID from OMHRS_SecAA where AbstractID = @AbstractID

	select AA.AbstractID, Z1, A1 
    from OMHRS_SecAA AA 
    inner join OMHRS_SecA A on AA.AbstractID = A.AbstractID 
    inner join OMHRS_RecInfo R ON AA.AbstractID = R.AbstractID
    where Z1 <> 200378
    and LinkID = @LinkID and IsDeleted = 2 
	order by [A1] desc, (case when z1 = 200375 then 200379 else [Z1] end) desc
    --PR - 05238 I guess. The iscurrent is not set correctly. change status z1 = 200376 > discharge 200375 

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO






-- Called by the CPI if there is preloaded Chart Number in the session object. It will
-- call this to retieve the Patient ID in order to auto-load the Chart Management Mods.
CREATE       PROCEDURE [P_GetPatientID]
	@SearchString as VarChar(50),
	@HospID as int = 0
AS 

SELECT PatientID FROM dbo.CM_CPI WHERE ChartNumber =   @SearchString AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE  PROCEDURE [P_GetPermanentLocation]
	@Volume as int,
	@PermLocation as VarChar(255) Output
AS
	Set @PermLocation = (SELECT Top 1 isnull(dbo.LoanLU_Location.DisplayCode, '') + ' - ' + isnull(dbo.LoanLU_Location.UserDescription, '') AS PreviousLocation
	FROM dbo.CM_CPI_Volume LEFT OUTER JOIN
	dbo.LoanLU_Location ON dbo.CM_CPI_Volume.PermLocation = dbo.LoanLU_Location.Code
	WHERE dbo.CM_CPI_Volume.VolumeID = @Volume)

	If @PermLocation is null
		Set @PermLocation = ''


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




--EN-00183
CREATE   PROCEDURE [P_GetPreviousLocation]
	@Volume as int,
	@PrevLocation as VarChar(255) Output
AS
-- 	Set @PrevLocation = (SELECT Top 1 dbo.LoanLU_Location.UserDescription AS PreviousLocation 
-- 	FROM dbo.CL_Activity LEFT OUTER JOIN
-- 	dbo.LoanLU_Location ON dbo.CL_Activity.ActivityPrevLocation = dbo.LoanLU_Location.Code
-- 	WHERE (dbo.CL_Activity.VolumeID = @Volume) and ActivityType <> 4
-- 	ORDER BY dbo.CL_Activity.ActivityDateOut DESC, 
--              dbo.CL_Activity.ActivityTimeOut DESC,
--              dbo.CL_Activity.CLActivityID Desc)
	Set @PrevLocation = (SELECT Top 1 UserDescription AS PreviousLocation 
        	FROM dbo.LoanLU_Location l 
                inner join CM_CPI_Volume v on v.CLPreviousLocation = l.code
            WHERE VolumeID = @Volume)

	If @Prevlocation is null
		Set @PrevLocation = ''





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE PROCEDURE [P_GetPreviousTransaction]
	@Volume  int
AS
    declare @Type  int 
	SELECT Top 1  @Type = ActivityType
	FROM dbo.CL_Activity 
       -- LEFT OUTER JOIN dbo.LoanLU_Type ON dbo.CL_Activity.ActivityType = dbo.LoanLU_Type.Code
	WHERE (dbo.CL_Activity.VolumeID = @Volume) and ActivityType <> 4
	ORDER BY dbo.CL_Activity.ActivityDateOut DESC, 
             dbo.CL_Activity.ActivityTimeOut DESC, 
             dbo.CL_Activity.CLActivityID desc
	If @Type is null 
		Set @type = 0
    return( @type )




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- Called by the Scheduler to get the Default Interval for Appointments
CREATE     PROCEDURE [P_GetProvdAppntDuration]
	@ProviderID AS INTEGER,
	@DayCode AS INTEGER
AS 
	DECLARE @Dur AS INTEGER
	SELECT @Dur = IntervalLen FROM LLU_Provider_Schedule WHERE ProviderID =  @ProviderID AND SchedDay = @DayCode
	RETURN @Dur



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE procedure [P_GetProviderAuthent]
    @ProviderNumber int,
    @ProvdrAuthent  varchar(12) output
as
    set @ProvdrAuthent = isnull((select top 1 YN.CIHIValue
        from LU_Provider lu
            inner join LU_YesNoSystem YN 
            on Lu.ProvdrAuthent = YN.Code
        where LU.Code = @ProviderNumber), 0)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--EN-00183
CREATE  procedure [P_GetProviderDefDetailForTran]
    @ProviderNumber int,
    @CareType       int,
    @AbstractID     int,
    @DefCode        int,
    @Permission     int,
    @Found          varchar(12) output
as
    declare @DefCodeType varchar(100)
    set @Found = '0'
    if @Permission = '1'
    begin
        if exists (select top 1 *
            from Def_SlipMain 
                inner join Def_Activity 
--                    on Def_SlipMain.DefeciencyID = Def_Activity.HeaderDefID
                    on Def_SlipMain.DefID = Def_Activity.DefID
                inner join AB_Main on Def_SlipMain.DefAbstractID = AB_Main.UniversalID
                left join dbo.DefLU_DeficiencyType T on Def_Activity.DefCodeType = T.Code
            where Def_SlipMain.DefDrNumber = @ProviderNumber 
                and Def_Activity.DefCode = @DefCode
                and AB_Main.AppType = @CareType 
                and AB_Main.AbstractID = @AbstractID
                and Def_Activity.DefStatus not in (8, 11))
            set @Found = '1'
    end
    else
    begin
        if not exists (select top 1 *
            from Def_SlipMain 
                inner join Def_Activity 
--                    on Def_SlipMain.DefeciencyID = Def_Activity.HeaderDefID
                    on Def_SlipMain.DefID = Def_Activity.DefID
                inner join AB_Main on Def_SlipMain.DefAbstractID = AB_Main.UniversalID
                inner join dbo.DefLU_DeficiencyType T on Def_Activity.DefCodeType = T.Code
            where Def_SlipMain.DefDrNumber = @ProviderNumber 
                and Def_Activity.DefCode = @DefCode
                and AB_Main.AppType = @CareType 
                and AB_Main.AbstractID = @AbstractID
                and ((Def_Activity.DefStatus not in (8, 11) and T.DisplayCode = 'S') or Def_Activity.DefStatus in (8) ))
            set @Found = '1'
   end



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE   procedure [P_GetProviderDeficiencyHeader]
    @ProviderNumber int,
    @CareType       int,
    @AbstractID     int,
    @DefeciencyID   int output
as
    set @DefeciencyID = isnull((select top 1 Def_SlipMain.DefID    --DefeciencyID
        from Def_SlipMain 
            inner join AB_Main on Def_SlipMain.DefAbstractID = AB_Main.UniversalID
        where Def_SlipMain.DefDrNumber = @ProviderNumber 
            and AB_Main.AppType = @CareType 
            and AB_Main.AbstractID = @AbstractID
            and Def_SlipMain.DefMainStatus <> 11), 0)




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



-- Ticket: 9043
CREATE   PROCEDURE [P_GetPullListLoanNotes]
-- 13004
    @PullID int,
--    @PullListID as varchar(20),
--	@VolumeID AS int,
--    @HospID as int,
    @LoanNotes as varchar(250) output
AS 

	SELECT top 1 @LoanNotes = LoanNote 
    FROM CL_PullList 
    where PullID = @PullID
--     WHERE PullListID = @PullListID and VolumeID =  @VolumeID
--     AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
    if @LoanNotes is null set @LoanNotes = ''

	RETURN 0






GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



Create PROCEDURE [P_GetRequestLocation]
	@ClActivityID as int,
	@RequestLocation as varchar(255) Output
AS
	Set @RequestLocation = (select top 1 L.UserDescription
	FROM dbo.CL_Activity A inner join LoanLU_Location L 
        on A.ActivityLocation = L.code
	WHERE CLActivityID = @ClActivityID)

	If @RequestLocation is null
		Set @RequestLocation = ''



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



Create PROCEDURE [P_GetRequestLocationCode]
	@ClActivityID as int,
	@RequestLocation as int Output
AS
	Set @RequestLocation = (select top 1 ActivityLocation
	FROM dbo.CL_Activity
	WHERE CLActivityID = @ClActivityID)

	If @RequestLocation is null
		Set @RequestLocation = 0



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE  PROCEDURE [P_GetROIReportPath]
	@Code AS INT
AS 
	SELECT ReportPath FROM LU_ROI_AuthorizationType WHERE Code = @Code



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- This is called by the Ctrl File - Details.
CREATE PROCEDURE [P_GetSingleDisplayField]
	@AppID	int = 0,
    	@UserID	int = 0,
 	@FieldID	int = 0
AS 

SELECT U_Fields.*, 
AppID, RoleID, UserID, SortOrder, GroupID, MultipleIndex, MandatoryStatus, Needed, FieldSize, DataType, SubAppID, 
LookUpTable = (case when isnull(LookUpTable, '') <> '' then LookUpTable 
                    else (case when DataType = 60 then 'ICD_DiagFile10'
                               when DataType = 61 then 'ICD_ProcFile10'
                          end)
               end), --PR - 04066
CIHI_ID, Header_CIHI_English, Header_CIHI_French, Header_CIHI_Spanish, Header_User, FieldEnabled, FieldVisible, DefaultValue, ParamProcID, ParamOrder, ParamName, ParamDataType, ParamSize, NeedForUserDef, MainDataType, UNoteCode
--U_UsersFields.*
FROM U_Fields, U_UsersFields 
WHERE U_UsersFields.FieldID = U_Fields.FieldID 
AND U_UsersFields.AppID = @AppID
AND U_UsersFields.UserID = @UserID
AND U_UsersFields.FieldID = @FieldID




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- Called by the Transcription to Get the Template File Name
CREATE     PROCEDURE [P_GetTranscriptTemplateName]
	@CodeID AS INTEGER,
	@FileName AS varchar(255) OUTPUT
AS 
	SELECT @FileName = TemplatePath FROM LU_TranscriptDocument WHERE Code =  @CodeID



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This returns the User Info. It's purpose now is to give Ctrl File selected User Submit permission, 
-- but it could have other applications later on...
CREATE   PROCEDURE [P_GetUserProperties]
	@UserID as INT
AS 

	SELECT * FROM U_Users WHERE Code = @UserID




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


-- Called by the Chart Requester to get the Permanent Location for Chart Returns.
CREATE PROCEDURE [P_GetVolumePermLocation]
	@VolumeID AS INTEGER,
	@LocType AS INTEGER
AS 

	DECLARE @Loc AS INTEGER
	IF @LocType = 0 
		SELECT @Loc = PermLocation FROM CM_CPI_Volume WHERE VolumeID = @VolumeID
	ELSE		
		SELECT @Loc = CLPreviousLocation FROM CM_CPI_Volume WHERE VolumeID = @VolumeID
        if isnull(@Loc, 0) = 0
    		SELECT TOP 1 @Loc = ActivityPrevLocation FROM CL_Activity 
            WHERE VolumeID = @VolumeID and ActivityType <> 4
            ORDER BY ActivityDateOut DESC, ActivityTimeOut DESC, CLActivityID DESC
	RETURN isnull(@Loc, 0)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



-- This is a Record history of Chart Locator Records.
CREATE PROCEDURE [P_HistoryActivity]
	@ActID AS INTEGER
AS 

	SELECT dbo.U_Users.UserDescription AS Coder, 
		CONVERT(VarChar(11), dbo.CL_ActivityUpdateHistory.Updated, 111) + ' ' + 		
		CONVERT(Varchar(5), dbo.CL_ActivityUpdateHistory.Updated, 14) AS [Updated]
	FROM dbo.CL_ActivityUpdateHistory 
	LEFT OUTER JOIN dbo.U_Users 
	ON dbo.CL_ActivityUpdateHistory.Coder = dbo.U_Users.Code 
	WHERE (dbo.CL_ActivityUpdateHistory.CLActivityID =  @ActID) and 
        CL_ActivityUpdateHistory.UpdateType in ('Saved')
	ORDER BY dbo.CL_ActivityUpdateHistory.Updated DESC

	RETURN 0





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is a Record history of Cancer Care Records.
CREATE PROCEDURE [P_HistoryCancerCare]
	@AbstractID AS INT,
	@DefaultCount as int output 
AS 

set @DefaultCount = isnull((select count(*) from CC_UpdateHistory where AbstractID = @AbstractID AND UpdateType = 'Saved' and Coder not in (77777, 88888, 99999)), 0) 

select 
	(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID],
	U.UserDescription AS Coder, 
	convert(varchar(11), H.Updated, 111) + ' ' + convert(varchar(5), H.Updated, 14) as [Updated]
from CC_UpdateHistory H left outer join U_Users U on H.Coder = U.Code 
where (H.AbstractID =  @AbstractID) and (UpdateType = 'Saved' or UpdateType = 'Recovered')
order by H.Updated desc, [Hosp ID] 
--order by [Hosp ID], H.Updated desc    PR - 03781

return 0




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is a record history of Care Map Records.
CREATE     PROCEDURE [P_HistoryCareMap]
	@RecordID as int
AS 
select 
	(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID],
	U.UserDescription as Coder, 
	convert(varchar(11), Updated, 111) + ' ' +  convert(varchar(5), Updated, 14) as [Updated]
from CMV_UpdateHistory H left outer join U_Users U on H.Coder = U.Code 
where (RecordID = @RecordID) 
and (isnull(Updatetype, 'Saved') = 'Saved'  or Updatetype = 'Recovered')
order by H.Updated desc, [Hosp ID] 
--order by [Hosp ID], H.Updated desc    PR - 03781

return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is a Record history of CCRS Records.
CREATE PROCEDURE [P_HistoryCCRS]
	@AbstractID AS INT, 
	@DefaultCount as int output 
AS 

--PR - 05431
set @DefaultCount = isnull((select count(*) from CRS_UpdateHistory where AbstractID = @AbstractID AND UpdateType = 'Saved' and Coder not in (77777, 88888, 99999)), 0) 

select 
	(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID],
	U.UserDescription AS Coder, 
	convert(varchar(11), H.Updated, 111) + ' ' + convert(varchar(5), H.Updated, 14) as [Updated]
from CRS_UpdateHistory H left outer join U_Users U on H.Coder = U.Code 
where (H.AbstractID =  @AbstractID) and (UpdateType = 'Saved' or UpdateType = 'Recovered')
order by H.Updated desc, [Hosp ID] 
--order by [Hosp ID], H.Updated desc    PR - 03781

return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is a Record history of CJRR Records.
create PROCEDURE [P_HistoryCJRR]
	@RecordID as int,
	@DefaultCount as int output 	
AS 
--13281
set @DefaultCount = isnull((select count(*) from CJRR_UpdateHistory where RecordID = @RecordID and UpdateType = 'Saved' and Coder not in (77777, 88888, 99999)), 0) 

select 
	(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID],
	U.UserDescription as Coder, 
	convert(varchar(11), H.Updated, 111) + ' ' + convert(varchar(5), H.Updated, 14) as [Updated]
from CJRR_UpdateHistory H left outer join U_Users U on H.Coder = U.Code 
where H.RecordID =  @RecordID and (isnull(H.Updatetype, 'Saved') = 'Saved' or isnull(H.Updatetype, 'Saved') = 'Recovered')
order by H.Updated desc, [Hosp ID] 
--order by [Hosp ID], H.Updated desc    PR - 03781

return 0
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO




-- This is a Record history of Clinic Records.
CREATE   PROCEDURE [P_HistoryClinic]
	@AbstractID AS INT
AS 
	SELECT dbo.U_Users.UserDescription AS Coder, 
		CONVERT(VarChar(11), dbo.CR_UpdateHistory.Updated, 111) + ' ' + 		
		CONVERT(Varchar(5), dbo.CR_UpdateHistory.Updated, 14) AS [Updated]
	FROM dbo.CR_UpdateHistory 
	LEFT OUTER JOIN dbo.U_Users 
	ON dbo.CR_UpdateHistory.Coder = dbo.U_Users.Code 
	WHERE (dbo.CR_UpdateHistory.AbstractID =  @AbstractID) 
	ORDER BY dbo.CR_UpdateHistory.Updated DESC

	RETURN 0



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--EN-00183
-- This is a Record history of Chart Deficiency Records.
CREATE PROCEDURE [P_HistoryDef]
	@DefID AS INTEGER
AS 

select
	(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID],
	U.UserDescription as Coder, 
	convert(varchar(11), H.Updated, 111) + ' ' + convert(varchar(5), H.Updated, 14) AS [Updated]
from Def_UpdateHistory H left outer join U_Users U on H.Coder = U.Code 
--where (H.DefeciencyID = @DefID) 
where (H.DefID = @DefID) 
    and (UpdateType in ('Saved',  'Recovered', 'Transfer'))
order by H.Updated desc, [Hosp ID] 
--order by [Hosp ID], H.Updated desc    PR - 03781

return 0
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- This is the Abstracts Deficiencies.
CREATE   PROCEDURE [P_HistoryDeficiency]
	@AbstractID as Int,
	@Patientid as int = 0,
	@HospID	as int = 0 
AS 
	if isnull(@AbstractID, 0) = 0
		SELECT 
    --EN-00813
            DefID as [ ],
	    -- NP-00025
	   (select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(D.HospitalID, 0)) as [Hosp ID], 
            DefeciencyID AS [Def. ID],
			(SELECT DisplayCode FROM LU_Provider WHERE Code = DefDrNumber) AS [Provider], 
			(SELECT UserDescription FROM DefLU_DocColourCode WHERE Code = DefColour) AS [Colour],
			(SELECT DisplayCode FROM DefLU_ChartStatus WHERE Code = DefMainStatus) AS [Status]
		FROM Def_SlipMain D
		WHERE DefPatientID = @Patientid AND ISNULL(DefAbstractID, 0) = 0
		and (isnull(D.HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(D.HospitalID, 0) end) 
        --and DefMainStatus <> 8 
		ORDER BY DefeciencyID

	Else
		SELECT 
    --EN-00813
            DefID as [ ],
	   (select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(D.HospitalID, 0)) as [Hosp ID],
            DefeciencyID AS [Def. ID],
			(SELECT DisplayCode FROM LU_Provider WHERE Code = DefDrNumber) AS [Provider], 
			(SELECT UserDescription FROM DefLU_DocColourCode WHERE Code = DefColour) AS [Colour],
			(SELECT DisplayCode FROM DefLU_ChartStatus WHERE Code = DefMainStatus) AS [Status]
		FROM Def_SlipMain D
		WHERE DefAbstractID = @AbstractID
		and (isnull(D.HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(D.HospitalID, 0) end) 
        --and DefMainStatus <> 8 
		ORDER BY DefeciencyID





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This is a Record history of Look Up Maintenance Records.
CREATE   PROCEDURE [P_HistoryLookUp]
	@TableName as VarChar(50),
	@RecordID as VarChar(10)
AS 

	SELECT dbo.U_Users.UserDescription AS Coder, 
		CONVERT(VarChar(11), dbo.LLU_UpdateHistory.Updated, 111) + ' ' + 		
		CONVERT(Varchar(5), dbo.LLU_UpdateHistory.Updated, 14) AS [Updated]
	FROM dbo.LLU_UpdateHistory 
	LEFT OUTER JOIN dbo.U_Users 
	ON dbo.LLU_UpdateHistory.Coder = dbo.U_Users.Code 
	WHERE (dbo.LLU_UpdateHistory.TableName =  @TableName) AND (dbo.LLU_UpdateHistory.RecordID =  @RecordID) 
	ORDER BY dbo.LLU_UpdateHistory.Updated DESC

	RETURN 0




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is a Record history of Maintenance Records (Hosp, Inst, Prov, User).
CREATE PROCEDURE [P_HistoryMaint]
	@AppID as int,
	@RecordID as VarChar(10)
AS 

select 

	(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID],
	U.UserDescription as Coder, 
	convert(varchar(11), H.Updated, 111) + ' ' + convert(varchar(5), H.Updated, 14) as [Updated]
from H_UpdateHistory H left outer join U_Users U on H.Coder = U.Code 
where (H.AppID = @AppID) and (H.RecordID =  @RecordID) --and (isnull(H.Updatetype, 'Saved') = 'Saved' or isnull(H.Updatetype, 'Saved') = 'Recovered')
order by H.Updated desc, [Hosp ID] 
--order by [Hosp ID], H.Updated desc    PR - 03781

return 0
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- Amcare's Encounter Number Multi-Contact List
CREATE   PROCEDURE [P_HistoryMultiContact]
	@EncounterNumber AS VarChar(10)
AS 

	SELECT AbstractID, 
		ICDType AS [ICD], 
		(SELECT DisplayCode FROM LU_CareType WHERE Code = CareType) AS [Care],
		(SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #],
		CONVERT(VarChar(10), DischargeDate, 111) AS [Discharge Date], EncounterSequence as [EncNo]
	FROM AB_Abstract 
	WHERE (ChartNumber = N'' + @EncounterNumber + '' AND IsDeleted = 2) 
	ORDER BY DischargeDate DESC




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is a Record history of OMHRS Records.
CREATE PROCEDURE [P_HistoryOMHRS]
	@AbstractID as int,
	@DefaultCount as int output 	
AS 
--13281
set @DefaultCount = isnull((select count(*) from OMHRS_UpdateHistory where AbstractID = @AbstractID and UpdateType = 'Saved' and Coder not in (77777, 88888, 99999)), 0) 

select 
	(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID],
	U.UserDescription as Coder, 
	convert(varchar(11), H.Updated, 111) + ' ' + convert(varchar(5), H.Updated, 14) as [Updated]
from OMHRS_UpdateHistory H left outer join U_Users U on H.Coder = U.Code 
where H.AbstractID =  @AbstractID and (isnull(H.Updatetype, 'Saved') = 'Saved' or isnull(H.Updatetype, 'Saved') = 'Recovered')
order by H.Updated desc, [Hosp ID] 
--order by [Hosp ID], H.Updated desc    PR - 03781

return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is a record history of CPI Records.
CREATE PROCEDURE [P_HistoryPatient]
	@PatientID as varchar(10)
AS 

select 
	(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(U.HospitalID, 0)) as [Hosp ID],
	U.UserDescription as Coder, 
	convert(varchar(11), H.Updated, 111) + ' ' + convert(varchar(5), H.Updated, 14) AS [Updated]
from CM_UpdateHistory H left outer join U_Users U on H.Coder = U.Code 
where (H.PatientID = @PatientID) 
and (isnull(UpdateType, 'Saved') = 'Saved'  or UpdateType = 'Recovered')
order by H.Updated desc, [Hosp ID] 
--order by [Hosp ID], H.Updated desc    PR - 03781

return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_HistoryRecord] 
   @AbstractID as VarChar(10), 
   @DefaultCount as int output 
AS  
--set @DefaultCount = isnull((select count(*) from AB_UpdateHistory where AbstractID = @AbstractID AND UpdateType = 'Saved' and Coder not in (1, 77777, 88888, 99999)), 0) 
set @DefaultCount = isnull((select count(*) from AB_UpdateHistory where AbstractID = @AbstractID AND UpdateType = 'Saved' and Coder not in (77777, 88888, 99999)), 0)  --PR-01896 
 
select 
	(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID],
	U.UserDescription as Coder,  
	convert(varchar(11), H.Updated, 111) + ' ' + convert(varchar(5), H.Updated, 14) as [Updated] 
from AB_UpdateHistory H left outer join U_Users U on H.Coder = U.Code  
where (H.AbstractID =  @AbstractID) and (Updatetype = 'Saved'  or Updatetype = 'Recovered')
order by H.Updated desc , [Hosp ID]
--order by [Hosp ID], H.Updated desc --2.x-0212

--PR - 04630 Keep the original one
--set nocount on
--declare @HR table (
--	Coder int, 
--	Updated datetime, 
--	UpdateType varchar(10), 
--	HospitalID int
--)

--insert @HR(Coder, Updated, UpdateType, HospitalID)
--select Coder, Updated, UpdateType, HospitalID 
--from AB_UpdateHistory 
--where (AbstractID =  @AbstractID) and (Updatetype = 'Saved'  or Updatetype = 'Recovered')

--set @DefaultCount = isnull((select count(*) from @HR where UpdateType = 'Saved' and Coder not in (77777, 88888, 99999)), 0)  
 
--select 
--	(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID],
--	U.UserDescription as Coder,  
--	convert(varchar(11), H.Updated, 111) + ' ' + convert(varchar(5), H.Updated, 14) as [Updated] 
--from @HR H left outer join U_Users U on H.Coder = U.Code  
--order by [Hosp ID], H.Updated desc 

--set nocount off

return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_HistoryRecordVH]
	@AbstractID as varchar(10), 
	@DefaultCount as int output 
as  

declare @AppType as int 
declare @PatientID as int
declare @AID as int

set nocount on
select 	@AppType = AppType, @AID = Abstractid, @PatientID = PatientID from AB_Main where universalID = @AbstractID
set nocount off

if @AppType in (1,101,2,102,5,105)
begin
	set @DefaultCount = isnull((select count(*) from AB_UpdateHistory where AbstractID = @AID AND UpdateType = 'Saved' and Coder not in (77777, 88888, 99999)), 0)  

	select 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID],
		U.Userdescription as Coder,  
		convert(varchar(11), H.Updated, 111) + ' ' + convert(varchar(5), H.Updated, 14) as [Updated] 
	from AB_UpdateHistory H left outer join U_Users U on H.Coder = U.Code  
	where (H.AbstractID = @AID) and (UpdateType = 'Saved' or UpdateType = 'Recovered')
    order by H.Updated desc, [Hosp ID] 
    --order by [Hosp ID], H.Updated desc    PR - 03781
end
else if @AppType = 0
begin
	set @DefaultCount = isnull((select count(*) from CM_UpdateHistory where PatientID = @PatientID AND UpdateType = 'Saved' and Coder not in (77777, 88888, 99999)), 0)  

	select 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID],
		U.Userdescription as Coder, 
		convert(varchar(11), H.Updated, 111) + ' ' + convert(varchar(5), H.Updated, 14) as [Updated]
	from CM_UpdateHistory H	left outer join U_Users U on H.Coder = U.Code 
	where (H.PatientID = @PatientID) and (UpdateType = 'Saved' or UpdateType = 'Recovered')
    order by H.Updated desc, [Hosp ID] 
    --order by [Hosp ID], H.Updated desc    PR - 03781
end
else if @AppType = 3
begin
	Set @DefaultCount = isnull((select count(*) from RH_UpdateHistory where AbstractID = @AID AND Coder not in (77777, 88888, 99999)), 0)  

	select 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID],
		U.Userdescription as Coder, 
		convert(varchar(11), H.Updated, 111) + ' ' + convert(varchar(5), H.Updated, 14) as [Updated]
	from RH_UpdateHistory H left outer join U_Users U on H.Coder = U.Code 
	where (H.AbstractID =  @AID) and (UpdateType = 'Saved' or UpdateType = 'Recovered')
    order by H.Updated desc, [Hosp ID] 
    --order by [Hosp ID], H.Updated desc    PR - 03781
end
else if @AppType = 4
begin
	Set @DefaultCount = isnull((select count(*) from CRS_UpdateHistory where AbstractID = @AID AND Coder not in (77777,88888, 99999)), 0)  

	select 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID],
		U.Userdescription as Coder, 
		convert(varchar(11), H.Updated, 111) + ' ' + convert(varchar(5), H.Updated, 14) as [Updated]
	from CRS_UpdateHistory H left outer join U_Users U on H.Coder = U.Code 
	where (H.AbstractID =  @AID) and (UpdateType = 'Saved' or UpdateType = 'Recovered')
    order by H.Updated desc, [Hosp ID] 
    --order by [Hosp ID], H.Updated desc    PR - 03781
end
else if @AppType = 7
begin
	Set @DefaultCount = isnull((select count(*) from OMHRS_UpdateHistory where AbstractID = @AID AND Coder not in (77777, 88888, 99999)), 0)  

	select 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID],
		U.Userdescription as Coder, 
		convert(varchar(11), H.Updated, 111) + ' ' + convert(varchar(5), H.Updated, 14) as [Updated]
	from OMHRS_UpdateHistory H left outer join U_Users U on H.Coder = U.Code 
	where (H.AbstractID = @AID) and (UpdateType = 'Saved' or UpdateType = 'Recovered')
    order by H.Updated desc, [Hosp ID] 
    --order by [Hosp ID], H.Updated desc    PR - 03781
end
else if @AppType = 8 --PR-03290
begin
	Set @DefaultCount = isnull((select count(*) from CC_UpdateHistory where AbstractID = @AID AND Coder not in (77777, 88888, 99999)), 0) 

	select 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID],
		U.Userdescription as Coder, 
		convert(varchar(11), H.Updated, 111) + ' ' + convert(varchar(5), H.Updated, 14) as [Updated]
	from CC_UpdateHistory H left outer join U_Users U on H.Coder = U.Code 
	where (H.AbstractID =  @AbstractID) and (UpdateType = 'Saved' or UpdateType = 'Recovered')
    order by H.Updated desc, [Hosp ID] 
    --order by [Hosp ID], H.Updated desc    PR - 03781
end
else if @AppType = 9
begin
	Set @DefaultCount = isnull((select count(*) from AB_MainHistory where AbstractID = @AID AND Coder not in (77777, 88888, 99999)), 0) 

	select 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID],
		U.Userdescription as Coder, 
		convert(varchar(11), H.Updated, 111) + ' ' + convert(varchar(5), H.Updated, 14) as [Updated]
	from AB_MainHistory H left outer join U_Users U on H.Coder = U.Code 
	where (H.AbstractID =  @AbstractID) and (UpdateType = 'Saved' or UpdateType = 'Recovered')
    order by H.Updated desc, [Hosp ID] 
    --order by [Hosp ID], H.Updated desc    PR - 03781
end
else if @AppType = 10   --PR - 05949
begin
	Set @DefaultCount = isnull((select count(*) from AB_MainHistory where AbstractID = @AID AND Coder not in (77777, 88888, 99999)), 0) 

	select 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID],
		U.Userdescription as Coder, 
		convert(varchar(11), H.Updated, 111) + ' ' + convert(varchar(5), H.Updated, 14) as [Updated]
	from AB_MainHistory H left outer join U_Users U on H.Coder = U.Code 
	where (H.AbstractID =  @AbstractID) and (UpdateType = 'Saved' or UpdateType = 'Recovered')
    order by H.Updated desc, [Hosp ID] 
    --order by [Hosp ID], H.Updated desc    PR - 03781
end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is a Record history of Rehab Records.
CREATE PROCEDURE [P_HistoryReHab]
	@AbstractID AS INT,
	@DefaultCount as int output 
AS 

set @DefaultCount = isnull((select count(*) from RH_UpdateHistory where AbstractID = @AbstractID AND UpdateType = 'Saved' and Coder not in (77777, 88888, 99999)), 0) 

select 
	(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID],
	U.UserDescription AS Coder, 
	convert(varchar(11), H.Updated, 111) + ' ' + convert(varchar(5), H.Updated, 14) as [Updated]
from RH_UpdateHistory H left outer join U_Users U on H.Coder = U.Code 
where (H.AbstractID =  @AbstractID) and (UpdateType = 'Saved' or UpdateType = 'Recovered')
order by H.Updated desc, [Hosp ID] 
--order by [Hosp ID], H.Updated desc    PR - 03781
return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- This is a Record history of ROI Records.
CREATE   PROCEDURE [P_HistoryROI]
	@ROIID AS INTEGER
AS 

select 
	(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID],
	U.UserDescription as Coder, 
	convert(varchar(11), H.Updated, 111) + ' ' + convert(varchar(5), H.Updated, 14) as [Updated]
from ROI_UpdateHistory H left outer join U_Users U on H.Coder = U.Code 
where (H.ROIID =  @ROIID) and (UpdateType in ('Saved',  'Recovered'))
order by H.Updated desc

return 0



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO




-- This is a Record history of Schedule Appointment Records.
CREATE   PROCEDURE [P_HistorySched]
	@AbstractID AS INT
AS 
	SELECT dbo.U_Users.UserDescription AS Coder, 
		CONVERT(VarChar(11), dbo.SH_UpdateHistory.Updated, 111) + ' ' + 		
		CONVERT(Varchar(5), dbo.SH_UpdateHistory.Updated, 14) AS [Updated]
	FROM dbo.SH_UpdateHistory LEFT OUTER JOIN dbo.U_Users ON dbo.SH_UpdateHistory.Coder = dbo.U_Users.Code 
	WHERE (dbo.SH_UpdateHistory.AbstractID =  @AbstractID) 
	ORDER BY dbo.SH_UpdateHistory.Updated DESC

	RETURN 0



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [P_HistoryUpdate]
	@AppID as Int,
	@RecordID as Int
AS 

select 
	(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID],
	U.UserDescription as Coder, 
	convert(varchar(11), H.Updated, 111) + ' ' + convert(varchar(5), H.Updated, 14) as [Updated]
from UH_Main H left outer join U_Users U on H.Coder = U.Code 
where (H.RecordID = @RecordID) and (H.AppID = @AppID)
order by  H.Updated desc, [Hosp ID]
--order by [Hosp ID], UH_Main.Updated desc  PR - 03781

return 0

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO



-- This is the Patients Visit History. 
CREATE PROCEDURE [P_HistoryVisit] 
   @ChartNumber as VarChar(10), 
   @ChartNumber2 as VarChar(10) 
AS  
   -- INPATIENT/CCR/SDS 
   SELECT AbstractID AS [ ], CASE WHEN ICDType = 'T' AND DischargeDate IS NULL THEN 200 WHEN ICDType = 'T' AND DischargeDate IS NOT NULL THEN 201 WHEN ICDType <> 'T' AND DischargeDate IS NULL THEN 100 ELSE 101 END AS [ ],  
           ICDType AS [ICD],  
           (SELECT DisplayCode FROM LU_CareType WHERE Code = right(CareType, 1)) AS [Care], 
           (SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #], 
           CONVERT(VarChar(10), DischargeDate, 111) AS [Visit Date],  
           '' AS [Enc. Seq.],  
           (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status] 
   FROM AB_Abstract  
   WHERE (ChartNumber IN (@ChartNumber, @ChartNumber2)) 
   AND IsDeleted = 2 
   AND CareType <> 5 
 
   -- AMCARE - UNDEFINED 
   UNION 
   SELECT AbstractID AS [ ], CASE ICDType WHEN 'T' THEN 401 ELSE 301 END AS [ ], 
           ICDType AS [ICD],  
           (SELECT DisplayCode FROM LU_CareType WHERE Code = right(CareType, 1)) AS [Care], 
           (SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #], 
           CONVERT(VarChar(10), AdmitDate, 111) AS [Visit Date],  
           REPLACE(SPACE(3-LEN(ISNULL(CONVERT(VARCHAR(3),EncounterSequence), 0))) + ISNULL(CONVERT(VARCHAR(3),EncounterSequence), 0), ' ', '0') AS [Enc. Seq.],  
           (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status] 
   FROM AB_Abstract  
   WHERE (ChartNumber IN (@ChartNumber, @ChartNumber2)) 
   AND IsDeleted = 2 
   AND CareType = 5 
   AND ISNULL(MISCode, 0) = 0 
    
   -- AMCARE - EMERG CASES 
   UNION 
   SELECT AbstractID AS [ ], CASE ICDType WHEN 'T' THEN 401 ELSE 301 END AS [ ], 
           ICDType AS [ICD],  
           (SELECT DisplayCode FROM LU_CareType WHERE Code = right(CareType, 1)) + '-E' AS [Care], 
           (SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #], 
           CONVERT(VarChar(10), AdmitDate, 111) AS [Visit Date],  
           REPLACE(SPACE(3-LEN(ISNULL(CONVERT(VARCHAR(3),EncounterSequence), 0))) + ISNULL(CONVERT(VARCHAR(3),EncounterSequence), 0), ' ', '0') AS [Enc. Seq.],  
           (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status] 
   FROM AB_Abstract  
   WHERE (ChartNumber IN (@ChartNumber, @ChartNumber2)) 
   AND IsDeleted = 2 
   AND CareType = 5 
   AND (MISCode <> 0 AND MISCode NOT IN (SELECT Code FROM LU_MISCode WHERE left (CIHIValue, 5) like '7%466'  
   or CIHIValue LIKE '7%34020' OR LEFT(CIHIValue, 7) LIKE '7%34025' OR CIHIValue LIKE '7%34055' OR LEFT(CIHIValue, 5) LIKE '7%260' OR CIHIValue LIKE '7%262' OR LEFT(CIHIValue, 5) LIKE '7%265' OR LEFT(CIHIValue, 7) LIKE '7%34066' OR LEFT(CIHIValue, 7) LIKE '7%35066' OR LEFT(CIHIValue, 5) LIKE '7%420' OR LEFT(CIHIValue, 7) LIKE '7%53066' OR LEFT(CIHIValue, 7) LIKE '7%34086' OR LEFT(CIHIValue, 7) LIKE '7%53086' OR LEFT(CIHIValue, 7) LIKE '7%41544')) 
 
   -- AMCARE - SDS CASES 
   UNION 
   SELECT AbstractID AS [ ], CASE ICDType WHEN 'T' THEN 401 ELSE 301 END AS [ ], 
           ICDType AS [ICD],  
           (SELECT DisplayCode FROM LU_CareType WHERE Code = right(CareType, 1)) + '-D' AS [Care], 
           (SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #], 
           CONVERT(VarChar(10), AdmitDate, 111) AS [Visit Date],  
           REPLACE(SPACE(3-LEN(ISNULL(CONVERT(VARCHAR(3),EncounterSequence), 0))) + ISNULL(CONVERT(VARCHAR(3),EncounterSequence), 0), ' ', '0') AS [Enc. Seq.],  
           (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status] 
   FROM AB_Abstract  
   WHERE (ChartNumber IN (@ChartNumber, @ChartNumber2)) 
   AND IsDeleted = 2 
   AND CareType = 5 
   AND MISCode IN (SELECT Code FROM LU_MISCode WHERE CIHIValue LIKE '7%34020' OR LEFT(CIHIValue, 7) LIKE '7%34025' OR CIHIValue LIKE '7%34055' OR LEFT(CIHIValue, 5) LIKE '7%260' OR CIHIValue LIKE '7%262' OR LEFT(CIHIValue, 5) LIKE '7%265') 
 
   -- AMCARE - CLINIC CASES 
   UNION 
   SELECT AbstractID AS [ ], CASE ICDType WHEN 'T' THEN 401 ELSE 301 END AS [ ], 
           ICDType AS [ICD],  
           (SELECT DisplayCode FROM LU_CareType WHERE Code = right(CareType, 1)) + '-C' AS [Care], 
           (SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #], 
           CONVERT(VarChar(10), AdmitDate, 111) AS [Visit Date],  
           REPLACE(SPACE(3-LEN(ISNULL(CONVERT(VARCHAR(3),EncounterSequence), 0))) + ISNULL(CONVERT(VARCHAR(3),EncounterSequence), 0), ' ', '0') AS [Enc. Seq.],  
           (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status] 
   FROM AB_Abstract  
   WHERE (ChartNumber IN (@ChartNumber, @ChartNumber2)) 
   AND IsDeleted = 2 
   AND CareType = 5 
   AND MISCode IN (SELECT Code FROM LU_MISCode WHERE left (CIHIValue, 5) like '7%466' 
   or LEFT(CIHIValue, 7) LIKE '7%34066' OR LEFT(CIHIValue, 7) LIKE '7%35066' OR LEFT(CIHIValue, 5) LIKE '7%420' OR LEFT(CIHIValue, 7) LIKE '7%53066' OR LEFT(CIHIValue, 7) LIKE '7%34086' OR LEFT(CIHIValue, 7) LIKE '7%53086' OR LEFT(CIHIValue, 7) LIKE '7%41544') 
 
   -- REHAB ADMISSION 
   UNION  
   SELECT AbstractID AS [ ], 250 AS [ ], 
           'T' AS [ICD],  
           'R-1' AS [Care], 
           (SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #], 
           CONVERT(VarChar(10), AdmitDate, 111) AS [Visit Date], 
           '' AS [Enc. Seq.],  
           (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]          
   FROM RH_ClientInfo  
   WHERE (ChartNumber IN (@ChartNumber, @ChartNumber2)) 
   AND IsDeleted = 2 
   AND AssessmentType = 134 
 
   -- REHAB DISCHARGE 
   UNION  
   SELECT AbstractID AS [ ], 251 AS [ ], 
           'T' AS [ICD],  
           'R-2' AS [Care], 
           (SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #], 
           CONVERT(VarChar(10), DischargeDate, 111) AS [Visit Date], 
           '' AS [Enc. Seq.],  
           (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]          
   FROM RH_ClientInfo  
   WHERE (ChartNumber IN (@ChartNumber, @ChartNumber2)) 
   AND IsDeleted = 2 
   AND AssessmentType = 135 
 
   -- REHAB FOLLOW UP 
   UNION  
   SELECT AbstractID AS [ ], 252 AS [ ], 
           'T' AS [ICD],  
           'R-3' AS [Care], 
           (SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #], 
           CONVERT(VarChar(10), FollowUpDate, 111) AS [Visit Date], 
           '' AS [Enc. Seq.],  
           (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]          
   FROM RH_ClientInfo  
   WHERE (ChartNumber IN (@ChartNumber, @ChartNumber2)) 
   AND IsDeleted = 2 
   AND AssessmentType = 136 
 
   -- CCRS ADMISSION BG 
   UNION  
   SELECT AbstractID AS [ ], 470 AS [ ], 
           'T' AS [ICD],  
           'L-0A' AS [Care], 
           (SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #], 
           CONVERT(VarChar(10), AdmitDate, 111) AS [Visit Date], 
           '' AS [Enc. Seq.],  
           (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]          
   FROM CRS_Demographic 
   WHERE (ChartNumber IN (@ChartNumber, @ChartNumber2)) 
   AND AA8 = 14501 
   AND IsDeleted = 2 
 
   -- CCRS DEMO CHANGES 
   UNION  
   SELECT AbstractID AS [ ], 471 AS [ ], 
           'T' AS [ICD],  
           'L-00' AS [Care], 
           (SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #], 
           CONVERT(VarChar(10), Z7, 111) AS [Visit Date], 
           '' AS [Enc. Seq.],  
           (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]          
   FROM CRS_Demographic 
   WHERE (ChartNumber IN (@ChartNumber, @ChartNumber2)) 
   AND AA8 = 14500 
   AND IsDeleted = 2 
 
   -- CCRS ADMIT ASSESS 
   UNION  
   SELECT AbstractID AS [ ], 473 AS [ ], 
           'T' AS [ICD],  
           'L-01' AS [Care], 
           (SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #], 
           CONVERT(VarChar(10), A3, 111) AS [Visit Date], 
           '' AS [Enc. Seq.],  
           (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]          
   FROM CRS_Demographic 
   WHERE (ChartNumber IN (@ChartNumber, @ChartNumber2)) 
   AND AA8 = 14502 
   AND IsDeleted = 2 
 
   -- CCRS FULL ASSESS 
   UNION  
   SELECT AbstractID AS [ ], 473 AS [ ], 
 
           'T' AS [ICD],  
           'L-02' AS [Care], 
           (SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #], 
           CONVERT(VarChar(10), A3, 111) AS [Visit Date], 
           '' AS [Enc. Seq.],  
           (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]          
   FROM CRS_Demographic 
   WHERE (ChartNumber IN (@ChartNumber, @ChartNumber2)) 
   AND AA8 = 14503 
   AND IsDeleted = 2 
 
   -- CCRS FULL ASSESS CHANGE 
   UNION  
   SELECT AbstractID AS [ ], 473 AS [ ], 
           'T' AS [ICD],  
           'L-03' AS [Care], 
           (SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #], 
           CONVERT(VarChar(10), A3, 111) AS [Visit Date], 
           '' AS [Enc. Seq.],  
           (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]          
   FROM CRS_Demographic 
   WHERE (ChartNumber IN (@ChartNumber, @ChartNumber2)) 
   AND AA8 = 14504 
   AND IsDeleted = 2 
 
   -- CCRS FULL ASSESS CORRECT 
   UNION  
   SELECT AbstractID AS [ ], 473 AS [ ], 
           'T' AS [ICD],  
           'L-04' AS [Care], 
           (SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #], 
           CONVERT(VarChar(10), A3, 111) AS [Visit Date], 
           '' AS [Enc. Seq.],  
           (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]          
   FROM CRS_Demographic 
   WHERE (ChartNumber IN (@ChartNumber, @ChartNumber2)) 
   AND AA8 = 14505 
   AND IsDeleted = 2 
 
   -- CCRS QUARTER ASSESS 
   UNION  
   SELECT AbstractID AS [ ], 472 AS [ ], 
           'T' AS [ICD],  
           'L-05' AS [Care], 
           (SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #], 
           CONVERT(VarChar(10), A3, 111) AS [Visit Date], 
           '' AS [Enc. Seq.],  
           (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]          
   FROM CRS_Demographic 
   WHERE (ChartNumber IN (@ChartNumber, @ChartNumber2)) 
   AND AA8 = 14506 
   AND IsDeleted = 2 
 
   -- CCRS QUARTER ASSESS CHANGE/CORRECT 
   UNION  
   SELECT AbstractID AS [ ], 472 AS [ ], 
           'T' AS [ICD],  
           'L-10' AS [Care], 
           (SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #], 
           CONVERT(VarChar(10), A3, 111) AS [Visit Date], 
           '' AS [Enc. Seq.],  
           (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]          
   FROM CRS_Demographic 
   WHERE (ChartNumber IN (@ChartNumber, @ChartNumber2)) 
   AND AA8 = 14511 
   AND IsDeleted = 2 
 
   -- CCRS DISCHARGE W/OUT RETURN 
   UNION  
   SELECT AbstractID AS [ ], 474 AS [ ], 
           'T' AS [ICD],  
           'L-06' AS [Care], 
           (SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #], 
           CONVERT(VarChar(10), DischargeDate, 111) AS [Visit Date], 
           '' AS [Enc. Seq.],  
           (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]          
   FROM CRS_Demographic 
   WHERE (ChartNumber IN (@ChartNumber, @ChartNumber2)) 
   AND AA8 = 14507 
   AND IsDeleted = 2 
 
   -- CCRS DISCHARGE W/ RETURN 
   UNION  
   SELECT AbstractID AS [ ], 474 AS [ ], 
           'T' AS [ICD],  
           'L-07' AS [Care], 
           (SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #], 
           CONVERT(VarChar(10), DischargeDate, 111) AS [Visit Date], 
           '' AS [Enc. Seq.],  
           (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]          
   FROM CRS_Demographic 
   WHERE (ChartNumber IN (@ChartNumber, @ChartNumber2)) 
   AND AA8 = 14508 
   AND IsDeleted = 2 
 
   -- CCRS DISCHARGE W/OUT ASSESSMENT 
   UNION  
   SELECT AbstractID AS [ ], 474 AS [ ], 
           'T' AS [ICD],  
           'L-08' AS [Care], 
           (SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #], 
           CONVERT(VarChar(10), DischargeDate, 111) AS [Visit Date], 
           '' AS [Enc. Seq.],  
           (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]          
   FROM CRS_Demographic 
   WHERE (ChartNumber IN (@ChartNumber, @ChartNumber2)) 
   AND AA8 = 14509 
   AND IsDeleted = 2 
 
   -- CCRS RE-ENTRY 
   UNION  
   SELECT AbstractID AS [ ], 475 AS [ ], 
           'T' AS [ICD],  
           'L-09' AS [Care], 
           (SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #], 
           CONVERT(VarChar(10), AB1b, 111) AS [Visit Date], 
           '' AS [Enc. Seq.],  
           (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]          
   FROM CRS_Demographic 
   WHERE (ChartNumber IN (@ChartNumber, @ChartNumber2)) 
   AND AA8 = 14510 
   AND IsDeleted = 2 
 
   -- CLINIC 
   UNION 
   SELECT  dbo.CR_Demographic.AbstractID AS [ ], 451 AS [ ], 
           '' AS ICD,  
           'C' AS Care,  
           '' AS [Inst. #],  
           CONVERT(VarChar(10), dbo.CR_Visit.AdmitDate, 111) AS [Visit Date], 
           '' AS [Enc. Seq.],  
                   (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted) AS Status 
   FROM dbo.CR_Demographic LEFT OUTER JOIN dbo.CR_Visit ON dbo.CR_Demographic.AbstractID = dbo.CR_Visit.AbstractID 
   WHERE (ChartNumber in (@ChartNumber, @ChartNumber2)) 
   AND IsDeleted = 2 
 
   -- TRANSCRIPITON 
   UNION 
   SELECT TranscriptionID AS [ ], 20 AS [ ], 
           '' AS [ICD],  
           'T' AS [Care], 
           '' AS [Inst. #], 
           CONVERT(VarChar(10), TranscriptionDate, 111) AS [Visit Date], 
           '' AS [Enc. Seq.],  
           '' AS [Status]           
   FROM TR_Main  
   WHERE (PatientID IN (SELECT PatientID FROM CM_CPI WHERE Chartnumber IN (@ChartNumber, @ChartNumber2))) 
 
   ORDER BY [Visit Date] DESC 




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is the Patients Visit History. 
CREATE PROCEDURE [P_HistoryVisit2]
	@ChartNumber as VarChar(10), 
	@ChartNumber2 as VarChar(10),
	@HospID as int = 0,
	@SearchType as int = 0,
	@ShowNonAbstract as int = 0
AS  
	set nocount on

	SELECT	dbo.AB_Main.UniversalID, dbo.AB_Main.AbstractID, dbo.AB_Main.AppID, 
		dbo.AB_Main.ICDType, 
		dbo.LU_CareType.DisplayCode AS CareType, 
		dbo.H_InstitutionProfile.DisplayCode AS Inst, 
		dbo.H_InstitutionProfile.UserDescription AS InstD, 
		CONVERT(VarChar(10), dbo.AB_Main.AdmitDate, 111) AS [Admit Date], 
		CONVERT(VarChar(10), dbo.AB_Main.DischargeDate, 111) AS [Discharge Date], 
		dbo.AB_Main.EncounterNumber AS [Enc. Num.], 
		CAST(dbo.AB_Main.EncounterSequence AS varchar(3)) AS [Enc. Seq.], 
		dbo.LU_MISCode.DisplayCode AS MISCode, 
-- 		dbo.LU_AbstractStatus.DisplayCode AS DCStatus,  --ED-02065
-- 		dbo.LU_AbstractStatus.UserDescription AS Status, --ED-02065 
		(select top 1 DisplayCode from LU_AbstractStatus where isnull(Code, 0) = isnull(IsValidLevel1, 0)) as [L1Status], --ED-02065
		(select top 1 UserDescription from LU_AbstractStatus where isnull(Code, 0) = isnull(IsValidLevel1, 0)) as [L1StatusD],
		(select top 1 DisplayCode from LU_AbstractStatus where isnull(Code, 0) = isnull(IsValidated, 0)) as [L3Status], --ED-02065
		(select top 1 UserDescription from LU_AbstractStatus where isnull(Code, 0) = isnull(IsValidated, 0)) as [L3StatusD],
		dbo.LU_YesBlank.DisplayCode AS Died, 
		LU_YesBlank_1.DisplayCode AS Trans, 
		--LU_YesBlank_2.DisplayCode AS MDAS, --RM: 2009/11/11
		--(case isnull(HasDAS, 0) when 0 then 'N' when -1 then 'P' else 'Y' end) as [MDAS],
		(case when isnull(HasDAS, 0) = 0 then 'N' when isnull(HasDAS, 0) = -1 then 'P' when isnull(HasDAS, 0) < -1 then 'E' else 'Y' end) as [MDAS],
		dbo.H_InstitutionProfile.LockDownDate, CAST('Open' AS varchar(10)) AS Lockdown, 
		dbo.AB_Main.HospitalID, 
		(select top 1 UserDescription from H_HospitalProfile where isnull(Code, 0) = isnull(dbo.AB_Main.HospitalID, -1)) as [HospitalIDD],
		12345 AS AssType, 
		dbo.AB_Main.RegisterNumber, 
		--PR - 05542
		--CONVERT(VarChar(10), dbo.AB_Main.AdmitDate, 111) AS [Visit Date], 
		CONVERT(VarChar(10), isnull(dbo.AB_Main.VisitDate, dbo.AB_Main.AdmitDate), 111) AS [Visit Date], 
		
		--PR - 05272
		--2.x- 0447 Add OT, DI
		(case LU_MISCode.AmCareGroup when 'ED' then 'B-E' when 'DS' then 'B-D' when 'CL' then 'B-C' when 'DI' then 'B-I' when 'OT' then 'B-O' else dbo.LU_CodeFile.DisplayCode end) AS AmcareCareType,
--	 	(select top 1 DisplayCode from H_HospitalProfile as H where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID] --NP-00025
		cast('' as varchar(50)) as [Hosp ID], --PR - 00901
		(select top 1 DisplayCode from LU_NurseArea where isnull(Code, 0) = isnull(AdmittingNurseArea, 0)) as [AdmittingNurseArea],
		(select top 1 UserDescription from LU_NurseArea where isnull(Code, 0) = isnull(AdmittingNurseArea, 0)) as [AdmittingNurseAreaD],
		(select top 1 DisplayCode from LU_Provider where isnull(Code, 0) = isnull(AttendingPhysician, 0)) as [AttendingPhysician],
		(select top 1 UserDescription from LU_Provider where isnull(Code, 0) = isnull(AttendingPhysician, 0)) as [AttendingPhysicianD],
		(select top 1 DisplayCode from LU_Provider where isnull(Code, 0) = isnull(RefPhysician, 0)) as [RefPhysician],
		(select top 1 UserDescription from LU_Provider where isnull(Code, 0) = isnull(RefPhysician, 0)) as [RefPhysicianD],
	--PR - 04909 Not showing the correct ICD9/9CM diagnosis code and intervention code.	
    (case when ICDType = 'T' 
            then (select top 1 DisplayCode from ICD_DiagFile10 where Code = isnull(DiagnosisCode, 0)) 
          when ICDType = '9' 
            then (select top 1 DisplayCode from ICD_DiagFile9 where Code = isnull(DiagnosisCode, 0)) 
          when ICDType = 'C' 
            then (select top 1 DisplayCode from ICD_DiagFile9cm where Code = isnull(DiagnosisCode, 0)) 
          end) as [DiagnosisCode],
    (case when ICDType = 'T' 
            then (select top 1 UserDescription from ICD_DiagFile10 where Code = isnull(DiagnosisCode, 0)) 
          when ICDType = '9' 
            then (select top 1 UserDescription from ICD_DiagFile9 where Code = isnull(DiagnosisCode, 0)) 
          when ICDType = 'C' 
            then (select top 1 UserDescription from ICD_DiagFile9cm where Code = isnull(DiagnosisCode, 0)) 
          end) as [DiagnosisCodeD],

    (case when ICDType = 'T' 
            then (select top 1 DisplayCode from ICD_ProcFile10 where Code = isnull(IntervCode, 0)) 
          when ICDType = '9' 
            then (select top 1 DisplayCode from ICD_ProcFile9 where Code = isnull(IntervCode, 0)) 
          when ICDType = 'C' 
            then (select top 1 DisplayCode from ICD_ProcFile9cm where Code = isnull(IntervCode, 0)) 
          end) as [IntervCode],
    (case when ICDType = 'T' 
            then (select top 1 UserDescription from ICD_ProcFile10 where Code = isnull(IntervCode, 0)) 
          when ICDType = '9' 
            then (select top 1 UserDescription from ICD_ProcFile9 where Code = isnull(IntervCode, 0)) 
          when ICDType = 'C' 
            then (select top 1 UserDescription from ICD_ProcFile9cm where Code = isnull(IntervCode, 0)) 
          end) as [IntervCodeD],

  --      (select top 1 UserDescription from ICD_DiagFile10 where Code = isnull(DiagnosisCode, 0)) 
		--(select top 1 UserDescription from ICD_DiagFile10 where isnull(Code, 0) = isnull(DiagnosisCode, 0)) as [DiagnosisCodeD],
		
		--(select top 1 DisplayCode from ICD_ProcFile10 where isnull(Code, 0) = isnull(IntervCode, 0)) as [IntervCode],
		--(select top 1 UserDescription from ICD_ProcFile10 where isnull(Code, 0) = isnull(IntervCode, 0)) as [IntervCodeD],

		(select top 1 DisplayCode from LU_PatientType where isnull(Code, 0) = isnull(AB_Main.PatientType, 0)) as [PType], --PR-01802
		(select top 1 UserDescription from LU_PatientType where isnull(Code, 0) = isnull(AB_Main.PatientType, 0)) as [PTypeD], --PR-01802
		VisitTime = isnull(VisitTime, AdmitTime),  --PR - 06798
		LevelCode =(case when H_InstitutionProfile.AssociationID = 5 then (case when H_InstitutionProfile.LevelCode in (1, 2, 4, 5) then cast(H_InstitutionProfile.LevelCode as varchar(10)) 
																				when H_InstitutionProfile.LevelCode = 0 and UseLite = 1 then '0'	--2.x-0446 add Lite
																				else '3' end) 
						 else '' end)
	Into #VHTemp
	FROM  dbo.LU_CareType 
--	RIGHT OUTER JOIN dbo.LU_AbstractStatus 
	RIGHT OUTER JOIN dbo.LU_CodeFile 
	RIGHT OUTER JOIN dbo.LU_MISCode ON dbo.LU_CodeFile.Code = dbo.LU_MISCode.AMCareType 
	RIGHT OUTER JOIN dbo.AB_Main ON dbo.LU_MISCode.Code = dbo.AB_Main.MISCode 
--	ON dbo.LU_AbstractStatus.Code = dbo.AB_Main.IsValidated --PR-01866 IsCompleted
	ON dbo.LU_CareType.Code = dbo.AB_Main.AppType 
--	LEFT OUTER JOIN dbo.LU_YesBlank AS LU_YesBlank_2 ON dbo.AB_Main.HasDAS = LU_YesBlank_2.Code --RM: 2009/11/11
	LEFT OUTER JOIN dbo.LU_YesBlank AS LU_YesBlank_1 ON dbo.AB_Main.HasTrans = LU_YesBlank_1.Code 
	LEFT OUTER JOIN dbo.LU_YesBlank ON dbo.AB_Main.DeathIndicator = dbo.LU_YesBlank.Code 
	LEFT OUTER JOIN	dbo.H_InstitutionProfile ON dbo.AB_Main.InstitutionNumber = dbo.H_InstitutionProfile.Code
	WHERE (dbo.AB_Main.IsDeleted = 2) AND (dbo.AB_Main.AppType <> 0) AND (dbo.AB_Main.ChartNumber IN (@ChartNumber, @ChartNumber2))

	--Restrict by hospital
	if isnull(@HospID, 0) <> 0
		Delete #VHTemp where isnull(HospitalID, 0) <> @HospID and isnull(HospitalID, 0) <> 0 -- [RM - PR-00599] 2006/04/03
		--Delete #VHTemp where HospitalID
	Update #VHTemp set [Hosp ID] = DisplayCode from H_HospitalProfile where code = #VHTemp.hospitalid--PR - 00901
	--Format Encounter Number Sequence
	Update #VHTEmp set [Enc. Seq.] = REPLACE(SPACE(3-LEN(ISNULL(CONVERT(VARCHAR(3),[Enc. Seq.]), 0))) + ISNULL(CONVERT(VARCHAR(3),[Enc. Seq.]), 0), ' ', '0')
	where [Enc. Seq.] is not null
	--Set Lockdown Status Flag
	Update #VHTEmp set LockDown = 'Locked' where lockdowndate > [Admit Date] and appid in (301,401)
	Update #VHTEmp set LockDown = 'Locked' where lockdowndate > [Discharge Date] and appid not in (301,401)
	--Update non Abstracts
	Update #VHTEmp set abstractid = universalID where appid = 3
	--Update Care Type
	-- AMCARE - EMERG CASES 
	Update #VHTEmp set CareType = AmcareCareType where appid in (301, 401)
	Update #VHTEmp set CareType = 'B' where appid in (301, 401) and CareType is null
--	Update #VHTEmp set CareType = 'B-E' where appid in (301, 401) and left(MISCode, 5) LIKE '7%310'
	-- AMCARE - SDS CASES 
--	Update #VHTEmp set CareType = 'B-D' where appid in (301, 401) and (MISCode LIKE '7%34020' OR LEFT(MISCode, 7) LIKE '7%34025' 
--	OR MISCode LIKE '7%34055' OR LEFT(MISCode, 5) LIKE '7%260' OR MISCode LIKE '7%262' OR LEFT(MISCode, 5) LIKE '7%265')
	-- AMCARE - CLINIC CASES 
--	Update #VHTEmp set CareType = 'B-C' where appid in (301, 401) and (left (MISCode, 5) like '7%466'
--	or LEFT(MISCode, 7) LIKE '7%34066' OR LEFT(MISCode, 7) LIKE '7%35066' OR LEFT(MISCode, 5) LIKE '7%420' OR LEFT(MISCode, 7) LIKE '7%53066' 
--	OR LEFT(MISCode, 7) LIKE '7%34086' OR LEFT(MISCode, 7) LIKE '7%53086' OR LEFT(MISCode, 7) LIKE '7%41544')

	-- REHAB ADMISSION
	Update #VHTEmp set CareType = 'R-1' where appid = 250
	-- REHAB ADMISSION
	Update #VHTEmp set CareType = 'R-2' where appid = 251
	-- REHAB ADMISSION
	Update #VHTEmp set CareType = 'R-3' where appid = 252
	--Rehab Interm
	delete #VHTEmp where appid = 253
	--Rehab Post Discharge(EN-00459)
	delete #VHTEmp where appid = 254
	-- OMHRS ADMISSION
	Update #VHTEmp set CareType = 'M-A' where appid = 650
	-- OMHRS Short Stay
	Update #VHTEmp set CareType = 'M-S' where appid = 651
	-- OMHRS Quarterly
	Update #VHTEmp set CareType = 'M-Q' where appid = 652
	-- OMHRS Change
	Update #VHTEmp set CareType = 'M-C' where appid = 653
	-- OMHRS Discharge
	Update #VHTEmp set CareType = 'M-D' where appid = 654


	If Exists (select * from #VHTEmp where left(CareType, 1) = 'R')
	Begin
		Update #VHTEmp set [Visit Date] = [Discharge Date] where caretype in ('R-2')
		Update #VHTEmp set [Visit Date] = CONVERT(VarChar(10), FollowUpDate, 111) from RH_ClientInfo where RH_ClientInfo.AbstractID = 
			#VHTEmp.AbstractID and (#VHTEmp.appid = 252 or #VHTEmp.appid = 254)
	End

	--Get Assessment type if there are any CCRS
	If Exists (select * from #VHTEmp where CareType = 'L')
	Begin
		Update #VHTEmp set AssType = AA8 from CRS_Demographic where CRS_Demographic.abstractid = 
		#VHTEmp.AbstractID and CareType = 'L'
		-- CCRS ADMISSION BG 
		Update #VHTEmp set CareType = 'L-0A' where appid = 470 and AssType = 14501
		--  CCRS DEMO CHANGES 
		Update #VHTEmp set CareType = 'L-00' where appid = 471 and AssType = 14500
		-- CCRS ADMIT ASSESS 
		Update #VHTEmp set CareType = 'L-01' where appid = 473 and AssType = 14502
		-- CCRS FULL ASSESS
		Update #VHTEmp set CareType = 'L-02' where appid = 473 and AssType = 14503
		-- CCRS FULL ASSESS CHANGE
		Update #VHTEmp set CareType = 'L-03' where appid = 473 and AssType = 14504
		-- CCRS FULL ASSESS CORRECT 
		Update #VHTEmp set CareType = 'L-04' where appid = 473 and AssType = 14505
		-- CCRS QUARTER ASSESS 
		Update #VHTEmp set CareType = 'L-05' where appid = 472 and AssType = 14506
		-- CCRS QUARTER ASSESS CHANGE/CORRECT 
		Update #VHTEmp set CareType = 'L-10' where appid = 472 and AssType = 14511
		-- CCRS DISCHARGE W/OUT RETURN  
		Update #VHTEmp set CareType = 'L-06' where appid = 474 and AssType = 14507
		-- CCRS DISCHARGE W/ RETURN 
		Update #VHTEmp set CareType = 'L-07' where appid = 474 and AssType = 14508
		-- CCRS DISCHARGE W/OUT ASSESSMENT
		Update #VHTEmp set CareType = 'L-08' where appid = 474 and AssType = 14509
		-- CCRS RE-ENTRY
		Update #VHTEmp set CareType = 'L-09' where appid in (470, 475) and AssType = 14510
		-- CCRS UPDATE --ED-02133
		Update #VHTEmp set CareType = 'L-17' where appid = 476 and AssType = 203626
		-- CCRS PROJECT --ED-02133
		Update #VHTEmp set CareType = 'L-18' where appid = 476 and AssType = 203627
		--Update Display Dates for CCRS
		Update #VHTEmp set [Visit Date] = [Discharge Date] where caretype in ('L-06', 'L-07', 'L-08')
		Update #VHTEmp set [Visit Date] = CONVERT(VarChar(10), Z7, 111) from CRS_Demographic where caretype in ('L-00') and CRS_Demographic.AbstractID = #VHTEmp.AbstractID
		--Added L-01 and l-02 for Hong 2006/01/19
		Update #VHTEmp set [Visit Date] = CONVERT(VarChar(10), A3, 111) from CRS_Demographic where caretype in ('L-02', 'L-01', 'L-03', 'L-04', 'L-05', 'L-10') and CRS_Demographic.AbstractID = #VHTEmp.AbstractID
		Update #VHTEmp set [Visit Date] = CONVERT(VarChar(10), AB1b, 111) from CRS_Demographic where caretype in ('L-09') and CRS_Demographic.AbstractID = #VHTEmp.AbstractID and #VHTEmp.[Visit Date] is null
		Update #VHTEmp set [Visit Date] = CONVERT(VarChar(10), Z12, 111) from CRS_Demographic where caretype in ('L-17') and CRS_Demographic.AbstractID = #VHTEmp.AbstractID --ED-02133
		Update #VHTEmp set [Visit Date] = CONVERT(VarChar(10), Z13, 111) from CRS_Demographic where caretype in ('L-18') and CRS_Demographic.AbstractID = #VHTEmp.AbstractID --ED-02133
	End

	-- PR - 03302 - CCO
	--Get Diagnosis Code if there are any Cancer Care 
	If Exists (select * from #VHTEmp where AppID = 675)
	Begin
				
		Update #VHTEmp set #VHTEmp.DiagnosisCode  = case when CC_DiseaseRegister.DiagnosisCode = 0 then null else CC_DiseaseRegister.DiagnosisCode end 
		from CC_DiseaseRegister where CC_DiseaseRegister.abstractid = #VHTEmp.AbstractID and AppID = 675

		-- Diagnosis Code Description 
		Update #VHTEmp set DiagnosisCodeD = UserDescription  from ICD_DiagFile10 where isnull(Code, 0) = isnull(DiagnosisCode, 0)
		and AppID = 675
		Update #VHTEmp set #VHTEmp.DiagnosisCode  = DisplayCode from ICD_DiagFile10 where isnull(Code, 0) = isnull(DiagnosisCode, 0)
		and AppID = 675		
		
	End

	Update #VHTEmp set [Visit Date] = [Discharge Date] where appid in (201, 101, 100, 200, 202, 102)
	Update #VHTEmp set ICDType = 'T' where appid in (650, 651, 652, 653, 654) and isnull(icdtype, '') = '' --PR - 00997

	If @SearchType = 0 and isnull(@ShowNonAbstract, 0) = 1--NP-00025
		Delete #VHTEmp where appid = 3--NP-00025

	set nocount off

	--If it is detail search
	If @SearchType = 1
		Select UniversalID, AbstractID, AppID, ICDType, 
			[Hosp ID],
			HospitalIDD as [Hospital Desc],
			CareType as [Care], 
			[PType] as [Patient Type], --PR-01802
			[PTypeD] as [Patient Type Desc], --PR-01802
			Inst, 
			InstD as [Inst Desc], 
			[Admit Date], 
			[Discharge Date], 
			[Enc. Num.], 
			[Enc. Seq.], 
			RegisterNumber as [Reg Num], 
			MISCode as [MIS Code], 
			[AdmittingNurseArea] as [Nurse Unit],
			[AdmittingNurseAreaD] as [Nurse Unit Desc],
			[AttendingPhysician] as [Att. Provider],
			[AttendingPhysicianD] as [Att. Provider Desc],
			[RefPhysician] as [Ref. Provider],
			[RefPhysicianD] as [Ref. Provider Desc],
			[DiagnosisCode] as [Diag Code],
			[DiagnosisCodeD] as [Diag Code Desc],
			[IntervCode] as [Interv Code], 
			[IntervCodeD] as [Interv Code Desc], 
--			Status, --ED-02065
			L1StatusD as [L1/2 Status],  --ED-02065
			L3StatusD as [L3 Status],  --ED-02065
			Died, 
			Trans, 
			MDAS, 
			Lockdown as [Locked] 
		from #VHTEmp
		--PR - 05542
		--ORDER BY [Hosp ID], [Admit Date] DESC, [Discharge Date] DESC
		--PR - 05777
		--ORDER BY [Hosp ID], [Visit Date] Desc, [Admit Date] DESC, [Discharge Date] DESC
		order by [Hosp ID], isnull([Visit Date], getdate()) desc, isnull([Admit Date], getdate()) desc, isnull([Discharge Date], getdate()) desc, convert(varchar(20), visittime, 114) desc

	--If it is main screen search
	Else
		--PR-01802: Added Patient Type
		--EN-00447: Added [MDAS] Scan Flag (borrowed from original [HasDAS]
		--ED-02065: Changed to DCStatus to L1Status & L3Status
		select UniversalID, AbstractID, AppID, L1Status, L3Status, [MDAS], [Hosp ID], CareType as [Care], [PType] as [Patient Type], Inst, [Visit Date], [Level Code] = LevelCode from #VHTEmp
		--PR - 05542
		--ORDER BY [Hosp ID], [Admit Date] DESC, [Discharge Date] DESC
		--PR - 05777
		--ORDER BY [Hosp ID], [Visit Date] Desc, [Admit Date] DESC, [Discharge Date] DESC
		order by [Hosp ID], isnull([Visit Date], getdate()) desc, isnull([Admit Date], getdate()) desc, isnull([Discharge Date], getdate()) desc, convert(varchar(20), visittime, 114) desc
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO







-- This is the Patients Visit History for Amcare.
CREATE     PROCEDURE [P_HistoryVisitAmcare]
	@ChartNumber as VarChar(10),
	@ChartNumber2 as VarChar(10)
AS 

	SELECT AbstractID, 
		ICDType AS [ICD], 
		(SELECT DisplayCode FROM LU_CareType WHERE Code = CareType) AS [Care],
		(SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #],
		CONVERT(VarChar(10), AdmitDate, 111) AS [Register Date], 
		REPLACE(SPACE(3-LEN(ISNULL(CONVERT(VARCHAR(3),EncounterSequence), 0))) + ISNULL(CONVERT(VARCHAR(3),EncounterSequence), 0), ' ', '0') AS [Enc. Seq.], 
		(SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]
	FROM AB_Abstract 
	WHERE (ChartNumber in (@ChartNumber, @ChartNumber2))
	AND IsDeleted = 2
	Union 
	SELECT TranscriptionID, 
		'' AS [ICD], 
		'T' AS [Care],
		'' AS [Inst. #],
		CONVERT(VarChar(10), TranscriptionDate, 111) AS [Register Date],'' AS [Enc. Seq.], 
		'' AS [Status]		
	FROM TR_Main 
	WHERE (Patientid in (select patientid from CM_CPI where Chartnumber in (@ChartNumber, @ChartNumber2)))
	Union
	SELECT  dbo.CR_Demographic.AbstractID, '' AS ICD, 'C' AS Care, '' AS [Inst. #], CONVERT(VarChar(10), dbo.CR_Visit.AdmitDate, 111) AS [Register Date], '' AS [Enc. Seq.], 
        	(SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted) AS Status
		FROM dbo.CR_Demographic LEFT OUTER JOIN
                dbo.CR_Visit ON dbo.CR_Demographic.AbstractID = dbo.CR_Visit.AbstractID
	WHERE (ChartNumber in (@ChartNumber, @ChartNumber2))
	AND IsDeleted = 2
	Union
	SELECT AbstractID, 
		'T' AS [ICD], 
		'R' AS [Care],
		(SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #],
		CONVERT(VarChar(10), DischargeDate, 111) AS [Register Date], '' AS [Enc. Seq.], 
		(SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]		
	FROM RH_ClientInfo 
	WHERE (ChartNumber in (@ChartNumber, @ChartNumber2))
	AND IsDeleted = 2
	Union
	SELECT AbstractID, 
		'T' AS [ICD], 
		'L' AS [Care],
		(SELECT DisplayCode FROM H_InstitutionProfile WHERE Code = InstitutionNumber)  AS [Inst. #],
		CONVERT(VarChar(10), AdmitDate, 111) AS [Register Date], '' AS [Enc. Seq.], 
		'' AS [Status]		
	FROM CRS_Demographic
	WHERE (ChartNumber in (@ChartNumber, @ChartNumber2))
	AND AA8 = 14501

	ORDER BY [Register Date] DESC



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is a record history of CPI Volume Records.
CREATE PROCEDURE [P_HistoryVolume]
	@VolumeID as VarChar(10)
AS 
	select 
		(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(H.HospitalID, 0)) as [Hosp ID],
		UserDescription AS Coder, 
		convert(varchar(11), Updated, 111) + ' ' +  convert(Varchar(5), Updated, 14) AS [Updated]
	from CM_Volume_UpdateHistory H left outer join U_Users U on H.Coder = U.Code 
	where (VolumeID = @VolumeID) 
	and (UpdateType = 'Saved'  or UpdateType = 'Recovered')
	order by H.Updated desc, [Hosp ID] 
    --order by [Hosp ID], H.Updated desc    PR - 03781
	return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [P_LogIn_DefCalc]
	@UserName as VarChar(50),
	@Password as VarChar(50)
as 
	declare @UpdateDate as datetime
	declare @UseDate as datetime

	set @UseDate = GetDate()

	Set @Password = replace(isnull(char(ASCII(SUBSTRING(reverse(@Password), 1, 1)) - 10), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 2, 1)) - 11), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 3, 1)) - 12), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 4, 1)) - 13), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 5, 1)) - 14), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 6, 1)) - 15), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 7, 1)) - 16), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 8, 1)) - 17), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 9, 1)) - 18), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 10, 1)) - 19), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 11, 1)) - 20), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 12, 1)) - 21), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 13, 1)) - 22), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 14, 1)) - 23), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 15, 1)) - 24), ''), '               ', '')

	--RM - Created to stop the Deficiency Days Calculation from causing the Log in the Time Ou
	set @Updatedate = isnull((select top 1 Updated from dbo.Def_CountUpdate order by updated desc), '1990/01/01')
	if datediff(dd, @Updatedate, getdate()) > 0
	begin
		exec C_DefCount 0
		--PR - 01072
		exec P_ResetProviderStatus 0
		insert into Def_CountUpdate select top 1 code, getdate() from U_Users where Code <> 1 and UserName = @UserName and UserPassword = @Password and ([ValidFrom] <= @UseDate) AND (@UseDate <= [ValidTo])
	end



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE       PROCEDURE [P_LookUpApp]
	@SearchString as VarChar(50),
	@SearchCode as VarChar(50) = '0'
AS 
	IF @SearchCode <> '0'
		BEGIN
			SELECT [Code] AS [ ], [ModuleName] AS [Module Name]
			FROM U_AppIDs
			WHERE [Code] = @SearchCode
			RETURN 1
		END
	ELSE IF @SearchString = ''
		BEGIN
			SELECT [Code] AS [ ], [ModuleName] AS [Module Name]
			FROM U_AppIDs
			WHERE AppID <= 1100 or appid in (1500, 1104, 1002, 1200, 40000, 40001)
			ORDER BY [ModuleName]
			RETURN 1
		END
	ELSE
		BEGIN	
			SELECT [Code] AS [ ], [ModuleName] AS [Module Name]
			FROM U_AppIDs
			WHERE (AppID <= 1100 or appid in (1500, 1104, 1002, 1200, 40000, 40001))
			AND [ModuleName] LIKE '%' + @SearchString + '%' ORDER BY [ModuleName]
			RETURN 1
		END


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- exec P_LookUpAssociate 'H_InstitutionProfile', '5', '0', '2012/04/01', '0', '0'

CREATE  PROCEDURE [P_LookUpAssociate]
	@SearchTable as varchar(50),
	@SearchString as varchar(50),
	@SearchCode as varchar(50) = '0',
	@UseDate as varchar(10),
	@AssocID as varchar(10),
	@HospID as varchar(100) = '0'
AS 

declare @return int
declare @sql varchar(5000)
declare @s varchar(2500)
declare @w varchar(2400)
declare @o varchar(100)

set @s = 'select 
			[Code] as [ ], 
            [LUText] as [l],
			(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],   
            [DisplayCode] as [Code Value],
			[UserDescription] as [Hospital Description], 
            [DefaultDescription] as [Default Description],
			[CIHIValue] as [CIHI Value], 
            convert(varchar(10), [Validfrom], 111) as [Valid from],
			convert(varchar(10), [ValidTo], 111) as [Valid To] 
        from ' + @SearchTable + ' lt '

set @o = ' order by [DisplayCode] '

if @SearchCode <> '0'
	set @w = ' where [Code] =  ' + @SearchCode 

else
begin
	set @w = ' where ([Validfrom] <= ''' + @UseDate + ''') 
		and (''' + @UseDate + ''' <= [ValidTo]) 
		and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
	--RM: Decided against this change (I just made the DataType 50 for CJRR Inst#
	--if @AssocID <> '0' --SP-01071: If there is no AssociationID value then show all the codes
	set @w = @w + ' and [AssociationID] = ' + @AssocID 

	if len(@SearchString) > 0
	begin
		execute @return = P_CheckLUDisplayCode @SearchTable, @SearchString, @UseDate, @HospID --PR-02277
		if @return <> 0 
			set @w = @w + ' and [DisplayCode] like ''%' + @SearchString + '%'''
		else
		begin
			set @w = @w + ' and [UserDescription] like ''%' + @SearchString + '%'''
			set @o = ' order by [UserDescription] '
		end		
	end
end

set @sql = @s + @w + @o
--print @sql
execute (@sql)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [P_LookUpAssociateNoCIHI]
	@SearchTable as varchar(50),
	@SearchString as varchar(50),
	@SearchCode as varchar(50) = '0',
	@UseDate as varchar(10),
	@AssocID as varchar(10)
AS 

declare @return int
declare @sql varchar(5000)
declare @s varchar(2500)
declare @w varchar(2400)
declare @o varchar(100)
    
set @s = 'select [Code] as [ ], 
		[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
                [DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description], 
		convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To] 				
	from ' + @SearchTable + ' lt '

set @o = + ' order by [DisplayCode] '

if @SearchCode <> '0'
	set @w =' where [Code] = ' + @SearchCode 

else if @SearchString = ''
	set @w = ' where ([Validfrom] <= ''' + @UseDate + ''') 
                	and (''' + @UseDate + ''' <= [ValidTo]) 
                	and [AssociationID] = ' + @AssocID  
else
begin	
	execute @return = P_CheckLUDisplayCode @SearchTable, @SearchString, @UseDate --PR-02277

	if @return <> 0 
		set @w = ' where ([Validfrom] <= ''' + @UseDate + ''') 
                	and (''' + @UseDate + ''' <= [ValidTo]) 
                	and [DisplayCode] like ''%' + @SearchString + '%''  
                	and [AssociationID] = ' + @AssocID 
    	else
	begin
		set @w = ' where ([Validfrom] <= ''' + @UseDate + ''') 
                	and (''' + @UseDate + ''' <= [ValidTo]) 
			and [UserDescription] like ''%' + @SearchString + '%'' 
                	and [AssociationID] = ' + @AssocID 
            
            	set @o = ' order by [UserDescription] '
	end
end

set @sql = @s + @w + @o
execute (@sql)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [P_LookUpAttribAssociate]
	@SearchTable as VarChar(50),
	@SearchString as VarChar(50),
	@SearchCode as VarChar(50) = '0',
	@UseDate as VarChar(10),
	@AssocID as VarChar(10),
	@Sector as VarChar(1)
AS 

declare @return int
declare @sql varchar(5000)
declare @s varchar(2500)
declare @w varchar(2400)
declare @o varchar(100)

set @s = 'select [Code] as [ ], 
        	[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
        	[DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description], 
        	[DefaultDescription] as [Default Description],
		[CIHIValue] as [CIHI Value], 
        	convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To] 				
	from ' + @SearchTable + ' lt '

set @o = ' order by [DisplayCode] '

if @SearchCode <> '0' 
    	set @w = ' where [Code] = ' + @SearchCode 

else if @SearchString = '' 
	set @w = ' where [AssociationID] = ' + @AssocID + ' 
            		and (isnull(Sector, 0) in (0, 3, ' + @Sector + '))
            		and ([Validfrom] <= ''' + @UseDate + ''') 
            		and (''' + @UseDate + ''' <= [ValidTo]) '
else
begin	
	execute @return = P_CheckLUDisplayCode @SearchTable, @SearchString, @UseDate --PR-02277

	if @return <> 0 
		set @w = ' where [DisplayCode] like ''%' + @SearchString + '%''  
                	and [AssociationID] = ' + @AssocID + ' 
                	and (isnull(Sector, 0) in (0, 3, ' + @Sector + '))
                	and ([Validfrom] <= ''' + @UseDate + ''') 
                	and (''' + @UseDate + ''' <= [ValidTo]) '
	else
	begin
		set @w = ' where [UserDescription] like ''%' + @SearchString + '%'' 
                	and [AssociationID] = ' + @AssocID + ' 
                	and (isnull(Sector, 0) in (0, 3,  ' + @Sector + ' ))
                	and ([Validfrom] <= ''' + @UseDate + ''') 
                	and (''' + @UseDate + ''' <= [ValidTo])  '

    		set @o = 'order by [UserDescription]'
	end
end

set @sql = @s + @w + @o
execute (@sql)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [P_LookUpAutoBorrower]
	@SearchString as VarChar(50),
	@SearchCode as int = 0,
	@UseDate as DateTime,
	@HospID as int = 0
AS 

if @SearchCode <> 0
	select [Code] as [ ], 
        	[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		[DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description], 
		convert (varchar(10), [Validfrom], 111) as [Valid from],
		convert (varchar(10), [ValidTo], 111) as [Valid To] 				
	from LoanLU_Borrower lt
	where [Code] = @SearchCode 

else if @SearchString = ''
	select [Code] as [ ], 
        	[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		[DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description], 
		convert (varchar(10), [Validfrom], 111) as [Valid from],
		convert (varchar(10), [ValidTo], 111) as [Valid To] 				
	from LoanLU_Borrower lt
	where ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	order by [DisplayCode]

else
	select [Code] as [ ], 
        	[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		[DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description], 
		convert (varchar(10), [Validfrom], 111) as [Valid from],
		convert (varchar(10), [ValidTo], 111) as [Valid To] 				
	from LoanLU_Borrower lt
	where ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
	and [DisplayCode] = @SearchString
	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	order by [DisplayCode]


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_LookUpAutoRequestor]
	@SearchString as VarChar(50),
	@SearchCode as int = 0,
	@UseDate as DateTime,
	@HospID as int = 0
AS 

if @SearchCode <> 0
	select [Code] as [ ], 
    		[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		[DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description], 
		convert (varchar(10), [Validfrom], 111) as [Valid from],
		convert (varchar(10), [ValidTo], 111) as [Valid To] 				
	from LU_ROI_Requesters lt
	where [Code] = @SearchCode 

else if @SearchString = ''
	select [Code] as [ ], 
    		[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		[DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description], 
		convert (varchar(10), [Validfrom], 111) as [Valid from],
		convert (varchar(10), [ValidTo], 111) as [Valid To] 				
	from LU_ROI_Requesters lt
	where ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	order by [DisplayCode]

else
	select [Code] as [ ], 
    		[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		[DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description], 
		convert (varchar(10), [Validfrom], 111) as [Valid from],
		convert (varchar(10), [ValidTo], 111) as [Valid To] 				
	from LU_ROI_Requesters lt 
	where ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
	and [DisplayCode] = @SearchString
	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	order by [DisplayCode]   


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_LookUpBasicOptions]
	@SearchTable as VarChar(50),
	@SearchString as VarChar(50),
	@SearchCode as VarChar(50) = '0',
	@UseDate as VarChar(10),
	@FieldLength as Int, 
	@AssociationID as VarChar(10)
AS 

declare @return int
declare @sql varchar(5000)
declare @s VarChar(2000)
declare @w VarChar(2500)
declare @o VarChar(500)

set @s = 'select 
		[Code] as [ ], 
		[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
        	[DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description], 
        	[DefaultDescription] as [Default Description],
		[CIHIValue] as [CIHI Value], 
        	convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To] 				
	from ' + @SearchTable + ' lt '

	set @o = ' order by [DisplayCode]'

if @SearchCode <> '0'
	set @w = ' where [Code] = ' + @SearchCode + ' 
            		and ([Validfrom] <= ''' + @UseDate + ''') 
            		and (''' + @UseDate + ''' <= [ValidTo])'

else if @SearchString = ''
	set @w = ' where ([Validfrom] <= ''' + @UseDate + ''') 
    			and (''' + @UseDate + ''' <= [ValidTo]) 
            		and AssociationID = ' + @AssociationID 
else
	--PR-00605 (changed @s to @w)
	set @w = ' where ([Validfrom] <= ''' + @UseDate + ''') 
    			and (''' + @UseDate + ''' <= [ValidTo]) 
    			and [DisplayCode] = '''+ @SearchString + ''' 
            		and AssociationID = ' + @AssociationID 

set @sql = @s + @w + @o
execute (@sql)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


--exec P_LookUpBatchInstNumber '51238', 0, '2009/08/31', 31, 2844
-- Called by Batch Grouper to Filter out the Inst Numbers based on CareTypes allowed for Groupers Modules.
CREATE    PROCEDURE [P_LookUpBatchInstNumber]
	@SearchString as VarChar(50),
	@SearchCode as int = 0,
	@UseDate as VarChar(10),
	@AssocID as int,
	@HospID as int = 0
AS 

declare @Assoc1 as int
declare @Assoc2 as int 
declare @Assoc3 as int
declare @Assoc4 as int
declare @Assoc5 as int 
declare @Assoc6 as int --ED-02030

declare @return int

select @Assoc1 = 1 -- Inpatient
if not ( (1 & @AssocID) = 1 ) set @Assoc1 = 0

select @Assoc2 = 2 -- SDS
if not ( (2 & @AssocID) = 2 ) set @Assoc2 = 0

select @Assoc3 = 5 -- NACRS
if not ( (4 & @AssocID) = 4 )
begin
    set @Assoc2 = 0     --2011 the DPG is dead. Use CACS
    set @Assoc3 = 0
end

select @Assoc4 = 4 -- CCRS
if not ( (8 & @AssocID) = 8 ) set @Assoc4 = 0

select @Assoc5 = 3 -- NRS
if not ( (16 & @AssocID) = 16 ) set @Assoc5 = 0

select @Assoc6 = 7 -- OMHRS
if not ( (32 & @AssocID) = 32 ) set @Assoc6 = 0

if @SearchCode <> 0
	select 
		[Code] as [ ],  
    		[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
    		[DisplayCode] as [Code Value], 
		[UserDescription] as [Hospital Description], 
    		[DefaultDescription] as [Default Description], 
    		[CIHIValue] as [CIHI Value], 
    		convert(varchar(10), [Validfrom], 111) as [Valid from], 
    		convert(varchar(10), [ValidTo], 111) as [Valid To] 				
	from H_InstitutionProfile lt
	where [Code] =  @SearchCode
	order by [DisplayCode]

else if @SearchString = ''
	select 
		[Code] as [ ],  
    		[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
    		[DisplayCode] as [Code Value], 
    		[UserDescription] as [Hospital Description], 
    		[DefaultDescription] as [Default Description], 
    		[CIHIValue] as [CIHI Value], 
    		convert(varchar(10), [Validfrom], 111) as [Valid from], 
    		convert(varchar(10), [ValidTo], 111) as [Valid To] 				
	from H_InstitutionProfile lt
	where ([AssociationID] = @Assoc1 
    	or [AssociationID] = @Assoc2  
    	or [AssociationID] = @Assoc3 
    	or [AssociationID] = @Assoc4
	or [AssociationID] = @Assoc5
	or [AssociationID] = @Assoc6)
	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)		
	order by [DisplayCode]

else
begin	
	execute @return = P_CheckLUDisplayCode  'H_InstitutionProfile', @SearchString, @UseDate, @HospID --PR-02277
	
	if @return <> 0 
		select 
			[Code] as [ ],  
	        	[LUText] as [l],
			(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
	        	[DisplayCode] as [Code Value], 
	        	[UserDescription] as [Hospital Description], 
	        	[DefaultDescription] as [Default Description], 
	        	[CIHIValue] as [CIHI Value], 
	        	convert(varchar(10), [Validfrom], 111) as [Valid from], 
	        	convert(varchar(10), [ValidTo], 111) as [Valid To] 				
		from H_InstitutionProfile lt
	    	where [DisplayCode] like '%' + @SearchString + '%'  
	    	and ([AssociationID] = @Assoc1 
	        or [AssociationID] = @Assoc2  
	        or [AssociationID] = @Assoc3 
	        or [AssociationID] = @Assoc4
		or [AssociationID] = @Assoc5
		or [AssociationID] = @Assoc6) 
		and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by [DisplayCode]
	
	else
		select 
			[Code] as [ ],  
	        	[LUText] as [l],
			(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
	        	[DisplayCode] as [Code Value], 
	        	[UserDescription] as [Hospital Description], 
	        	[DefaultDescription] as [Default Description], 
	        	[CIHIValue] as [CIHI Value], 
	        	convert(varchar(10), [Validfrom], 111) as [Valid from], 
	        	convert(varchar(10), [ValidTo], 111) as [Valid To] 				
		from H_InstitutionProfile lt
	    	where [UserDescription] like '%' + @SearchString + '%' 
	    	and ([AssociationID] = @Assoc1 
	        or [AssociationID] = @Assoc2  
	        or [AssociationID] = @Assoc3 
	        or [AssociationID] = @Assoc4
		or [AssociationID] = @Assoc5 
		or [AssociationID] = @Assoc6)
		and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by [UserDescription]
end


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- Called by Batch Grouper to Filter out the Batch Years based on Care Type & ICD Type
CREATE      PROCEDURE [P_LookUpBatchYear]
	@SearchString as VarChar(4),
	@SearchCode as int = 0,
	@AssocID as VarChar(2),
	@MinYear as int
AS 

	DECLARE @CareType as int
	DECLARE @ICDType as varchar(1)

	SELECT @CareType = LEFT(@AssocID, 1)
	SELECT @ICDType = RIGHT(@AssocID, 1)

	IF @SearchCode <> 0
		SELECT [Code] AS [ ], [BatchYear] AS [Year], 'Batch Year: ' + [BatchYear] AS [Description] FROM LLU_BatchYears WHERE [Code] = @SearchCode

	ELSE IF @SearchString = ''
		SELECT [Code] AS [ ], [BatchYear] AS [Year], 'Batch Year: ' + [BatchYear] AS [Description] FROM LLU_BatchYears WHERE [CareType] = @CareType AND [ICDType] = @ICDType and BatchYear >= @MinYear ORDER BY [BatchYear]
	
	ELSE
		SELECT [Code] AS [ ], [BatchYear] AS [Year], 'Batch Year: ' + [BatchYear] AS [Description] FROM LLU_BatchYears WHERE [BatchYear] LIKE '%' + @SearchString + '%'  AND ([CareType] = @CareType AND [ICDType] = @ICDType) and BatchYear >= @MinYear ORDER BY [BatchYear]




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [P_LookUpBorrow]
	@SearchString as varchar(50),
	@SearchCode as varchar(50) = '0',
	@UseDate as DateTime,
	@HospID as int = 0
as 

declare @return int

if @SearchCode <> '0'
	select 
		[Code] as [ ], 
    		[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		[DisplayCode] as [Code Value],
		[UserDescription] as [Borrower Name], 
		convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To] 				
	from LoanLU_Borrower lt
	where [Code] = @SearchCode
	and ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) 

else if @SearchString = ''
	select 
		[Code] as [ ], 
    		[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		[DisplayCode] as [Code Value],
		[UserDescription] as [Borrower Name], 
		convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To] 
	from LoanLU_Borrower lt
	where ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
	and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	order by [DisplayCode]

else
begin	
	--2.x-1688 client mix displaycode with description and number. change to use both
	--execute @return = P_CheckLUDisplayCode 'LoanLU_Borrower', @SearchString, @UseDate, @HospID --PR-02277

	--if @return <> 0 
	--	select 
	--		[Code] as [ ], 
 --       		[LUText] as [l],
	--		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
	--		[DisplayCode] as [Code Value],
	--		[UserDescription] as [Borrower Name], 
	--		convert(varchar(10), [Validfrom], 111) as [Valid from],
	--		convert(varchar(10), [ValidTo], 111) as [Valid To] 
	--	from LoanLU_Borrower lt
	--	where ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
 --   		and [DisplayCode] like '%' + @SearchString + '%' 
	--	and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)	
	--	order by [DisplayCode]

	--else
		select 
			[Code] as [ ],  
        		[LUText] as [l],
			(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
			[DisplayCode] as [Code Value],
			[UserDescription] as [Borrower Name], 
			convert(varchar(10), [Validfrom], 111) as [Valid from],
			convert(varchar(10), [ValidTo], 111) as [Valid To] 
		from LoanLU_Borrower lt
		where ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
--		and ([UserDescription] like '%' + @SearchString + '%' or [DisplayCode] like '%' + @SearchString + '%' )
		and ([UserDescription] like '%' + replace(@SearchString, '''''', '''') + '%' or [DisplayCode] like '%' + replace(@SearchString, '''''', '''') + '%' )   --2.x-1688
		and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by [UserDescription]
end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO







CREATE   PROCEDURE [P_LookUpBorrowFull]
	@SearchString as VarChar(50),
	@SearchCode as VarChar(50) = '0',
	@HospID as int = 0
as 

declare @return int

if @SearchCode <> '0'
	select 
		[Code] as [ ], 
    		[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		[DisplayCode] as [Code Value],
		[UserDescription] as [Borrower Name], 
		convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To] 				
	from LoanLU_Borrower lt 
	where [Code] = @SearchCode

else if @SearchString = ''
	select 
		[Code] as [ ], 
    		[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		[DisplayCode] as [Code Value],
		[UserDescription] as [Borrower Name], 
		convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To] 
	from LoanLU_Borrower lt
	where (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	order by [DisplayCode]

else
begin	
	execute @return = P_CheckLUDisplayCode 'LoanLU_Borrower', @SearchString, 'NO DATE', @HospID --PR-02277

	if @return <> 0 
		select 
			[Code] as [ ], 
        		[LUText] as [l],
			(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
			[DisplayCode] as [Code Value],
			[UserDescription] as [Borrower Name], 
			convert(varchar(10), [Validfrom], 111) as [Valid from],
			convert(varchar(10), [ValidTo], 111) as [Valid To] 
		from LoanLU_Borrower lt
		where 
-- PR - 02277
    		([DisplayCode] like '%' + @SearchString + '%' 
                or [UserDescription] like '%' + @SearchString + '%' )
--[DisplayCode] like '%' + @SearchString + '%' 
		and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by [DisplayCode]
	else
		select 
			[Code] as [ ],  
        		[LUText] as [l],
			(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
			[DisplayCode] as [Code Value],
			[UserDescription] as [Borrower Name], 
			convert(varchar(10), [Validfrom], 111) as [Valid from],
			convert(varchar(10), [ValidTo], 111) as [Valid To] 
		from LoanLU_Borrower lt
		where [UserDescription] like '%' + @SearchString + '%' 
		and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by [UserDescription]
end






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_LookUpCCMVisit]
	@SearchCode as Integer,
	@ChartNumber as varchar(10),
	@HCN as varchar(12),
	@HospID as int = 0
AS 
set nocount on

declare @count int

Create TABLE #visit(
	[UniversalID] [bigint],
	[AbstractID] [int],
    [AppID] int,
	[Hospital] [varchar] (250) COLLATE Latin1_General_CI_AS  ,
    VisitDate datetime,
	[CareType] [varchar] (250) COLLATE Latin1_General_CI_AS  ,
	Problem [varchar] (250) COLLATE Latin1_General_CI_AS  ,
) 

Create TABLE #RegionalPatientID(
	[RegionalPatientID] [varchar] (50) COLLATE Latin1_General_CI_AS  
) 

if @SearchCode <> 0
begin
    insert into #visit(UniversalID, AbstractID, AppID, Hospital, VisitDate, CareType, Problem)
 	select 
 		UniversalID, AbstractID, AppID, 
 		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)),
 		VisitDate,  
 		'Inst:' + isnull(H.CIHIValue, ''), 
 		''
	from AB_Main lt
        left join H_InstitutionProfile h on lt.InstitutionNumber = h.code
	where UniversalID = @SearchCode
	and isnull(IsDeleted, 0) = 2 and AppType = 8
--	order by [Visit Date] desc
end

else
begin
    set @count = 0
    if len(isnull(@HCN, '')) > 1
    begin
        insert into #visit(UniversalID, AbstractID, AppID, Hospital, VisitDate, CareType, Problem)
 	    select 
 		    UniversalID, AbstractID, AppID, 
 		    (select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)),
 		    VisitDate,  
 		    'Inst:' + isnull(H.CIHIValue, '') , 
 		    ''
	    from AB_Main lt
	        left join H_InstitutionProfile h on lt.InstitutionNumber = h.code
	    where HealthCareNumber = @HCN
	    --and (isnull(lt.HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(lt.HospitalID, 0) end) 	
	    and isnull(IsDeleted, 0) = 2 and AppType = 8
	    set @count = @@Rowcount
    end
    if @count = 0
    begin
        insert into #visit(UniversalID, AbstractID, AppID, Hospital, VisitDate, CareType, Problem)
 	    select 
 		    UniversalID, AbstractID, AppID, 
 		    (select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)),
 		    VisitDate,  
 		    'Inst:' + isnull(H.CIHIValue, '') , 
 		    ''
	    from AB_Main lt
            left join H_InstitutionProfile h on lt.InstitutionNumber = h.code
	    where ChartNumber = @ChartNumber
	    and (isnull(lt.HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(lt.HospitalID, 0) end) --0824 allow hospital link	
	    and isnull(IsDeleted, 0) = 2 and AppType = 8
        --	order by [Visit Date] desc
	    set @count = @@Rowcount
    end
	-- 0771 add to search by regional patient ID
    if @count = 0 
    begin
		insert into #RegionalPatientID(RegionalPatientID) select RegionalPatientID from CM_cpi where ChartNumber = @ChartNumber and isnull(RegionalPatientID, '') <> ''
		if @@rowcount > 0
			insert into #visit(UniversalID, AbstractID, AppID, Hospital, VisitDate, CareType, Problem)
 			select 
 				UniversalID, AbstractID, AppID, 
 				(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)),
 				VisitDate,  
 				'Inst:' + isnull(H.CIHIValue, '') , 
 				''
			from AB_Main lt
				inner join CM_cpi cm on lt.ChartNumber = cm.ChartNumber 
				inner join #RegionalPatientID r on cm.RegionalPatientID = r.RegionalPatientID
				left join H_InstitutionProfile h on lt.InstitutionNumber = h.code
			where AppType = 8 and isnull(lt.IsDeleted, 0) = 2
			--and (isnull(lt.HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(lt.HospitalID, 0) end) 	
				
			--	order by [Visit Date] desc
    end
end

delete from #visit
from  #visit z
    left join dbo.CC_DiseaseRegister r on z.AbstractID = r.AbstractID
where r.AbstractID is null

Update #visit
set AppID = isnull(DiseaseSequenceNum, 1),
    CareType = CareType + ', Seq:' + cast(isnull(DiseaseSequenceNum, 1) as varchar(20)),
    VisitDate = convert(varchar(20), r.RegisterDate, 111),
    Problem = isnull(ltrim(rtrim(d.DisplayCode)) + '-' + d.UserDescription, '')
from  #visit z
    inner join dbo.CC_DiseaseRegister r on z.AbstractID = r.AbstractID
    left join ICD_DiagFile10 d on r.DiagnosisCode = d.code
  

select 
	UniversalID, 
	cast(AppID as varchar(20)) as [LUText], 
	Hospital as [H Link],
	VisitDate as [Register Date],  
	CareType + ', Problem: ' + Problem as [CCM Information]
from #visit
order by AppID desc, visitdate desc

set nocount off

return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [P_LookUpChart]
    @SearchCode as Integer,
    @SearchString as VarChar(50), 
    @SearchString2 as VarChar(50),
    @HospID as int = 0,
    @AccessLockChart as int = 1,
	@VIP int = 0
AS 

if @SearchCode <> 0
   select 
	PatientID, 
	'' as LUText, 
	(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
	ChartNumber, 
	isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') as [Patient Name]
   from CM_CPI lt
	    left join LU_YesBlank s on lt.[Secret] = s.code
   where PatientID = @SearchCode
    and (@VIP = 1 or isnull(s.CIHIValue, 0) not in ('1', 'Y'))
else
   select top 999 
	PatientID, 
	'' as LUText, 
	(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
	ChartNumber, 
	isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(MiddleName, '') as [Patient Name]
   from CM_CPI lt
	    left join LU_YesBlank s on lt.[Secret] = s.code
   where (ChartNumber like @SearchString + '%' or ChartNumber like @SearchString2 + '%')
   and (isnull(lt.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(lt.HospitalID, 0) end) 	
    --PR-01006
    and ((LastName not like '%merged%' and FirstName not like '%merged%') or @AccessLockChart = 1)
    and (@VIP = 1 or isnull(s.CIHIValue, 0) not in ('1', 'Y'))
return 0


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_LookUpCharts]
	@SearchCode as varchar(10),
	@SearchString as varchar(50), 
	@HospID as int = 0,
	@VIP int = 0
as 
	
declare @count as integer

if len(@SearchCode) <> 0
	select 
		PatientID, 
    		'' as [  ],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		ChartNumber as [Chart Number], 
		isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(Middlename, '') as [Patient Name],
		(select DisplayCode from LU_Gender_I where Code = Gender) as [Gender],
		convert(varchar(10), BirthDate, 111) as [Birthdate],
		HealthCareNumber,
		HCNVersion
	from CM_CPI lt
	    left join LU_YesBlank s on lt.[Secret] = s.code
	where (ChartNumber = @SearchCode or ChartNumber = ' ' + replace(space(9-len(@SearchCode)) + @SearchCode, ' ', '0'))
	and (isnull(lt.HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(lt.HospitalID, 0) end)			
    and (@VIP = 1 or isnull(s.CIHIValue, 0) not in ('1', 'Y'))
else if len(@SearchString) = 0 --EN-00303
	select 
		PatientID, 
    		'' as [  ],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		ChartNumber as [Chart Number], 
		isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(Middlename, '') as [Patient Name],
		(select DisplayCode from LU_Gender_I where Code = Gender) as [Gender],
		convert(varchar(10), BirthDate, 111) as [Birthdate],
		HealthCareNumber,
		HCNVersion
	from CM_CPI lt
	where 1 = 2
else
begin
	select @count = count(ChartNumber) from CM_CPI where ChartNumber like @SearchString + '%' and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end) --PR-02277
	
	if @count > 0
		select 
			PatientID, 
        		'' as [  ],
			(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
			ChartNumber as [Chart Number], 
			isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(Middlename, '') as [Patient Name],
			(select DisplayCode from LU_Gender_I where Code = Gender) as [Gender],
			convert(varchar(10), BirthDate, 111) as [Birthdate],
			HealthCareNumber,
			HCNVersion
		from CM_CPI lt
    	    left join LU_YesBlank s on lt.[Secret] = s.code
		where ChartNumber like @SearchString + '%' 
		and (isnull(lt.HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(lt.HospitalID, 0) end)
        and (@VIP = 1 or isnull(s.CIHIValue, 0) not in ('1', 'Y'))
		order by [ChartNumber]
	else
		select 
			PatientID, 
        		'' as [  ],
			(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
			ChartNumber as [Chart Number], 
			isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(Middlename, '') as [Patient Name],
			(select DisplayCode from LU_Gender_I where Code = Gender) as [Gender],
			convert(varchar(10), BirthDate, 111) as [Birthdate],
			HealthCareNumber,
			HCNVersion
		from CM_CPI lt
    	    left join LU_YesBlank s on lt.[Secret] = s.code
		where LastName like @SearchString + '%' 
		and (isnull(lt.HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(lt.HospitalID, 0) end)					
        and (@VIP = 1 or isnull(s.CIHIValue, 0) not in ('1', 'Y'))
		order by [LastName]
end




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_LookUpCharts_CPI]
	@SearchCode as varchar(10),
	@SearchString as varchar(50), 
	@HospID as int = 0,
	@VIP int = 0
as 

--PR-02117	
declare @count as integer

if len(@SearchCode) <> 0
	select 
		PatientID, 
    		'' as [  ],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		ChartNumber as [Chart Number], 
		isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(Middlename, '') as [Patient Name],
		(select DisplayCode from LU_Gender_I where Code = Gender) as [Gender],
		convert(varchar(10), BirthDate, 111) as [Birthdate],
		HealthCareNumber,
		HCNVersion
	from CM_CPI lt
	    left join LU_YesBlank s on lt.[Secret] = s.code
	where (ChartNumber = @SearchCode or ChartNumber = ' ' + replace(space(9-len(@SearchCode)) + @SearchCode, ' ', '0'))
	and (isnull(lt.HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(lt.HospitalID, 0) end)			
    and (@VIP = 1 or isnull(s.CIHIValue, 0) not in ('1', 'Y'))
    order by isnull((case when @HospID > 0 then 0 - lt.HospitalID else lt.HospitalID end), 0)
else
	select 
		PatientID, 
		'' as [  ],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		ChartNumber as [Chart Number], 
		isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(Middlename, '') as [Patient Name],
		(select DisplayCode from LU_Gender_I where Code = Gender) as [Gender],
		convert(varchar(10), BirthDate, 111) as [Birthdate],
		HealthCareNumber,
		HCNVersion
	from CM_CPI lt
	    left join LU_YesBlank s on lt.[Secret] = s.code
	where ChartNumber = @SearchString 
	and (isnull(lt.HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(lt.HospitalID, 0) end)
    and (@VIP = 1 or isnull(s.CIHIValue, 0) not in ('1', 'Y'))
	order by [ChartNumber], isnull((case when @HospID > 0 then 0 - lt.HospitalID else lt.HospitalID end), 0)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_LookUpCharts_Merge]
	@SearchCode as varchar(10),
	@PatientID  as varchar(50), 
	@HospID     as int = 0
as 
	
declare @count as integer
if isnull(@PatientID, 0) = 0
    select 
	    PatientID, 
	    isnull(HospitalID, 0) as HospitalID, 
	    (select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
	    ChartNumber as [Chart Number], 
	    isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(Middlename, '') as [Patient Name],
	    (select DisplayCode from LU_Gender_I where Code = Gender) as [Gender],
	    convert(varchar(10), BirthDate, 111) as [Birth date],
	    HealthCareNumber as [Health Care Number]
    from CM_CPI lt
    where (ChartNumber = @SearchCode or ChartNumber = ' ' + replace(space(9-len(@SearchCode)) + @SearchCode, ' ', '0')) 
        and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)			
else
    select 
	    PatientID, 
	    isnull(HospitalID, 0) as HospitalID, 
	    (select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
	    ChartNumber as [Chart Number], 
	    isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(Middlename, '') as [Patient Name],
	    (select DisplayCode from LU_Gender_I where Code = Gender) as [Gender],
	    convert(varchar(10), BirthDate, 111) as [Birth Date],
	    HealthCareNumber as [Health Care Number]
    from CM_CPI lt
    where PatientID = @PatientID 






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [P_LookUpCharts_Merge_RegionalID]
	@SearchCode as varchar(10),
	@PatientID  as varchar(50)
as 
	
declare @count as integer
if isnull(@PatientID, 0) = 0
    select 
	    PatientID, 
	    isnull(RegionalPatientID, '') as RegionalID, 
	    (select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
	    ChartNumber as [Chart Number], 
	    isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(Middlename, '') as [Patient Name],
	    (select DisplayCode from LU_Gender_I where Code = Gender) as [Gender],
	    convert(varchar(10), BirthDate, 111) as [Birth date],
	    HealthCareNumber as [Health Care Number]
    from CM_CPI lt
    where (ChartNumber = @SearchCode or ChartNumber = ' ' + replace(space(9-len(@SearchCode)) + @SearchCode, ' ', '0')) 
else
    select 
	    PatientID, 
	    isnull(RegionalPatientID, '') as RegionalID, 
	    (select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
	    ChartNumber as [Chart Number], 
	    isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(Middlename, '') as [Patient Name],
	    (select DisplayCode from LU_Gender_I where Code = Gender) as [Gender],
	    convert(varchar(10), BirthDate, 111) as [Birth Date],
	    HealthCareNumber as [Health Care Number]
    from CM_CPI lt
    where PatientID = @PatientID 






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






CREATE PROCEDURE [P_LookUpCharts_NoAccess]
	@SearchCode as varchar(10),
	@SearchString as varchar(50), 
	@HospID as int = 0
as 
	
declare @count as integer

if len(@SearchCode) <> 0
	select 
		PatientID, 
    		'' as [  ],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		ChartNumber as [Chart Number], 
		isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(Middlename, '') as [Patient Name],
		(select DisplayCode from LU_Gender_I where Code = Gender) as [Gender],
		convert(varchar(10), BirthDate, 111) as [Birthdate],
		HealthCareNumber,
		HCNVersion
	from CM_CPI lt
	where (ChartNumber = @SearchCode or ChartNumber = ' ' + replace(space(9-len(@SearchCode)) + @SearchCode, ' ', '0'))
	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	and (LastName not like '%merged%' and FirstName not like '%merged%') 			

else if len(@SearchString) = 0 --EN-00303
	select 
		PatientID, 
    		'' as [  ],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		ChartNumber as [Chart Number], 
		isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(Middlename, '') as [Patient Name],
		(select DisplayCode from LU_Gender_I where Code = Gender) as [Gender],
		convert(varchar(10), BirthDate, 111) as [Birthdate],
		HealthCareNumber,
		HCNVersion
	from CM_CPI lt
	where 1 = 2

else
begin
	select @count = count(ChartNumber) from CM_CPI where ChartNumber like @SearchString + '%' and (LastName not like '%merged%' and FirstName not like '%merged%') and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end) --PR-02277			
	if @count > 0
		select 
			PatientID, 
        		'' as [  ],
			(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
			ChartNumber as [Chart Number], 
			isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(Middlename, '') as [Patient Name],
			(select DisplayCode from LU_Gender_I where Code = Gender) as [Gender],
			convert(varchar(10), BirthDate, 111) as [Birthdate],
			HealthCareNumber,
			HCNVersion
		from CM_CPI lt
		where ChartNumber like @SearchString + '%' 
		and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		and (LastName not like '%merged%' and FirstName not like '%merged%') 			
		order by [ChartNumber]
	else
		select 
			PatientID, 
        		'' as [  ],
			(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
			ChartNumber as [Chart Number], 
			isnull(LastName, '') + ', ' + isnull(FirstName, '') + ' ' + isnull(Middlename, '') as [Patient Name],
			(select DisplayCode from LU_Gender_I where Code = Gender) as [Gender],
			convert(varchar(10), BirthDate, 111) as [Birthdate],
			HealthCareNumber,
			HCNVersion
		from CM_CPI lt
		where LastName like @SearchString + '%' 
		and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)					
		and (LastName not like '%merged%' and FirstName not like '%merged%') 			
		order by [LastName]
end





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


--exec P_LookUpCIHI 'LU_MISCode', '713', '2099/03/31', 0 




CREATE   PROCEDURE [P_LookUpCIHI] 
	@SearchTable as varchar(50),
	@SearchString as varchar(50),
	@UseDate as varchar(10),
	@HospID as varchar(100) = '0'
AS 

	declare @Return int
	declare @sql varchar(3000)
	declare @s varchar(500)
	declare @w varchar(2400)
	declare @o varchar(100)

    set @s = 'select distinct [CIHIValue] as [CIHI Value], 
				[DefaultDescription] AS [Default Description]
			from ' + @SearchTable  
    
    set @o = ' order by [CIHIValue] '

    if @SearchString = ''
        set @w = ' where (''' + @UseDate + ''' <= [ValidTo])  
			and (isnull(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
	
	else
	begin	
	    execute @Return = P_CheckLUCIHICode @SearchTable, @SearchString, @UseDate, @HospID --PR-02277

		if @Return <> 0 
			set @w = ' where [CIHIValue] like ''%' + @SearchString + '%'' 
			and (isnull(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '

		else
		begin
			set @w = ' where [DefaultDescription] like ''%' + @SearchString + '%'' 
			and (isnull(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
            
            set @o = ' order by [DefaultDescription] '
		end
    end

    set @sql = @s + @w + @o
    execute (@sql)	   





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE  PROCEDURE [P_LookUpCIHI_CF]
	@LookUpID as int,
	@SearchString as VarChar(50),
	@UseDate as VarChar(10),
	@HospID as int = 0
as 

	declare @Return int

    if @SearchString = ''
		select distinct [CIHIValue] as [CIHI Value], 
			[DefaultDescription] as [Default Description]
		from LU_CodeFile 
        where [LookUpID] = @LookUpID 
        and (@UseDate <= [ValidTo])  
		and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by [CIHIValue]
	
	else
	begin	
		execute @Return = P_CheckLUCIHICodeCF @LookUpID, @SearchString, @UseDate, @HospID --PR-02277

		if @Return <> 0 
			select distinct [CIHIValue] as [CIHI Value], 
    			[DefaultDescription] as [Default Description]
			from LU_CodeFile 
            where [LookUpID] = @LookUpID 
            and [CIHIValue] like '%' + @SearchString + '%' 
			and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
			order by [CIHIValue]

		else
		    select distinct [CIHIValue] as [CIHI Value], 
			    [DefaultDescription] as [Default Description]
			from LU_CodeFile
            where [LookUpID] = @LookUpID 
            and [DefaultDescription] like '%' + @SearchString + '%' 				
			and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
			order by [DefaultDescription]
    end




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE  PROCEDURE [P_LookUpCIHIAssociate]
	@SearchTable as varchar(50),
	@SearchString as varchar(50),
	@UseDate as varchar(10),
	@AssocID as varchar(50),
	@HospID as varchar(100) = '0'
AS 

    declare @Return int
	declare @sql varchar(3000)
    declare @s varchar(5000)
    declare @w varchar(5000)
    declare @o varchar(5000)
    
	set @s = 'select distinct [CIHIValue] as [CIHI Value], 
				[DefaultDescription] as [Default Description]
			  from ' + @SearchTable 

    set @o =  'order by [CIHIValue] ' 
	
    if @SearchString = ''
        set @w = ' where (''' + @UseDate + ''' <= [ValidTo])
					and [AssociationID] = ' + @AssocID + ' 
			        and (isnull(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
	
	else
	begin			
        execute @Return = P_CheckLUCIHICode @SearchTable, @SearchString, @UseDate, @HospID --PR-02277
		if @Return <> 0 
			set @w = ' where (''' + @UseDate + ''' <= [ValidTo]) 
				and [AssociationID] = ' + @AssocID + '
				and [CIHIValue] like ''%' + @SearchString + '%'' 
				and (isnull(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
		
        else
		begin
			set @w = ' where (''' + @UseDate + ''' <= [ValidTo]) 
				and [AssociationID] = ' + @AssocID + '
				and [DefaultDescription] like ''%' + @SearchString + '%'' 
				and (isnull(HospitalID, 0) = 0 OR ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '

			set @o = 'ORDER BY [DefaultDescription]'
		end
    end

    set @sql = @s + @w + @o
	execute (@sql)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_LookUpCodeFile]
	@LookupID as int,
	@SearchString as VarChar(50),
	@SearchCode as VarChar(50) = '0',
	@UseDate as VarChar(10),
	@HospID as int = 0
as 
declare @return int

if @SearchCode <> '0'
	select 
		[Code] as [ ], 
    		[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
    		[DisplayCode] as [Code Value],
	    	[UserDescription] as [Hospital Description], 
    		[DefaultDescription] as [Default Description],
	    	[CIHIValue] as [CIHI Value], 
    		convert(varchar(10), [Validfrom], 111) as [Valid from],
	    	convert(varchar(10), [ValidTo], 111) as [Valid To] 				
	from LU_CodeFile lt
	where [Code] = @SearchCode     
	and ([Validfrom] <= @UseDate) and (@UseDate<= [ValidTo])
	and LookupID = @LookupID 
	order by [DisplayCode]

else if @SearchString = ''
	select  
		[Code] as [ ], 
    		[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
    		[DisplayCode] as [Code Value],
	    	[UserDescription] as [Hospital Description],
    		[DefaultDescription] as [Default Description],
	    	[CIHIValue] as [CIHI Value], 
    		convert(varchar(10), [Validfrom], 111) as [Valid from],
	    	convert(varchar(10), [ValidTo], 111) as [Valid To] 
	from LU_CodeFile lt
	where ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
	and LookupID = @LookupID 
	and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	order by [DisplayCode]
else
begin
	if exists (select * from LU_CodeFile where LookUpID = @LookUpID and ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) and ([DisplayCode] like '%' + @SearchString + '%' or [CIHIValue] like '%' + @SearchString + '%') and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)) --PR-02277
		select  
			[Code] as [ ], 
        		[LUText] as [l],
			(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
        		[DisplayCode] as [Code Value],
		    	[UserDescription] as [Hospital Description], 
        		[DefaultDescription] as [Default Description],
		    	[CIHIValue] as [CIHI Value], 
        		convert(varchar(10), [Validfrom], 111) as [Valid from],
		    	convert(varchar(10), [ValidTo], 111) as [Valid To] 
		from LU_CodeFile lt
    		where ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
    		and ([DisplayCode] like '%' + @SearchString + '%' 
        	or [CIHIValue] like '%' + @SearchString + '%') 
		and LookupID = @LookupID 
		and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by [DisplayCode]
	else
		select 
			[Code] as [ ], 
        		[LUText] as [l],
			(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
        		[DisplayCode] as [Code Value],
		    	[UserDescription] as [Hospital Description], 
        		[DefaultDescription] as [Default Description],
		    	[CIHIValue] as [CIHI Value], 
        		convert(varchar(10), [Validfrom], 111) as [Valid from],
		    	convert(varchar(10), [ValidTo], 111) as [Valid To] 
		from LU_CodeFile lt
    		where ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
		and [UserDescription] like '%' + @SearchString + '%' 
    		and LookupID = @LookupID 
		and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by [UserDescription]
end



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





-- Called by the Look Up Maint. - Main. (Different from Standard LU because there
-- is no filtering by Valid Date from/Valid Date To)
CREATE  PROCEDURE [P_LookUpCodeFileMaint]
	@LookUpID as int,
	@SearchString as VarChar(50),
	@SearchCode as VarChar(50) = '0',
	@HospID as int = 0
as 

declare @return int

if @SearchCode <> '0'
	select 
		[Code] as [ ], 
    		[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		[DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description], 
		[DefaultDescription] as [Default Description],
		[CIHIValue] as [CIHI Value], 
		convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To] 				
	from LU_CodeFile lt 
	where [Code] =  + @SearchCode 

else if @SearchString = ''
	select 
		[Code] as [ ], 
    		[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		[DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description],
		[DefaultDescription] as [Default Description],
		[CIHIValue] as [CIHI Value],	 
		convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To] 
	from LU_CodeFile lt
	where [LookUpID] = @LookUpID 
	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	order by [DisplayCode]
else
begin	
	execute @return = P_CheckLUDisplayCodeCF @LookUpID, @SearchString, 'NO DATE', @HospID --PR-02277
	if @return <> 0 
		select 
			[Code] as [ ], 
        		[LUText] as [l],
			(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
			[DisplayCode] as [Code Value],
			[UserDescription] as [Hospital Description],
			[DefaultDescription] as [Default Description],
			[CIHIValue] as [CIHI Value],	 
			convert(varchar(10), [Validfrom], 111) as [Valid from],
			convert(varchar(10), [ValidTo], 111) as [Valid To] 
		from LU_CodeFile lt
    		where [LookUpID] = @LookUpID 
    		and [DisplayCode] like '%' + @SearchString + '%' 
		and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by [DisplayCode]				
	else
		select 
			[Code] as [ ],  
        		[LUText] as [l],
			(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
			[DisplayCode] as [Code Value],
			[UserDescription] as [Hospital Description],
			[DefaultDescription] as [Default Description],
			[CIHIValue] as [CIHI Value],	 
			convert(varchar(10), [Validfrom], 111) as [Valid from],
			convert(varchar(10), [ValidTo], 111) as [Valid To] 
		from LU_CodeFile lt
    		where [LookUpID] = @LookUpID 
    		and [UserDescription] like '%' + @SearchString + '%' 
		and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by [UserDescription]
end




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE     PROCEDURE [P_LookUpDetails]
	@SearchTable as varchar(50),
	@SearchCode as varchar(50) = '0',
	@UsesCIHI as Int
AS 

	declare @sql varchar(3000)

	if @UsesCIHI = 1 
	begin
    	if isnumeric(@SearchTable) <> 0
			select 
				[DisplayCode],
				[UserDescription],
				convert(varchar(10), [Validfrom], 111) as [Valid from],
				convert(varchar(10), [ValidTo], 111) as [Valid To],
				[InterfaceIn],
				(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(L.HospitalID, 0)) as [Hosp ID],
				[CIHIValue]
			from LU_CodeFile L
		    where [Code] = @SearchCode

		else
		begin
			select @sql = 'select 
						[DisplayCode],
						[UserDescription],
						convert(varchar(10), [Validfrom], 111) as [Valid from],
						convert(varchar(10), [ValidTo], 111) as [Valid To],
						[InterfaceIn],
						(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(L.HospitalID, 0)) as [Hosp ID],
						[CIHIValue] 
			from ' + @SearchTable + ' L ' +
			' where [Code] = ' + @SearchCode + ''
			execute (@sql)
		end
	end

	else
	begin
		select @sql = 'select 
					[DisplayCode],
					[UserDescription],
					convert(varchar(10), [Validfrom], 111) as [Valid from],
					convert(varchar(10), [ValidTo], 111) as [Valid To],
					[InterfaceIn],
					(select top 1 DisplayCode from H_HospitalProfile where isnull(Code, 0) = isnull(L.HospitalID, 0)) as [Hosp ID]				
		from ' + @SearchTable + ' L ' +
		' where [Code] = ' + @SearchCode + ''
		execute (@sql)
	end


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


/*This returns the DPG values for the proper year, ICD Type and Procedure Code*/
CREATE       PROCEDURE [P_LookupDPG]
	@ICDType as VarChar(1),
	@FiscalYear as int,
	@InterventionCode as Varchar(10),
	@InterventionAttribute as VarChar(2) = '',
	@AbstractID as Int,
	@DPGID as Int OUTPUT,
	@DPG as VarChar(3) OUTPUT,
	@DPG_RIW as VarChar(6) OUTPUT,
	@DPG_MOH_RIW as VarChar(6) OUTPUT,
	@DPG_Description as VarChar(255) OUTPUT,
	@FlagRecord as VarChar(1) = 'N'

AS 
	If @ICDType = 'T'
		Begin
			If Exists(SELECT DPGCode, DPGCodeDesc, RIW FROM dbo.LLU_DPG10
				WHERE (DPGYear = @FiscalYear) AND (ProcedureCode = @InterventionCode) AND (ProcLocationAttribute = @InterventionAttribute))
				Select @DPG = DPGCode, @DPG_Description = DPGCodeDesc, @DPG_RIW = RIW FROM dbo.LLU_DPG10
					WHERE (DPGYear = @FiscalYear) AND (ProcedureCode = @InterventionCode) AND (ProcLocationAttribute = @InterventionAttribute)
			Else If Exists(Select DPGCode, DPGCodeDesc, RIW FROM dbo.LLU_DPG10
					WHERE (DPGYear = @FiscalYear) AND (ProcedureCode = @InterventionCode) AND (ProcLocationAttribute is null))
				Select @DPG = DPGCode, @DPG_Description = DPGCodeDesc, @DPG_RIW = RIW FROM dbo.LLU_DPG10
					WHERE (DPGYear = @FiscalYear) AND (ProcedureCode = @InterventionCode) AND (ProcLocationAttribute is null)
--added 2006 and X3 for ticket ED-00312
			Else if @FiscalYear < 2006
				Select Top 1 @DPG = DPGCode, @DPG_Description = DPGCodeDesc, @DPG_RIW = RIW FROM dbo.LLU_DPG10
					WHERE (DPGYear = @FiscalYear) AND (dpgcode = '98')
			Else
			Begin
				If Exists(Select * FROM dbo.LLU_DPG10 WHERE (DPGYear = @FiscalYear) AND (ProcedureCode = @InterventionCode) and (ProcedureCode <> 'X1'))
					Select Top 1 @DPG = DPGCode, @DPG_Description = DPGCodeDesc, @DPG_RIW = RIW FROM dbo.LLU_DPG10
					WHERE (DPGYear = @FiscalYear) AND (dpgcode = 'X3')
				else
					Select Top 1 @DPG = DPGCode, @DPG_Description = DPGCodeDesc, @DPG_RIW = RIW FROM dbo.LLU_DPG10
					WHERE (DPGYear = @FiscalYear) AND (dpgcode = 'X1')
			End
		End
	Else If @ICDType = 'C'
	Begin
		 
		SELECT @DPG = DPGCode, @DPG_Description = DPGCodeDesc, @DPG_RIW = RIW FROM dbo.LLU_DPG9
		WHERE (DPGYear = @FiscalYear) AND (ICDIndicator = @ICDType) AND (ProcedureCode = @InterventionCode)

		/*if isnull(@DPG, '') = ''
			SELECT @DPG = DPGCode, @DPG_Description = DPGCodeDesc, @DPG_RIW = RIW FROM dbo.LLU_DPG9
			WHERE (DPGYear = @FiscalYear) AND (ICDIndicator = '9') AND (ProcedureCode = @InterventionCode)
		*/

		if isnull(@DPG, '') = ''
			Select Top 1 @DPG = DPGCode, @DPG_Description = DPGCodeDesc, @DPG_RIW = RIW FROM dbo.LLU_DPG9
				WHERE (DPGYear = @FiscalYear) AND (dpgcode = '98')
	End

	Else 
	Begin
		 
		SELECT @DPG = DPGCode, @DPG_Description = DPGCodeDesc, @DPG_RIW = RIW FROM dbo.LLU_DPG9
		WHERE (DPGYear = @FiscalYear) AND (ICDIndicator = @ICDType) AND (ProcedureCode = @InterventionCode)

		/*if isnull(@DPG, '') = ''
			SELECT @DPG = DPGCode, @DPG_Description = DPGCodeDesc, @DPG_RIW = RIW FROM dbo.LLU_DPG9
			WHERE (DPGYear = @FiscalYear) AND (ICDIndicator = 'C') AND (ProcedureCode = @InterventionCode)
		*/

		if isnull(@DPG, '') = ''
			Select Top 1 @DPG = DPGCode, @DPG_Description = DPGCodeDesc, @DPG_RIW = RIW FROM dbo.LLU_DPG9
				WHERE (DPGYear = @FiscalYear) AND (dpgcode = '98')
	End

	--Ticket 11969 Enhancement for DPG Auditing
	If isnull(@AbstractID, 0) > 0
	Begin
		Declare @AUDPG as Varchar(6)
		Declare @AUDPGRIW as VarChar(20)
		Declare @AUAid as int
		Declare @GrouperChange as VarChar(1)
		Set @GrouperChange = 'N'
		SELECT @AUAid = Abstractid, @AUDPG = DPG, @AUDPGRIW = DPG_RIW
		FROM AB_DPG where AbstractID = @AbstractID and OccurrenceNumber = 1 and DPG_Year = @FiscalYear
		If isnull(@AUAid, 0) > 0
		Begin
			If @AUDPG <> @DPG
			begin
				Insert into AB_GrouperAudit Values (@AbstractID, @FiscalYear, 'DPG', @AUDPG, @DPG, GetDate())
				Set @GrouperChange = 'Y'
			end
			If @AUDPGRIW <> @DPG_RIW
			begin
				Insert into AB_GrouperAudit Values (@AbstractID, @FiscalYear, 'DPGRIW', @AUDPGRIW, @DPG_RIW, GetDate())
				Set @GrouperChange = 'Y'
			end

		End
	End

	If isnull(@AbstractID, 0) > 0
	Begin
		Delete AB_DPG where Abstractid = @Abstractid and DPG_Year = @FiscalYear and OccurrenceNumber = 1
		If IsNull(@DPG, '') <> ''
		Begin
			If @ICDType = 'C'
				Set @InterventionCode = (select top 1 code from ICD_ProcFile9cm where cihivalue = @InterventionCode)
			Else If @ICDType = 'T'
				Set @InterventionCode = (select top 1 code from ICD_ProcFile10 where cihivalue = @InterventionCode)
			Else
				Set @InterventionCode = (select top 1 code from ICD_ProcFile9 where cihivalue = @InterventionCode)

			INSERT INTO [dbo].[AB_DPG] (AbstractID, OccurrenceNumber, DPG_Year, DPG, DPG_RIW, 
			DPG_MOH_RIW, DPG_Description, InterventionCode) VALUES 
			(@AbstractID, 1, @FiscalYear, @DPG, @DPG_RIW, @DPG_MOH_RIW, @DPG_Description, @InterventionCode)
		End
		If @GrouperChange = 'Y' and @FlagRecord = 'Y'
			Update AB_Abstract set iscorrected = 2 where abstractid = @AbstractID and issubmited = 1 and isdeleted = 2 and iscorrected in (1, 3)
				and batchyear = 2006
	End


	Return 0

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE       PROCEDURE [P_LookupDPGON]
	@ICDType as VarChar(1),
	@FiscalYear as int,
	@InterventionCode as Varchar(10),
	@InterventionAttribute as VarChar(2) = '',
	@AbstractID as Int
AS 
	declare @DPGID as Int
	declare @DPG as VarChar(6)
	declare @DPG_RIW as VarChar(6)
	declare @DPG_MOH_RIW as VarChar(6)
	declare @DPG_Description as VarChar(255)
	declare @YearToSearchOn as int
--PR-01621
	if @FiscalYear <= 2003
		set @YearToSearchOn = 2003
	else if @FiscalYear = 2004
		set @YearToSearchOn = 2004
	else
		set @YearToSearchOn = 2005

	If Exists(SELECT DPGCode, DPGCodeDesc, RIW FROM dbo.LLU_DPGON10
		WHERE (DPGYear = @YearToSearchOn) AND (ProcedureCode = @InterventionCode) AND (ProcLocationAttribute = @InterventionAttribute))
		Select @DPG = DPGCode, @DPG_Description = DPGCodeDesc, @DPG_RIW = RIW FROM dbo.LLU_DPGON10
			WHERE (DPGYear = @YearToSearchOn) AND (ProcedureCode = @InterventionCode) AND (ProcLocationAttribute = @InterventionAttribute)
	Else If Exists(Select DPGCode, DPGCodeDesc, RIW FROM dbo.LLU_DPGON10
			WHERE (DPGYear = @YearToSearchOn) AND (ProcedureCode = @InterventionCode) AND (ProcLocationAttribute is null))
		Select @DPG = DPGCode, @DPG_Description = DPGCodeDesc, @DPG_RIW = RIW FROM dbo.LLU_DPGON10
			WHERE (DPGYear = @YearToSearchOn) AND (ProcedureCode = @InterventionCode) AND (ProcLocationAttribute is null)
	Else
		Select Top 1 @DPG = DPGCode, @DPG_Description = DPGCodeDesc, @DPG_RIW = RIW FROM dbo.LLU_DPGON10
			WHERE (DPGYear = @YearToSearchOn) AND (dpgcode = '98')


	If isnull(@AbstractID, 0) > 0
	Begin
		Delete AB_DPG where Abstractid = @Abstractid and DPG_Year = @FiscalYear and OccurrenceNumber = 1
		If IsNull(@DPG, '') <> ''
		Begin
			Set @InterventionCode = (select top 1 code from ICD_ProcFile10 where cihivalue = @InterventionCode)

			INSERT INTO [dbo].[AB_DPG] (AbstractID, OccurrenceNumber, DPG_Year, DPG, DPG_RIW, 
			DPG_MOH_RIW, DPG_Description, InterventionCode) VALUES 
			(@AbstractID, 1, @FiscalYear, @DPG, @DPG_RIW, @DPG_MOH_RIW, @DPG_Description, @InterventionCode)
		End
	End



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE            PROCEDURE [P_LookUpICD]
	@SearchType as VarChar(1),
	@ICDType as VarChar(1),
	@SearchString as VarChar(50) = '',
	@SearchCode as int = 0,
	@Gender AS VarChar(1)='', 
	@UseDate as VarChar(10)='',
	@UseAge as int = 0,
	@OccNo as int = 0
AS 

DECLARE @Return as VarChar(3)

declare @GenderS as varchar(50) --PR-02786

if @Gender = '2' set @Gender = 'F'
if @Gender = '1' set @Gender = 'M'

set @GenderS = '(''A'', ''N'', ''G'')' --PR-02786
if @Gender = 'F' set @GenderS = '(''A'', ''F'', ''G'')' --PR-02786
if @Gender = 'M' set @GenderS = '(''A'', ''M'', ''N'')' --PR-02786


IF @SearchType = 'D'
	
	IF @ICDType = '9'
		IF @SearchCode <> '0'
			BEGIN
				SELECT [Code] AS [ ], 
					[DisplayCode] AS [Code Value],
					[UserDescription] AS [Hospital Description],
					[DefaultDescription] AS [Default Description],
					[CIHIValue] AS [CIHI Value],	 
					Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
					Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]
				FROM dbo.ICD_DiagFile9 WHERE [Code] = @SearchCode AND ([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo])
				RETURN @@ROWCOUNT
			END
		ELSE IF @SearchString = ''
			BEGIN
				If @OccNo = 1
					SELECT [Code] AS [ ], 
					[DisplayCode] AS [Code Value],
					[UserDescription] AS [Hospital Description],
					[DefaultDescription] AS [Default Description],
					[CIHIValue] AS [CIHI Value],	 
					Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
					Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]	
					FROM dbo.ICD_DiagFile9
					WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'' OR
			                        DiagnosisGender = @GenderS) And (MRDxFlag = 'Y') AND 
						([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [DisplayCode]
				else
					SELECT [Code] AS [ ], 
					[DisplayCode] AS [Code Value],
					[UserDescription] AS [Hospital Description],
					[DefaultDescription] AS [Default Description],
					[CIHIValue] AS [CIHI Value],	 
					Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
					Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]	
					FROM dbo.ICD_DiagFile9
					WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'' OR
			                           DiagnosisGender = @GenderS) AND ([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [DisplayCode]
				RETURN @@ROWCOUNT
			END
		
		ELSE
			IF EXISTS (SELECT [Code] FROM dbo.ICD_DiagFile9 WHERE ([DisplayCode] LIKE @SearchString + '%' or [CIHIValue] LIKE @SearchString + '%') AND ([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]))
				BEGIN	
					If @OccNo = 1
						SELECT [Code] AS [ ], 
						[DisplayCode] AS [Code Value],
						[UserDescription] AS [Hospital Description],
						[DefaultDescription] AS [Default Description],
						[CIHIValue] AS [CIHI Value],	 
						Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
						Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]	
						FROM dbo.ICD_DiagFile9 WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'' OR
			                           DiagnosisGender = @GenderS) And (MRDxFlag = 'Y') AND ([DisplayCode] LIKE @SearchString + '%' or [CIHIValue] LIKE @SearchString + '%') AND 
						([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [DisplayCode]
					else
						SELECT [Code] AS [ ], [DisplayCode] AS [Code Value],
						[UserDescription] AS [Hospital Description],
						[DefaultDescription] AS [Default Description],
						[CIHIValue] AS [CIHI Value],	 
						Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
						Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]	
						FROM dbo.ICD_DiagFile9 WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'' OR
			                           DiagnosisGender = @GenderS) AND ([DisplayCode] LIKE @SearchString + '%' or [CIHIValue] LIKE @SearchString + '%')  AND 
						([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [DisplayCode]
					RETURN @@ROWCOUNT	
				END
			ELSE
				BEGIN
					If @OccNo = 1
						SELECT [Code] AS [ ], 
						[DisplayCode] AS [Code Value],
						[UserDescription] AS [Hospital Description],
						[DefaultDescription] AS [Default Description],						
						[CIHIValue] AS [CIHI Value],	 
						Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
						Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]	
						FROM dbo.ICD_DiagFile9 WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'' OR
			                           DiagnosisGender = @GenderS) And (MRDxFlag = 'Y') AND [UserDescription] LIKE '%' + @SearchString + '%' AND 
						([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [UserDescription]
					Else
						SELECT [Code] AS [ ], 
						[DisplayCode] AS [Code Value],
						[UserDescription] AS [Hospital Description],
						[DefaultDescription] AS [Default Description],						
						[CIHIValue] AS [CIHI Value],	 
						Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
						Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]	
						FROM dbo.ICD_DiagFile9 WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'' OR
			                           DiagnosisGender = @GenderS) AND [UserDescription] LIKE '%' + @SearchString + '%' AND 
						([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [UserDescription]
					RETURN @@ROWCOUNT
				END		
	ELSE IF @ICDType = 'C'
		IF @SearchCode <> '0'
			BEGIN
				SELECT [Code] AS [ ], 
					[DisplayCode] AS [Code Value],
					[UserDescription] AS [Hospital Description],
					[DefaultDescription] AS [Default Description],
					[CIHIValue] AS [CIHI Value],	 
					Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
					Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]
				FROM dbo.ICD_DiagFile9cm WHERE [Code] = @SearchCode  AND ([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo])
				RETURN @@ROWCOUNT
			END
		ELSE IF @SearchString = ''
			BEGIN
				If @OccNo = 1
					SELECT [Code] AS [ ], 
					[DisplayCode] AS [Code Value],
					[UserDescription] AS [Hospital Description],
					[DefaultDescription] AS [Default Description],
					[CIHIValue] AS [CIHI Value],	 
					Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
					Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]	
					FROM dbo.ICD_DiagFile9cm
					WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'' OR
			                           DiagnosisGender = @GenderS) And (MRDxFlag = 'Y') AND 
					([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [DisplayCode]
				else
					SELECT [Code] AS [ ], 
					[DisplayCode] AS [Code Value],
					[UserDescription] AS [Hospital Description],
					[DefaultDescription] AS [Default Description],
					[CIHIValue] AS [CIHI Value],	 
					Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
					Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]	
					FROM dbo.ICD_DiagFile9cm
					WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'' OR
			                           DiagnosisGender = @GenderS) AND ([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [DisplayCode]
				RETURN @@ROWCOUNT
			END
		
		ELSE
			IF EXISTS (SELECT [Code] FROM dbo.ICD_DiagFile9cm WHERE ([DisplayCode] LIKE @SearchString + '%' or [CIHIValue] LIKE @SearchString + '%') AND ([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]))
				BEGIN	
					If @OccNo = 1
						SELECT [Code] AS [ ], 
						[DisplayCode] AS [Code Value],
						[UserDescription] AS [Hospital Description],
						[DefaultDescription] AS [Default Description],
						[CIHIValue] AS [CIHI Value],	 
						Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
						Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]	
						FROM dbo.ICD_DiagFile9cm WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'' OR
			                           DiagnosisGender = @GenderS) And (MRDxFlag = 'Y') AND ([DisplayCode] LIKE @SearchString + '%' or [CIHIValue] LIKE @SearchString + '%') AND 
						([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [DisplayCode]
					else
						SELECT [Code] AS [ ], [DisplayCode] AS [Code Value],
						[UserDescription] AS [Hospital Description],
						[DefaultDescription] AS [Default Description],
						[CIHIValue] AS [CIHI Value],	 
						Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
						Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]	
						FROM dbo.ICD_DiagFile9cm WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'' OR
			                           DiagnosisGender = @GenderS) AND ([DisplayCode] LIKE @SearchString + '%' or [CIHIValue] LIKE @SearchString + '%') AND 
						([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [DisplayCode]
					RETURN @@ROWCOUNT	
				END
			ELSE
				BEGIN
					If @OccNo = 1
						SELECT [Code] AS [ ], 
						[DisplayCode] AS [Code Value],
						[UserDescription] AS [Hospital Description],
						[DefaultDescription] AS [Default Description],						
						[CIHIValue] AS [CIHI Value],	 
						Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
						Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]	
						FROM dbo.ICD_DiagFile9cm WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'' OR
			                           DiagnosisGender = @GenderS) And (MRDxFlag = 'Y') AND [UserDescription] LIKE '%' + @SearchString + '%' AND 
						([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [UserDescription]
					Else
						SELECT [Code] AS [ ], 
						[DisplayCode] AS [Code Value],
						[UserDescription] AS [Hospital Description],
						[DefaultDescription] AS [Default Description],						
						[CIHIValue] AS [CIHI Value],	 
						Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
						Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]	
						FROM dbo.ICD_DiagFile9cm WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'' OR
			                           DiagnosisGender = @GenderS) AND [UserDescription] LIKE '%' + @SearchString + '%' AND 
						([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [UserDescription]
					RETURN @@ROWCOUNT
				END		
	ELSE IF @ICDType = 'T'
		IF @SearchCode <> '0'
			BEGIN
				SELECT [Code] AS [ ], 
					[DisplayCode] AS [Code Value],
					[UserDescription] AS [Hospital Description],
					[DefaultDescription] AS [Default Description],
					[CIHIValue] AS [CIHI Value],	 
					Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
					Convert(VarChar(10), [ValidTo], 111)  AS [Valid To], 
                    ICD9, 
                    ICD9CM
				FROM dbo.ICD_DiagFile10 WHERE [Code] = @SearchCode  AND ([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo])
				RETURN @@ROWCOUNT
			END
		ELSE IF @SearchString = ''
			BEGIN
				If @OccNo = 1
					SELECT [Code] AS [ ], 
					[DisplayCode] AS [Code Value],
					[UserDescription] AS [Hospital Description],
					[DefaultDescription] AS [Default Description],
					[CIHIValue] AS [CIHI Value],	 
					Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
					Convert(VarChar(10), [ValidTo], 111)  AS [Valid To], 
                    ICD9, 
                    ICD9CM
					FROM dbo.ICD_DiagFile10
					WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'A' OR
			                           DiagnosisGender = @GenderS) And (MRDxFlag = 'Y') AND ([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [DisplayCode]
				else
					SELECT [Code] AS [ ], 
					[DisplayCode] AS [Code Value],
					[UserDescription] AS [Hospital Description],
					[DefaultDescription] AS [Default Description],
					[CIHIValue] AS [CIHI Value],	 
					Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
					Convert(VarChar(10), [ValidTo], 111)  AS [Valid To], 
                    ICD9, 
                    ICD9CM
					FROM dbo.ICD_DiagFile10
					WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'A' OR
			                           DiagnosisGender = @GenderS) AND ([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [DisplayCode]
				RETURN @@ROWCOUNT
			END
		
		ELSE
			IF EXISTS (SELECT [Code] FROM dbo.ICD_DiagFile10 WHERE ([DisplayCode] LIKE @SearchString + '%' or [CIHIValue] LIKE @SearchString + '%') AND ([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]))
				BEGIN	
					If @OccNo = 1
						SELECT [Code] AS [ ], 
						[DisplayCode] AS [Code Value],
						[UserDescription] AS [Hospital Description],
						[DefaultDescription] AS [Default Description],
						[CIHIValue] AS [CIHI Value],	 
						Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
						Convert(VarChar(10), [ValidTo], 111)  AS [Valid To], 
                        ICD9, 
                        ICD9CM
						FROM dbo.ICD_DiagFile10 WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'A' OR
			                           DiagnosisGender = @GenderS) And (MRDxFlag = 'Y') AND ([DisplayCode] LIKE @SearchString + '%' or [CIHIValue] LIKE @SearchString + '%') AND 
						([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [DisplayCode]
					else
						SELECT [Code] AS [ ], [DisplayCode] AS [Code Value],
						[UserDescription] AS [Hospital Description],
						[DefaultDescription] AS [Default Description],
						[CIHIValue] AS [CIHI Value],	 
						Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
						Convert(VarChar(10), [ValidTo], 111)  AS [Valid To], 
                        ICD9, 
                        ICD9CM
						FROM dbo.ICD_DiagFile10 WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'A' OR
			                           DiagnosisGender = @GenderS) AND ([DisplayCode] LIKE @SearchString + '%' or [CIHIValue] LIKE @SearchString + '%') AND 
						([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [DisplayCode]
					RETURN @@ROWCOUNT	
				END
			ELSE
				BEGIN
					If @OccNo = 1
						SELECT [Code] AS [ ], 
						[DisplayCode] AS [Code Value],
						[UserDescription] AS [Hospital Description],
						[DefaultDescription] AS [Default Description],						
						[CIHIValue] AS [CIHI Value],	 
						Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
						Convert(VarChar(10), [ValidTo], 111)  AS [Valid To], 
                        ICD9, 
                        ICD9CM
						FROM dbo.ICD_DiagFile10 WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'A' OR
			                           DiagnosisGender = @GenderS) And (MRDxFlag = 'Y') AND [UserDescription] LIKE '%' + @SearchString + '%' AND 
						([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [UserDescription]
					Else
						SELECT [Code] AS [ ], 
						[DisplayCode] AS [Code Value],
						[UserDescription] AS [Hospital Description],
						[DefaultDescription] AS [Default Description],						
						[CIHIValue] AS [CIHI Value],	 
						Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
						Convert(VarChar(10), [ValidTo], 111)  AS [Valid To], 
                        ICD9, 
                        ICD9CM
						FROM dbo.ICD_DiagFile10 WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'A' OR
			                           DiagnosisGender = @GenderS) AND [UserDescription] LIKE '%' + @SearchString + '%' AND 
						([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [UserDescription]
					RETURN @@ROWCOUNT
				END		
	ELSE
		BEGIN
			RETURN @@ROWCOUNT
		END
-- END OF SEARCH TYPE 'D'
Else
-- BEGIN OF SEARCH TYPE 'P'
	IF @ICDType = '9'
		IF @SearchCode <> '0'
			BEGIN
				SELECT [Code] AS [ ], 
					[DisplayCode] AS [Code Value],
					[UserDescription] AS [Hospital Description],
					[DefaultDescription] AS [Default Description],
					[CIHIValue] AS [CIHI Value],	 
					Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
					Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]	
				FROM dbo.ICD_ProcFile9 WHERE [Code] = @SearchCode  AND ([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo])
				RETURN @@ROWCOUNT
			END
		ELSE IF @SearchString = ''
			BEGIN
				SELECT [Code] AS [ ], 
					[DisplayCode] AS [Code Value],
					[UserDescription] AS [Hospital Description],
					[DefaultDescription] AS [Default Description],
					[CIHIValue] AS [CIHI Value],	 
					Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
					Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]	
				FROM dbo.ICD_ProcFile9
				WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'' OR
			                           DiagnosisGender = @GenderS) AND ([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [DisplayCode]
				RETURN @@ROWCOUNT
			END
		
		ELSE
			IF EXISTS (SELECT [Code] FROM dbo.ICD_ProcFile9 WHERE ([DisplayCode] LIKE @SearchString + '%' or [CIHIValue] LIKE @SearchString + '%') AND ([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]))
				BEGIN	
					SELECT [Code] AS [ ], 
						[DisplayCode] AS [Code Value],
						[UserDescription] AS [Hospital Description],
						[DefaultDescription] AS [Default Description],
						[CIHIValue] AS [CIHI Value],	 
						Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
						Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]	
					FROM dbo.ICD_ProcFile9 WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'' OR
			                           DiagnosisGender = @GenderS) AND ([DisplayCode] LIKE @SearchString + '%' or [CIHIValue] LIKE @SearchString + '%') AND 
					([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [DisplayCode]
					RETURN @@ROWCOUNT	
				END
			ELSE
				BEGIN
					SELECT [Code] AS [ ], 
						[DisplayCode] AS [Code Value],
						[UserDescription] AS [Hospital Description],
						[DefaultDescription] AS [Default Description],
						[CIHIValue] AS [CIHI Value],	 
						Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
						Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]	
					FROM dbo.ICD_ProcFile9 WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'' OR
			                           DiagnosisGender = @GenderS) AND [UserDescription] LIKE '%' + @SearchString + '%'  AND 
					([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [UserDescription]
					RETURN @@ROWCOUNT
				END		
	ELSE IF @ICDType = 'C'
		IF @SearchCode <> '0'
			BEGIN
				SELECT [Code] AS [ ], 
					[DisplayCode] AS [Code Value],
					[UserDescription] AS [Hospital Description],
					[DefaultDescription] AS [Default Description],
					[CIHIValue] AS [CIHI Value],	 
					Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
					Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]	
				FROM dbo.ICD_ProcFile9cm WHERE [Code] = @SearchCode  AND ([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo])
				RETURN @@ROWCOUNT
			END
		ELSE IF @SearchString = ''
			BEGIN
				SELECT [Code] AS [ ], 
					[DisplayCode] AS [Code Value],
					[UserDescription] AS [Hospital Description],
					[DefaultDescription] AS [Default Description],
					[CIHIValue] AS [CIHI Value],	 
					Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
					Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]	
				FROM dbo.ICD_ProcFile9cm
				WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'' OR
			                           DiagnosisGender = @GenderS) AND ([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [DisplayCode]
				RETURN @@ROWCOUNT
			END
		
		ELSE
			IF EXISTS (SELECT [Code] FROM dbo.ICD_ProcFile9cm WHERE ([DisplayCode] LIKE @SearchString + '%' or [CIHIValue] LIKE @SearchString + '%') AND ([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]))
				BEGIN	
					SELECT [Code] AS [ ], 
						[DisplayCode] AS [Code Value],
						[UserDescription] AS [Hospital Description],
						[DefaultDescription] AS [Default Description],
						[CIHIValue] AS [CIHI Value],	 
						Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
						Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]	
					FROM dbo.ICD_ProcFile9cm WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'' OR
			                           DiagnosisGender = @GenderS) AND ([DisplayCode] LIKE @SearchString + '%' or [CIHIValue] LIKE @SearchString + '%') AND 
					([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [DisplayCode]
					RETURN @@ROWCOUNT	
				END
			ELSE
				BEGIN
					SELECT [Code] AS [ ], 
						[DisplayCode] AS [Code Value],
						[UserDescription] AS [Hospital Description],
						[DefaultDescription] AS [Default Description],
						[CIHIValue] AS [CIHI Value],	 
						Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
						Convert(VarChar(10), [ValidTo], 111)  AS [Valid To]	
					FROM dbo.ICD_ProcFile9cm WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'' OR
			                           DiagnosisGender = @GenderS) AND [UserDescription] LIKE '%' + @SearchString + '%' AND 
					([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [UserDescription]
					RETURN @@ROWCOUNT
				END
	ELSE IF @ICDType ='T'
		IF @SearchCode <> '0'
			BEGIN
				SELECT [Code] AS [ ], 
					[DisplayCode] AS [Code Value],
					[UserDescription] AS [Hospital Description],
					[DefaultDescription] AS [Default Description],
					[CIHIValue] AS [CIHI Value],	 
					Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
					Convert(VarChar(10), [ValidTo], 111)  AS [Valid To], 
					[ICD9] AS [ICD9],
					[ICD9cm] AS [ICD9cm]
				FROM dbo.ICD_ProcFile10 WHERE [Code] = @SearchCode  AND ([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo])
				RETURN @@ROWCOUNT
			END
		ELSE IF @SearchString = ''
			BEGIN
				SELECT [Code] AS [ ], 
					[DisplayCode] AS [Code Value],
					[UserDescription] AS [Hospital Description],
					[DefaultDescription] AS [Default Description],
					[CIHIValue] AS [CIHI Value],	 
					Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
					Convert(VarChar(10), [ValidTo], 111)  AS [Valid To],	
					[ICD9] AS [ICD9],
					[ICD9cm] AS [ICD9cm],
					[DiagnosisGender] AS [Gender]
				FROM dbo.ICD_ProcFile10
				WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'A' OR
			                           DiagnosisGender = @GenderS) AND ([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [DisplayCode]
				RETURN @@ROWCOUNT
			END
		
		ELSE
			IF EXISTS (SELECT [Code] FROM dbo.ICD_ProcFile10 WHERE ([DisplayCode] LIKE @SearchString + '%' or [CIHIValue] LIKE @SearchString + '%') AND ([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]))
				BEGIN	
					SELECT [Code] AS [ ], 
						[DisplayCode] AS [Code Value],
						[UserDescription] AS [Hospital Description],
						[DefaultDescription] AS [Default Description],
						[CIHIValue] AS [CIHI Value],	 
						Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
						Convert(VarChar(10), [ValidTo], 111)  AS [Valid To], 
						[ICD9] AS [ICD9],
						[ICD9cm] AS [ICD9cm],
						[DiagnosisGender] AS [Gender]
					FROM dbo.ICD_ProcFile10 WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'A' OR
			                           DiagnosisGender = @GenderS) AND ([DisplayCode] LIKE @SearchString + '%' or [CIHIValue] LIKE @SearchString + '%') AND 
					([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [DisplayCode]
					RETURN @@ROWCOUNT	
				END
			ELSE
				BEGIN
					SELECT [Code] AS [ ], 
						[DisplayCode] AS [Code Value],
						[UserDescription] AS [Hospital Description],
						[DefaultDescription] AS [Default Description],
						[CIHIValue] AS [CIHI Value],	 
						Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
						Convert(VarChar(10), [ValidTo], 111)  AS [Valid To],
						[ICD9] AS [ICD9],
						[ICD9cm] AS [ICD9cm],
						Case When [DiagnosisGender] = 'A' Then 'All' END AS [Gender]
					FROM dbo.ICD_ProcFile10 WHERE (AgeLow <= @UseAge) AND (@UseAge <= AgeHigh) AND (DiagnosisGender = N'A' OR
			                           DiagnosisGender = @GenderS) AND [UserDescription] LIKE '%' + @SearchString + '%' AND 
					([ValidFrom] <= '' + @UseDate + '') AND ('' + @UseDate + '' <= [ValidTo]) ORDER BY [UserDescription]
					RETURN @@ROWCOUNT
				END

-- END OF SEARCH TYPE 'P'




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_LookUpICD_CCRS]
	@SearchType as varchar(1),
	@ICDType as varchar(1),
	@SearchString as varchar(250) = '',
	@SearchCode as varchar(10) = '0',
	@Gender AS varchar(1)='', 
	@UseDate as varchar(10)='',
	@UseAge as varchar(5) = '0',
	@OccNo as varchar(5) = '0',
	@CareType as varchar(1) = '0'
AS 
--
--copy the code from P_LookUpICD_NRS change the table name 
declare @return as varchar(3)
declare @sql as varchar(8000)

declare @s as varchar(2500)
declare @f as varchar(100)
declare @w as varchar(2500)
declare @o as varchar(100)

declare @MostR as varchar(20)
declare @GenderS as varchar(50) --PR-02786

declare @CodeStart as varchar(10)  --- Only neoplasms codes condition added NP-00083 Jan 2008
declare @CodeEnd as varchar(10)    -- Condition removed as per PR - 03284

if @Gender = '2' set @Gender = 'F'
if @Gender = '1' set @Gender = 'M'

set @GenderS = '(''A'', ''N'', ''G'')' --PR-02786
if @Gender = 'F' set @GenderS = '(''A'', ''F'', ''G'')' --PR-02786
if @Gender = 'M' set @GenderS = '(''A'', ''M'', ''N'')' --PR-02786

print ''
set @s = 'select 
		[Code] as [ ], 
        	[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
        	[DisplayCode] as [Code Value], 
        	[UserDescription] as [Hospital Description],
            	[DefaultDescription] as [Default Description], 
        	[CIHIValue] as [CIHI Value], 
        	convert(varchar(10), [Validfrom], 111) as [Valid from],
            	convert(varchar(10), [ValidTo], 111)  AS [Valid To] '

set @o = ' order by [DisplayCode]'

set @MostR = '(''Y'')'
if @CareType = '5' and @ICDType = 'T' set @MostR = '(''Y'', ''A'')'

set @f = ' from ICD_ProcFileMDS'
if @SearchType = 'D' set @f = ' from ICD_DiagFileMDS'

if @ICDType = 'T'
begin
	set @w = ' where (isnull(DiagnosisGender, '''') in ' + @GenderS + ') and ' --PR-02786
end

set @f = @f + ' lt '

if @SearchCode <> '0'
    	set @w = @w + '[Code] = ''' + @SearchCode + ''' 
            	and ([Validfrom] <= ''' + @UseDate + ''') 
            	and (''' + @UseDate + ''' <= [ValidTo]) '

else if @SearchString = ''
    	set @w = @w + '(AgeLow <= ' + @UseAge + ') 
            	and (' + @UseAge + ' <= AgeHigh) 
            	and ([Validfrom] <= ''' + @UseDate + ''') 
            	and (''' + @UseDate + ''' <= [ValidTo]) '
else
begin
    	set @SearchString = replace(@SearchString, '''', '')
    	exec('select [Code] ' + @f + 'where ([DisplayCode] like ''' + @SearchString + '%'' or [CIHIValue] like ''' + @SearchString + '%'') and ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo])')
    	if @@RowCount > 0
    	begin
	    	if @OccNo = 1 and @SearchType = 'D'
			set @w = @w + '(AgeLow <= ' + @UseAge + ') 
                    		and (' + @UseAge + ' <= AgeHigh) 
                    		--and (MRDxFlag in ' + @MostR + ') 
                    		and ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo]) 
                    		and ([DisplayCode] like ''' + @SearchString + '%''                       	or [CIHIValue] like ''' + @SearchString + '%'') '
		else
		    	set @w = @w + '(AgeLow <= ' + @UseAge + ') 
                    		and (' + @UseAge + ' <= AgeHigh) 
                    		and ([Validfrom] <= ''' + @UseDate + ''') 
                    		and (''' + @UseDate + ''' <= [ValidTo]) 
                    		and ([DisplayCode] like ''' + @SearchString + '%'' 
                        	or [CIHIValue] like ''' + @SearchString + '%'') '
end
    
else
begin
	set @SearchString = ltrim(rtrim(@SearchString))
	set @SearchString = replace(@SearchString, '  ', ' ')
	set @SearchString = replace(@SearchString, ' ', '%'' and [UserDescription] + [cihivalue] + [displaycode] like ''%')
	if @OccNo = 1 and @SearchType = 'D'
		set @w = @w + '(AgeLow <= ' + @UseAge + ') 
                    	and (' + @UseAge + ' <= AgeHigh) 
                    	--and (MRDxFlag in ' + @MostR + ') 
                    	and ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo]) 
                    	and ([UserDescription] + [cihivalue] + [displaycode] like ''%' + @SearchString + '%'')  '
	else
		set @w = @w + '(AgeLow <= ' + @UseAge + ') 
                    	and (' + @UseAge + ' <= AgeHigh) 
                    	and ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo]) 
                    	and ([UserDescription] + [cihivalue] + [displaycode] like ''%' + @SearchString + '%'') '
	end
end

set @sql = @s + @f + @w + @o
print @sql
exec(@sql)

return @@ROWCOUNT


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE      PROCEDURE [P_LookUpICD_NRS]
	@SearchType as varchar(1),
	@ICDType as varchar(1),
	@SearchString as varchar(250) = '',
	@SearchCode as varchar(10) = '0',
	@Gender AS varchar(1)='', 
	@UseDate as varchar(10)='',
	@UseAge as varchar(5) = '0',
	@OccNo as varchar(5) = '0',
	@CareType as varchar(1) = '0'
AS 

declare @return as varchar(3)
declare @sql as varchar(8000)

declare @s as varchar(2500)
declare @f as varchar(100)
declare @w as varchar(2500)
declare @o as varchar(100)

declare @MostR as varchar(20)
declare @GenderS as varchar(50) --PR-02786

declare @CodeStart as varchar(10)  --- Only neoplasms codes condition added NP-00083 Jan 2008
declare @CodeEnd as varchar(10)    -- Condition removed as per PR - 03284

if @Gender = '2' set @Gender = 'F'
if @Gender = '1' set @Gender = 'M'

set @GenderS = '(''A'', ''N'', ''G'')' --PR-02786
if @Gender = 'F' set @GenderS = '(''A'', ''F'', ''G'')' --PR-02786
if @Gender = 'M' set @GenderS = '(''A'', ''M'', ''N'')' --PR-02786

print ''
set @s = 'select 
		[Code] as [ ], 
        	[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
        	[DisplayCode] as [Code Value], 
        	[UserDescription] as [Hospital Description],
            	[DefaultDescription] as [Default Description], 
        	[CIHIValue] as [CIHI Value], 
        	convert(varchar(10), [Validfrom], 111) as [Valid from],
            	convert(varchar(10), [ValidTo], 111)  AS [Valid To] '

set @o = ' order by [DisplayCode]'

set @MostR = '(''Y'')'
if @CareType = '5' and @ICDType = 'T' set @MostR = '(''Y'', ''A'')'

set @f = ' from ICD_ProcFileNRS'
if @SearchType = 'D' set @f = ' from ICD_DiagFileNRS'

if @ICDType = 'T'
begin
	set @w = ' where (isnull(DiagnosisGender, '''') in ' + @GenderS + ') and ' --PR-02786
end

set @f = @f + ' lt '

if @SearchCode <> '0'
    	set @w = @w + '[Code] = ''' + @SearchCode + ''' 
            	and ([Validfrom] <= ''' + @UseDate + ''') 
            	and (''' + @UseDate + ''' <= [ValidTo]) '

else if @SearchString = ''
    	set @w = @w + '(AgeLow <= ' + @UseAge + ') 
            	and (' + @UseAge + ' <= AgeHigh) 
            	and ([Validfrom] <= ''' + @UseDate + ''') 
            	and (''' + @UseDate + ''' <= [ValidTo]) '
else
begin
    	set @SearchString = replace(@SearchString, '''', '')
    	exec('select [Code] ' + @f + 'where ([DisplayCode] like ''' + @SearchString + '%'' or [CIHIValue] like ''' + @SearchString + '%'') and ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo])')
    	if @@RowCount > 0
    	begin
	    	if @OccNo = 1 and @SearchType = 'D'
			set @w = @w + '(AgeLow <= ' + @UseAge + ') 
                    		and (' + @UseAge + ' <= AgeHigh) 
                    		--and (MRDxFlag in ' + @MostR + ') 
                    		and ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo]) 
                    		and ([DisplayCode] like ''' + @SearchString + '%''                       	or [CIHIValue] like ''' + @SearchString + '%'') '
		else
		    	set @w = @w + '(AgeLow <= ' + @UseAge + ') 
                    		and (' + @UseAge + ' <= AgeHigh) 
                    		and ([Validfrom] <= ''' + @UseDate + ''') 
                    		and (''' + @UseDate + ''' <= [ValidTo]) 
                    		and ([DisplayCode] like ''' + @SearchString + '%'' 
                        	or [CIHIValue] like ''' + @SearchString + '%'') '
end
    
else
begin
	set @SearchString = ltrim(rtrim(@SearchString))
	set @SearchString = replace(@SearchString, '  ', ' ')
	set @SearchString = replace(@SearchString, ' ', '%'' and [UserDescription] + [cihivalue] + [displaycode] like ''%')
	if @OccNo = 1 and @SearchType = 'D'
		set @w = @w + '(AgeLow <= ' + @UseAge + ') 
                    	and (' + @UseAge + ' <= AgeHigh) 
                    	--and (MRDxFlag in ' + @MostR + ') 
                    	and ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo]) 
                    	and ([UserDescription] + [cihivalue] + [displaycode] like ''%' + @SearchString + '%'')  '
	else
		set @w = @w + '(AgeLow <= ' + @UseAge + ') 
                    	and (' + @UseAge + ' <= AgeHigh) 
                    	and ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo]) 
                    	and ([UserDescription] + [cihivalue] + [displaycode] like ''%' + @SearchString + '%'') '
	end
end

set @sql = @s + @f + @w + @o
print @sql
exec(@sql)

return @@ROWCOUNT


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_LookUpICD2]
	@SearchType as varchar(1),
	@ICDType as varchar(1),
	@SearchString as varchar(250) = '',
	@SearchCode as varchar(10) = '0',
	@Gender AS varchar(1)='', 
	@UseDate as varchar(10)='',
	@UseAge as varchar(5) = '0',
	@OccNo as varchar(5) = '0',
	@CareType as varchar(1) = '0',
	@IsDisch as int = 0,
	@BirthDate as varchar(20) --ED - 02232
AS 

declare @return as varchar(3)
declare @sql as varchar(8000)

declare @s as varchar(2500)
declare @f as varchar(100)
declare @w as varchar(2500)
declare @o as varchar(100)

declare @MostR as varchar(20)
declare @GenderS as varchar(50) --PR-02786

declare @CodeStart as varchar(10)  --- Only neoplasms codes condition added NP-00083 Jan 2008
declare @CodeEnd as varchar(10)    -- Condition removed as per PR - 03284

--set @CodeStart = 'C00' Now all codes incluided PR - 03284
--set @CodeEnd =  'D49'

if @Gender = '2' set @Gender = 'F'
if @Gender = '1' set @Gender = 'M'

set @GenderS = '(''A'', ''N'', ''G'')' --PR-02786
if @Gender = 'F' set @GenderS = '(''A'', ''F'', ''G'')' --PR-02786
if @Gender = 'M' set @GenderS = '(''A'', ''M'', ''N'')' --PR-02786

print ''
set @s = 'select 
		[Code] as [ ], 
        	[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
        	[DisplayCode] as [Code Value], 
        	[UserDescription] as [Hospital Description],
            	[DefaultDescription] as [Default Description], 
        	[CIHIValue] as [CIHI Value], 
        	convert(varchar(10), [Validfrom], 111) as [Valid from],
            	convert(varchar(10), [ValidTo], 111)  AS [Valid To] '

set @o = ' order by [DisplayCode]'

set @MostR = '(''Y'')'
if @CareType = '5' and @ICDType = 'T' set @MostR = '(''Y'', ''A'')'

set @f = ' from ICD_ProcFile'
if @SearchType = 'D' set @f = ' from ICD_DiagFile'

if @ICDType = '9'
begin
	set @f = @f + '9 '
    	set @w = ' where (isnull(DiagnosisGender, '''') = '''' or DiagnosisGender = ''' + @Gender + ''') and '
end
else if @ICDType = 'C'
begin
	set @f = @f + '9cm '
    	set @w = ' where (isnull(DiagnosisGender, '''') = '''' or DiagnosisGender = ''' + @Gender + ''') and '
end
else if @ICDType = 'T'
begin
    	set @f = ', ICD9, ICD9CM ' + @f + '10 '
    	--set @w = ' where (isnull(DiagnosisGender, '''') = ''A'' or DiagnosisGender = ''' + @Gender + ''') and '
    
	    set @w = ' where (isnull(DiagnosisGender, '''') in ' + @GenderS + ') and ' --PR-02786
end

set @f = @f + ' lt '

if @SearchCode <> '0'
begin
    	set @w = @w + '[Code] = ''' + @SearchCode + ''' 
            	and ([Validfrom] <= ''' + @UseDate + ''') 
            	and (''' + @UseDate + ''' <= [ValidTo]) '

		-- and ([DisplayCode] between ''' + @CodeStart + ''' AND ''' + @CodeEnd + ''') 		 PR - 03284
	  	--		and ([CIHIValue] between ''' + @CodeStart + ''' AND ''' +  @CodeEnd + ''')'
end
else if @SearchString = ''
begin
		--ED - 02232 if @BirthDate = 9999/09/01, then do not check age.
    	set @w = @w + (case when convert(varchar(10), @BirthDate, 111) = '9999/09/01' then ' ' else '(AgeLow <= ' + @UseAge + ') and (' + @UseAge + ' <= AgeHigh) and ' end) + ' 
            	([Validfrom] <= ''' + @UseDate + ''') 
            	and (''' + @UseDate + ''' <= [ValidTo]) '
        --PR - 07437 ignore main diagnosis code for ED discharge diagnosis code
    	--if @OccNo = 1 and @SearchType = 'D'		--PR - 04702 
    	if @OccNo = 1 and @SearchType = 'D'	and @IsDisch <> 1	--PR - 04702 
			set @w = @w + 'and (MRDxFlag in ' + @MostR + ') ' 


--            	and ([Validfrom] <= ''1901/12/01'') and (''1901/12/01'' <= [ValidTo]) '        PR - 03349: This line replaced by the line above 
--		and ([DisplayCode] between ''' + @CodeStart + ''' AND ''' + @CodeEnd + ''')   PR - 03284
--				and ([CIHIValue] between ''' + @CodeStart + ''' AND ''' +  @CodeEnd + ''')'
end
else
begin
    	set @SearchString = replace(@SearchString, '''', '')
    	exec('select [Code] ' + @f + 'where ([DisplayCode] like ''' + @SearchString + '%'' or [CIHIValue] like ''' + @SearchString + '%'') and ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo])')
    	if @@RowCount > 0
    	begin
    		--ED - 02232 if @BirthDate = 9999/09/01, then do not check age.
            --PR - 07437 ignore main diagnosis code for ED discharge diagnosis code
    	    --if @OccNo = 1 and @SearchType = 'D'		
    	    if @OccNo = 1 and @SearchType = 'D'	and @IsDisch <> 1	
			    set @w = @w + (case when convert(varchar(10), @BirthDate, 111) = '9999/09/01' then ' '  else '(AgeLow <= ' + @UseAge + ') and (' + @UseAge + ' <= AgeHigh) and ' end) + ' 
                    		    (MRDxFlag in ' + @MostR + ') 
                    		    and ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo]) 
                    		    and ([DisplayCode] like ''' + @SearchString + '%''                       	or [CIHIValue] like ''' + @SearchString + '%'') '
    --				and ([DisplayCode] between ''' + @CodeStart + ''' AND ''' + @CodeEnd + ''')   PR - 03284
    --				and ([CIHIValue] between ''' + @CodeStart + ''' AND ''' +  @CodeEnd + ''')'
		    else
    		    --ED - 02232 if @BirthDate = 9999/09/01, then do not check age.
		    	    set @w = @w + (case when convert(varchar(10), @BirthDate, 111) = '9999/09/01' then ' '  else '(AgeLow <= ' + @UseAge + ') and (' + @UseAge + ' <= AgeHigh) and ' end) + ' 
                    		    ([Validfrom] <= ''' + @UseDate + ''') 
                    		    and (''' + @UseDate + ''' <= [ValidTo]) 
                    		    and ([DisplayCode] like ''' + @SearchString + '%'' 
                        	    or [CIHIValue] like ''' + @SearchString + '%'') '
    --				and ([DisplayCode] between ''' + @CodeStart + ''' AND ''' + @CodeEnd + ''')   PR - 03284
    --				and ([CIHIValue] between ''' + @CodeStart + ''' AND ''' +  @CodeEnd + ''')'
		end
    
	else
	begin
		set @SearchString = ltrim(rtrim(@SearchString))
		set @SearchString = replace(@SearchString, '  ', ' ')
		set @SearchString = replace(@SearchString, ' ', '%'' and [UserDescription] + [cihivalue] + [displaycode] like ''%')
		--ED - 02232 if @BirthDate = 9999/09/01, then do not check age.

        --PR - 07437 ignore main diagnosis code for ED discharge diagnosis code
    	--if @OccNo = 1 and @SearchType = 'D'		
    	if @OccNo = 1 and @SearchType = 'D'	and @IsDisch <> 1	
			set @w = @w + (case when convert(varchar(10), @BirthDate, 111) = '9999/09/01' then ' ' else '(AgeLow <= ' + @UseAge + ') and (' + @UseAge + ' <= AgeHigh) and ' end) + ' 
                    		(MRDxFlag in ' + @MostR + ') 
                    		and ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo]) 
                    		and ([UserDescription] + [cihivalue] + [displaycode] like ''%' + @SearchString + '%'')  '
	--			and ([DisplayCode] between ''' + @CodeStart + ''' AND ''' + @CodeEnd + ''')   PR - 03284
	--				and ([CIHIValue] between ''' + @CodeStart + ''' AND ''' +  @CodeEnd + ''')'
		else
		--ED - 02232 if @BirthDate = 9999/09/01, then do not check age.
			set @w = @w + (case when convert(varchar(10), @BirthDate, 111) = '9999/09/01' then ' '  else '(AgeLow <= ' + @UseAge + ') and (' + @UseAge + ' <= AgeHigh) and ' end) + ' 
                    		([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo]) 
                    		and ([UserDescription] + [cihivalue] + [displaycode] like ''%' + @SearchString + '%'') '
	--			and ([DisplayCode] between ''' + @CodeStart + ''' AND ''' + @CodeEnd + ''')
	--				and ([CIHIValue] between ''' + @CodeStart + ''' AND ''' +  @CodeEnd + ''')'
	end
end

--ED-02091
if @IsDisch = 1
	set @w = @w + 'and IsDischarge = 1'

set @sql = @s + @f + @w + @o
--print @sql
exec(@sql)

return @@ROWCOUNT






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



--exec P_LookUpLink 1455, 'LLU_ProviderSpecialty', '', '0', '2009/04/01', '100146'
--exec P_LookUpLink  812 , 'LLU_ProviderSpecialty', '', '0', '2010/04/01', '0'

-- Uses a 3rd Linking Table to determine what Valid Codes may be selected when 2 tables determine.
CREATE    PROCEDURE [P_LookUpLink]
    @FieldID as int,
    @SearchTable as varchar(50),
    @SearchString as varchar(50),
    @SearchCode as varchar(50) = '0',
    @UseDate as varchar(10),
    @assocID as varchar(10)
as 

declare @return int

declare @sql varchar(5000)
declare @s varchar(2500)
declare @w varchar(2400)
declare @o varchar(100)

declare @LUSourceTable varchar(100)
declare @LUassocTable varchar(100)

if @FieldID = 1452 or @FieldID = 1454 or @FieldID = 50502 or ((@FieldID = 1213 or @FieldID = 4516) and @SearchTable = 'LLU_ProviderServices')-- This is the Provider Service.
begin            
	select @LUSourceTable = 'LU_ProviderService'
	select @LUassocTable = 'LU_Provider'
end

if @FieldID = 1455 or @FieldID = 50501 or ((@FieldID = 1213 or @FieldID = 4517 or @FieldID = 9256 or @FieldID = 812 or @FieldID = 822 or @FieldID = 1185) and @SearchTable = 'LLU_ProviderSpecialty')-- This is the Provider Specialty. --ED-02091 (add 812/822) --NP - 00151
begin
	select @LUSourceTable = 'LU_ProviderSpecialty'
	select @LUassocTable = 'LU_Provider'
end

set @s = 'select 
		[Code] as [ ], 
    		[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
    		[DisplayCode] as [Code Value], 
    		[UserDescription] as [Hospital Description], 
    		[DefaultDescription] as [Default Description],
    		[CIHIValue] as [CIHI Value], 
    		convert(varchar(10), [Validfrom], 111) as [Valid from],
    		convert(varchar(10), [ValidTo], 111) as [Valid To] 
from ' + @LUSourceTable + ' lt '

set @o = 'order by [DisplayCode] '

if @SearchCode <> '0'
	set @w = ' where [Code] = ' + @SearchCode  

else if @assocID = '0' -- No associate set yet (Shows all Codes in range)
begin
	execute P_LookUpStandard @LUSourceTable, @SearchString, @SearchCode, @UseDate
	return 1
end

else if @SearchString = ''
	set @w = ' where [Code] in ' +
            		'(select Code from ' + @SearchTable + ' ' +
                	'where ([Validfrom] <= ''' + @UseDate + ''') ' +
                	'and (''' + @UseDate + ''' <= [ValidTo]) ' +
                	'and [associationID] = ' + @assocID + ') '

else
begin    
	execute @return = P_CheckLUDisplayCode @LUSourceTable, @SearchString, @UseDate --PR-02277
	if @return <> 0 
    		set @w = ' where [Code] in ' +
            			'(select Code from ' + @SearchTable + ' ' +
                		'where ([Validfrom] <= ''' + @UseDate + ''') ' +
                		'and (''' + @UseDate + ''' <= [ValidTo]) ' +
                		'and [DisplayCode] like ''%' + @SearchString + '%'' ' +
                		'and [associationID] = ' + @assocID + ') ' 
	else
	begin
    		set @w = ' where [Code] in ' +
            			'(select Code from ' + @SearchTable + ' ' +
                		'where ([Validfrom] <= ''' + @UseDate + ''') ' +
                		'and (''' + @UseDate + ''' <= [ValidTo]) ' +
                		'and [UserDescription] like ''%' + @SearchString + '%'' ' +
                		'and [associationID] = ' + @assocID + ') ' 

    		set @o = ' order by [UserDescription] '
	end    
end

--PR-04071
set @w = @w + ' and ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo]) '

set @sql = @s + @w + @o
--print @sql
execute (@sql)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- Uses a 3rd Linking Table to determine what Valid Codes may be selected SHOWS ALL. 
CREATE PROCEDURE [P_LookUpLinkFull]
	@FieldID as int,
	@SearchTable as varchar(50),
	@SearchString as varchar(50),
	@SearchCode as varchar(50) = '0',
	@AssocID as varchar(10)
as 

declare @return int

declare @sql varchar(6000)
declare @s varchar(2500)
declare @w varchar(2500)
declare @o varchar(1000)

declare @LUSourceTable varchar(100)
declare @LUassocTable varchar(100)

if @FieldID = 1454 or @FieldID = 50502 or (@FieldID = 1213 and @SearchTable = 'LLU_ProviderServices')-- This is the Provider Service.
begin
	select @LUSourceTable = 'LU_ProviderService'
	select @LUassocTable = 'LU_Provider'
end

else if @FieldID = 1455 or @FieldID = 50501 or (@FieldID = 1213 and @SearchTable = 'LLU_ProviderSpecialty')-- This is the Provider Specialty.
begin 
	select @LUSourceTable = 'LU_ProviderSpecialty'
	select @LUassocTable = 'LU_Provider'
end

set @s = 'select 
		[Code] as [ ], 
        	[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		[DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description], 
		[DefaultDescription] as [Default Description],
		[CIHIValue] as [CIHI Value], 
		convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To] 				
	from ' + @LUSourceTable + ' lt '

set @o = ' order by [DisplayCode] '				

if @SearchCode <> '0'
	set @w = ' where [Code] = ' + @SearchCode

else if @AssocID = '0' -- No associate set yet (Shows all Codes in range)
	set @w = ''

else if @SearchString = ''
	set @w = ' where [Code] in 
			(select Code from ' + @SearchTable + '
			where [associationID] = ' + @AssocID + ')'
else
begin	
	execute @return = P_CheckLUDisplayCode @LUSourceTable, @SearchString, 'NO DATE' --PR-02277
	if @return <> 0 
		set @w = 'where [Code] in 
				(select Code from ' + @SearchTable + '
				where [DisplayCode] like ''%' + @SearchString + '%''  
				and [AssociationID] = ' + @AssocID + ')'
	else
	begin
		set @w = 'where [Code] in 
				(select Code from ' + @SearchTable + '
				where [UserDescription] like ''%' + @SearchString + '%'' 
				and [AssociationID] = ' + @AssocID + ')'
    		
		set @o = ' order by [UserDescription] '
	end
end

set @sql = @s + @w + @o
execute (@sql)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- Called modules like Project Maintenance. Passes the Project # to filter values in Question LU's
CREATE PROCEDURE [P_LookUpMaintassociate]
	@SearchTable as varchar(50),
	@SearchString as varchar(50),
	@SearchCode as varchar(50) = '0',
	@UseDate as varchar(10),
	@AssocID as varchar(10)
as 

declare @return int
declare @sql varchar(5000)
declare @s varchar(2500)
declare @w varchar(2400)
declare @o varchar(100)

set @s = 'select 
		[Code] as [ ], 
        	[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
        	[DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description], 
        	[DefaultDescription] as [Default Description],
		[CIHIValue] as [CIHI Value], 
        	convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To] 				
	from ' + @SearchTable + ' lt '

set @o = ' order by [DisplayCode] '

if @SearchCode <> '0'
	set @w = ' where [Code] = ' + @SearchCode

else if @SearchString = ''
	set @w = ' where [AssociationID] = ' + @AssocID 

else
begin	
	execute @return = P_CheckLUDisplayCode @SearchTable, @SearchString, @UseDate --PR-02277
	if @return <> 0 
		set @w = ' where [DisplayCode] like ''%' + @SearchString + '%''  
    				and [AssociationID] = ' + @AssocID 
	else
	begin
		set @w = 'where [UserDescription] like ''%' + @SearchString + '%'' 
		            	and [AssociationID] = ' + @AssocID 
		
		set @o = ' order by [UserDescription] '
	end
end

set @sql = @s + @w + @o
execute (@sql)

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- Called modules like Project Maintenance. Passes the Project # to filter values in Question LU's
CREATE PROCEDURE [P_LookUpMaintassociateNoCIHI]
	@SearchTable as varchar(50),
	@SearchString as varchar(50),
	@SearchCode as varchar(50) = '0',
	@UseDate as varchar(10),
	@AssocID as varchar(10)
as 

declare @return int
declare @sql varchar(5000)
declare @s varchar(2500)
declare @w varchar(2400)
declare @o varchar(100)

set @s = 'select 
		[Code] as [ ], 
        	[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
        	[DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description], 
		convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To] 				
	from ' + @SearchTable + ' lt '

set @o = ' order by [DisplayCode] '

if @SearchCode <> '0'
	set @w = ' where [Code] = ' + @SearchCode

else if @SearchString = ''
	set @w = ' where [AssociationID] = ' + @AssocID 

else
begin	
	execute @return = P_CheckLUDisplayCode @SearchTable, @SearchString, @UseDate --PR-02277
	if @return <> 0 
		set @w = ' where [DisplayCode] like ''%' + @SearchString + '%''  
		            and [AssociationID] = ' + @AssocID 
	else
	begin
		set @w = ' where [UserDescription] like ''%' + @SearchString + '%'' 
		            and [AssociationID] = ' + @AssocID 
    		
		set @o = ' order by [UserDescription] '
	end
end

set @sql = @s + @w + @o
execute (@sql)


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO















-- Called by the Look Up Maint. - Main. (Different from Standard LU because there
-- is no filtering by Valid Date from/Valid Date To)
CREATE PROCEDURE [P_LookUpMaintenance]
	@SearchTable as varchar(50),
	@SearchString as varchar(50),
	@SearchCode as varchar(50) = '0',
	@HospID as varchar(100) = '0'
as 

declare @return int
declare @sql varchar(5000)
declare @s varchar(2500)
declare @w varchar(2400)
declare @o varchar(100)

set @s = 'select 
		[Code] as [ ], 
        	[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
        	[DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description], 
        	[DefaultDescription] as [Default Description],
		[CIHIValue] as [CIHI Value], 
        	convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To] 				
	from ' + @SearchTable + ' lt '

set @o = ' order by [DisplayCode] '

if @SearchCode <> '0'
	set @w = ' where [Code] = ' + @SearchCode

else if @SearchString = ''
	set @w = ' where (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end)'

else
begin	
	execute @return = P_CheckLUDisplayCode @SearchTable, @SearchString, 'NO DATE', @HospID --PR-02277
	if @return <> 0 
		set @w = ' where [DisplayCode] like ''%' + @SearchString + '%'' 
		            and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
	else
	begin
		set @w = ' where [UserDescription] like ''%' + @SearchString + '%'' 
		            and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
    
		set @o = ' order by [UserDescription] '
	end
end

set @sql = @s + @w + @o
execute (@sql)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO










CREATE    PROCEDURE [P_LookUpNCoderXRef]
	@SearchString as VarChar(50),
	@SearchCode as int = 0,
	@LangID as int
AS 

-- EBV Added @LangID as int parameter

DECLARE @Return INT
if @LangId=10000
begin
	IF @SearchCode <> 0
	BEGIN
		SELECT [Code] AS [ ], 
			[EntryValue] AS [Entry Value], 
			[SearchValue] AS [Search Value]
		FROM NU_CrossReferenceFr
		WHERE [Code] = @SearchCode
		RETURN 1
	END
	ELSE IF @SearchString = ''
	BEGIN
		SELECT [Code] AS [ ], 
			[EntryValue] AS [Entry Value], 
			[SearchValue] AS [Search Value]
		FROM NU_CrossReferenceFr
		ORDER BY [EntryValue]
		RETURN 1
	END
	ELSE
	BEGIN	
		SELECT [Code] AS [ ], 
			[EntryValue] AS [Entry Value], 
			[SearchValue] AS [Search Value]
		FROM NU_CrossReferenceFr
		WHERE [EntryValue] LIKE '%' + @SearchString + '%'  OR [SearchValue] LIKE '%' + @SearchString + '%' ORDER BY [EntryValue]
		RETURN 1
	END
end
if @LangId=0
begin
	IF @SearchCode <> 0
	BEGIN
		SELECT [Code] AS [ ], 
			[EntryValue] AS [Entry Value], 
			[SearchValue] AS [Search Value]
		FROM NU_CrossReference
		WHERE [Code] = @SearchCode
		RETURN 1
	END
	ELSE IF @SearchString = ''
	BEGIN
		SELECT [Code] AS [ ], 
			[EntryValue] AS [Entry Value], 
			[SearchValue] AS [Search Value]
		FROM NU_CrossReference
		ORDER BY [EntryValue]
		RETURN 1
	END
	ELSE
	BEGIN	
		SELECT [Code] AS [ ], 
			[EntryValue] AS [Entry Value], 
			[SearchValue] AS [Search Value]
		FROM NU_CrossReference
		WHERE [EntryValue] LIKE '%' + @SearchString + '%'  OR [SearchValue] LIKE '%' + @SearchString + '%' ORDER BY [EntryValue]
		RETURN 1
	END
end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [P_LookUpNoCIHI]
	@SearchTable as varchar(50),
	@SearchString as varchar(50),
	@SearchCode as varchar(50) = '0',
	@UseDate as varchar(10),
	@HospID as varchar(100) = '0'
as 

declare @return int
declare @sql varchar(5000)
declare @s varchar(2500)
declare @w varchar(2400)
declare @o varchar(100)

set @s = 'select 
		[Code] as [ ], 
        	[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		[DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description], 
		convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To] 				
	from ' + @SearchTable + ' lt '

set @o = ' order by [DisplayCode]'

if @SearchCode <> '0'
	set @w = ' where [Code] = ' + @SearchCode + ' 
        		and ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo])'

else if @SearchString = ''
	set @w = ' where ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo]) 
	        	and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
else
begin	
	execute @return = P_CheckLUDisplayCode @SearchTable, @SearchString, @UseDate, @HospID --PR-02277
	if @return <> 0 
		set @w = ' where ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo]) 
                		and [DisplayCode] like ''%' + @SearchString + '%'' 
		            	and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
	else
	begin
		set @w = ' where ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo]) 
		            	and [UserDescription] like ''%' + @SearchString + '%'' 
		            	and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '

		set @o = ' order by [UserDescription] '
	end
end

set @sql = @s + @w + @o
execute (@sql)    




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE  PROCEDURE [P_LookUpNoCIHIFull]
	@SearchTable as varchar(50),
	@SearchString as varchar(50),
	@SearchCode as varchar(50) = '0',
	@HospID as varchar(100) = '0'
AS 

declare @return int
declare @sql varchar(5000)
declare @s varchar(2500)
declare @w varchar(2400)
declare @o varchar(100)

set @s = 'select 
		[Code] AS [ ], 
        	[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		[DisplayCode] AS [Code Value],
		[UserDescription] AS [Hospital Description], 
		convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To] 				
	from ' + @SearchTable + ' lt '

set @o = ' order by [DisplayCode]'

if @SearchCode <> '0'
	set @w =  ' where [Code] = ' + @SearchCode 

else if @SearchString = ''
	set @w = ' where (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '

else
begin	
	execute @return = P_CheckLUDisplayCode @SearchTable, @SearchString, 'NO DATE', @HospID --PR-02277
	if @return <> 0 
		set @w = ' where [DisplayCode] like ''%' + @SearchString + '%'' 
		        	and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
	else
	begin
		set @w = ' where [UserDescription] like ''%' + @SearchString + '%'' 
		        	and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '

		set @o = ' order by [UserDescription] '
	end
end

set @sql = @s + @w + @o
execute (@sql)




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO









CREATE     PROCEDURE [P_LookUpNU_Codes]
	@SearchTable as VarChar(50),
	@SearchString as VarChar(50),
	@SearchCode as VarChar(50) = '0'
AS 
    set noCount on

	DECLARE @SQL VarChar(1800)
	DECLARE @Return int
	
IF @SearchCode <> '0'
	SELECT @SQL = 'select top 100 [Code] AS [ ], 
				[CodeNum] AS [Code Value],
				[CodeDesc] AS [Hospital Description],
				[CIHIValue] AS [CIHI Value],	 
				Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
				Convert(VarChar(10), [ValidTo], 111)  AS [Valid To], 
	    			AgeLow as [Age Low],
	    			AgeHigh as [Age High],
	    			DiagnosisGender as [Gender],
	    			ICDNotes as [Public Note] 
			from ' + @SearchTable + ' where [Code] = ' + @SearchCode + ' order by [CodeNum]'
	
ELSE IF @SearchString = ''
	SELECT @SQL = 'select top 100 [Code] AS [ ], 
    				[CodeNum] AS [Code Value],
    				[CodeDesc] AS [Hospital Description],
    				[CIHIValue] AS [CIHI Value],	 
    				Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
    				Convert(VarChar(10), [ValidTo], 111)  AS [Valid To], 
                    			AgeLow as [Age Low],
                    			AgeHigh as [Age High],
                    			DiagnosisGender as [Gender],
                    			ICDNotes as [Public Note] 
        			from ' + @SearchTable + ' order by [CodeNum]'
	
ELSE
BEGIN	
	EXECUTE @Return = P_CheckNUCode @SearchTable, @SearchString 
	IF @Return <> 0 
		SELECT @SQL = 'select top 100 [Code] AS [ ], 
    				[CodeNum] AS [Code Value],
    				[CodeDesc] AS [Hospital Description],
    				[CIHIValue] AS [CIHI Value],	 
    				Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
    				Convert(VarChar(10), [ValidTo], 111)  AS [Valid To], 
                    			AgeLow as [Age Low],
                    			AgeHigh as [Age High],
                    			DiagnosisGender as [Gender],
                    			ICDNotes as [Public Note] 
        			from ' + @SearchTable + ' where [CodeNum] like ''%' + @SearchString + '%''order by [CodeNum]'
	ELSE
	SELECT @SQL = 'select top 100 [Code] AS [ ], 
           				[CodeNum] AS [Code Value],
            				[CodeDesc] AS [Hospital Description],
            				[CIHIValue] AS [CIHI Value],	 
            				Convert(VarChar(10), [ValidFrom], 111)  AS [Valid From],
            				Convert(VarChar(10), [ValidTo], 111)  AS [Valid To], 
                            		AgeLow as [Age Low],
                            		AgeHigh as [Age High],
                            		DiagnosisGender as [Gender],
                            		ICDNotes as [Public Note] 
                		from ' + @SearchTable + ' where [CodeDesc] like ''%' + @SearchString + '%'' order by [CodeDesc]'
END

set noCount off

execute (@SQL)
return 1








GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [P_LookUpProvider]
	@SearchString as VarChar(50),
	@SearchCode as int = '0',
	@UseDate as DateTime, 
	@HospID as int = 0
AS 

declare @return int
if @SearchCode <> 0
begin
	select 
		[Code] as [ ], 
	        [LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		[DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description], 
		[DefaultDescription] as [Default Description],
		[CIHIValue] AS [CIHI Value], 
		convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To],
		(select DisplayCode from LU_ProviderService where Code = (select top 1 Code from LLU_ProviderServices where Type = 1 and AssociationID = lt.Code and (([Validfrom] <=  @UseDate) and (@UseDate <= [ValidTo])))) as [Service],
		(select DisplayCode from LU_ProviderSpecialty where Code = (select top 1 Code from LLU_ProviderSpecialty where Type = 1 and AssociationID = lt.Code and (([Validfrom] <=  @UseDate) and (@UseDate <= [ValidTo])))) as [Specialty]
	from LU_Provider lt 
	where [Code] = @SearchCode and ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) order by [DisplayCode]
	return 1
end
else if @SearchString = ''
begin
	select  
		[Code] AS [ ], 
	        [LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		[DisplayCode] AS [Code Value],
		[UserDescription] AS [Hospital Description],
		[DefaultDescription] AS [Default Description],
		[CIHIValue] AS [CIHI Value],	 
		convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To],
		(select DisplayCode from LU_ProviderService where Code = (select top 1 Code from LLU_ProviderServices where Type = 1 and AssociationID = lt.Code and (([Validfrom] <=  @UseDate) and (@UseDate <= [ValidTo])))) AS [Service],
		(select DisplayCode from LU_ProviderSpecialty where Code = (select top 1 Code from LLU_ProviderSpecialty where Type = 1 and AssociationID = lt.Code and (([Validfrom] <=  @UseDate) and (@UseDate <= [ValidTo])))) AS [Specialty]
	from LU_Provider lt
	where ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
	and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	order by [DisplayCode]
	return 1
end
else
begin
	--2.x-0492 -   Provider Search Selection
	--set @return = (select count(*) from lu_provider where displaycode like '%' + @SearchString + '%' and ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)) --PR-02277
	--if @return <> 0 
	--begin	
		select  
			[Code] AS [ ], 
			[LUText] as [l],
			(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
			[DisplayCode] AS [Code Value],
			[UserDescription] AS [Hospital Description],
			[DefaultDescription] AS [Default Description],
			[CIHIValue] AS [CIHI Value],	 
			convert(varchar(10), [Validfrom], 111) as [Valid from],
			convert(varchar(10), [ValidTo], 111) as [Valid To],
			(select DisplayCode from LU_ProviderService where Code = (select top 1 Code from LLU_ProviderServices where Type = 1 and AssociationID = lt.Code and (([Validfrom] <=  @UseDate) and (@UseDate <= [ValidTo])))) AS [Service],
			(select DisplayCode from LU_ProviderSpecialty where Code = (select top 1 Code from LLU_ProviderSpecialty where Type = 1 and AssociationID = lt.Code and (([Validfrom] <=  @UseDate) and (@UseDate <= [ValidTo])))) AS [Specialty]
		from LU_Provider lt
		where ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
		and ([DisplayCode] like '%' + @SearchString + '%' or UserDescription like '%' + @SearchString + '%' )
		and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)	
		order by [DisplayCode]		
		return 1	

	--end	
	--else
	--begin
	--	select 
	--		[Code] AS [ ],  
	--	        [LUText] as [l],
	--		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
	--		[DisplayCode] AS [Code Value],
	--		[UserDescription] AS [Hospital Description],
	--		[DefaultDescription] AS [Default Description],
	--		[CIHIValue] AS [CIHI Value],	 
	--		convert(varchar(10), [Validfrom], 111) as [Valid from],
	--		convert(varchar(10), [ValidTo], 111) as [Valid To],
	--		(select DisplayCode from LU_ProviderService where Code = (select top 1 Code from LLU_ProviderServices where Type = 1 and AssociationID = lt.Code and (([Validfrom] <=  @UseDate) and (@UseDate <= [ValidTo])))) AS [Service],
	--		(select DisplayCode from LU_ProviderSpecialty where Code = (select top 1 Code from LLU_ProviderSpecialty where Type = 1 and AssociationID = lt.Code and (([Validfrom] <=  @UseDate) and (@UseDate <= [ValidTo])))) AS [Specialty]
	--	from LU_Provider lt
	--	where ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
	--	and [UserDescription] like '%' + @SearchString + '%' 
	--	and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	--	order by [UserDescription]
	--	return 1
	--end
end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_LookUpReference]
  	@SearchString as varchar(50),
  	@UseDate as varchar(10),
  	@Country as varchar(10) = ''    --PR - 05485
as 
declare @i int -- PR - 03980
    
set @i = 1
print ''
if @SearchString = '' --or @SearchString = '0'	--PR - 05525 add 0
	select  
		[Code] as [ ], 
        [LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
        [DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description],
		[DefaultDescription] as [Default Description],
		[CIHIValue] as [CIHI Value],	 
		convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To] 
	from LU_PostalCode lt
	where ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
--QA - 00014
--PR - 05485
--else if len (@SearchString) = 5 and isnumeric(@SearchString) = 1 and @Country = 'US'
else if len (@SearchString) < 13 and isnumeric(replace(@SearchString, '-', '')) = 1 and @Country = 'US'
begin
    --PR - 05485
    select  
		9999999 as [ ], 
        '' as [l],
		0 as [H Link],
        'US' as [Code Value],
		'US' as [Hospital Description],
		'US' as [Default Description],
		'US' as [CIHI Value],	 
		convert(varchar(10), cast('1950/01/01' as datetime), 111) as [Valid from],
		convert(varchar(10), cast('2099/03/31' as datetime), 111) as [Valid To] 
end
else
begin
    if(len(@SearchString) > 2)  --PR - 03980
        if isnumeric(left(@SearchString, 1)) = 0 and isnumeric(substring(@SearchString, 2, 1)) = 0
            set @i = 0
    if (@i = 1)  
    begin
  	    select top 1 
		    [Code] as [ ], 
            		    [LUText] as [l],
		    (select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
            		    [DisplayCode] as [Code Value], 
            		    [UserDescription] as [Hospital Description],
		    [DefaultDescription] as [Default Description], 
            		    [CIHIValue] as [CIHI Value],	 
		    convert(varchar(10), [Validfrom], 111) as [Valid from], 
		    convert(varchar(10), [ValidTo], 111) as [Valid To] 
  	    into #PCTemp 
	    from LU_PostalCode lt
	    where ([Validfrom] <= @UseDate and @UseDate <= [ValidTo]) 
	    and CIHIValue in (
		    left( @SearchString, 6 ), 
            left( @SearchString, 5 ), 
            left( @SearchString, 4 ), 
            left( @SearchString, 3 ), 
		    left( @SearchString, 2 ), 
            (case when len(@SearchString) = 2 and isnumeric(substring(@SearchString, 2, 1)) = 0 then @SearchString else left( @SearchString, 1 ) end)
        )
	    order by len(CIHIValue) desc
    
	    if @@Rowcount = 0 set @i = 0
    end
    if @i = 0
	begin
	    if @Country = 'OC'
	    begin
            select  
		        9999999 as [ ], 
                '' as [l],
		        0 as [H Link],
                'OC' as [Code Value],
		        'Other country' as [Hospital Description],
		        'Other country' as [Default Description],
		        'Other country' as [CIHI Value],	 
		        convert(varchar(10), cast('1950/01/01' as datetime), 111) as [Valid from],
		        convert(varchar(10), cast('2099/03/31' as datetime), 111) as [Valid To] 
	        
	    end
	    else
	    begin
		    select  
			    [Code] as [ ], 
            			    [LUText] as [l],
			    (select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
            			    [DisplayCode] as [Code Value], 
            			    [UserDescription] as [Hospital Description],
			    [DefaultDescription] as [Default Description], 
			    [CIHIValue] as [CIHI Value],	 
			    convert(varchar(10), [Validfrom], 111) as [Valid from],
			    convert(varchar(10), [ValidTo], 111) as [Valid To] 
		    into #PCTemp2 
    		    from LU_PostalCode lt
    		    where ([Validfrom] <= @UseDate and @UseDate <= [ValidTo])
    		    and [UserDescription] like '%' + @SearchString + '%'

		    select * from #PCTemp2 
		end
	end
	else
		select * from #PCTemp 
end
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE     PROCEDURE [P_LookUpReports]
	@SearchString as VarChar(50),
	@SearchCode as VarChar(50) = '0',
	@HospID as int = 0
AS 
	DECLARE @Return INT

	IF @SearchCode <> '0'
		BEGIN
			SELECT [Code] AS [ ], 
				(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
				[UserDescription] AS [Report Name], 
				[ReportPath] AS [Report Path],
				Convert(VarChar(10), [ValidFrom], 111) as [Valid From],
				Convert(VarChar(10), [ValidTo], 111) as [Valid To] 				
			FROM LU_Reports lt
			WHERE [Code] = @SearchCode
			RETURN 1
		END
	ELSE IF @SearchString = ''
		BEGIN
			SELECT [Code] AS [ ], 
				(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
				[UserDescription] AS [Report Name], 
				[ReportPath] AS [Report Path],
				Convert(VarChar(10), [ValidFrom], 111) as [Valid From],
				Convert(VarChar(10), [ValidTo], 111) as [Valid To] 				
			FROM LU_Reports lt
			WHERE (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
			ORDER BY [UserDescription]
			RETURN 1
		END
	ELSE
		BEGIN	
			SELECT [Code] AS [ ], 
				(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
				[UserDescription] AS [Report Name], 
				[ReportPath] AS [Report Path],
				Convert(VarChar(10), [ValidFrom], 111) as [Valid From],
				Convert(VarChar(10), [ValidTo], 111) as [Valid To] 				
			FROM LU_Reports lt 
			WHERE [UserDescription] LIKE '%' + @SearchString + '%' 
			AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
			ORDER BY [UserDescription]
			RETURN 1
		END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [P_LookUpROI_Item]
	@SearchString as varchar(50),
	@SearchCode as int = '0',
	@UseDate as DateTime,
	@HospID as int = 0
as 

declare @Return int

if @SearchCode <> 0
	select 
		[Code] as [ ], 
    		[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		[DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description], 
		convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To],
		'$' + ltrim(str(ROIPrice, 10, 2)) as [Fee Level 1],
		'$' + ltrim(str(ROIPrice2, 10, 2)) as [Fee Level 2],
		'$' + ltrim(str(ROIPrice3, 10, 2)) as [Fee Level 3],
		'$' + ltrim(str(ROIPrice4, 10, 2)) as [Fee Level 4],
		'$' + ltrim(str(ROIPrice5, 10, 2)) as [Fee Level 5]
	from LU_ROI_SentItemTypes lt
	where [Code] = @SearchCode 
	and ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
	order by [DisplayCode]

else if @SearchString = ''
	select 
		[Code] as [ ], 
    		[LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
		[DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description],
		convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To],
		'$' + ltrim(str(ROIPrice, 10, 2)) as [Fee Level 1],
		'$' + ltrim(str(ROIPrice2, 10, 2)) as [Fee Level 2],
		'$' + ltrim(str(ROIPrice3, 10, 2)) as [Fee Level 3],
		'$' + ltrim(str(ROIPrice4, 10, 2)) as [Fee Level 4],
		'$' + ltrim(str(ROIPrice5, 10, 2)) as [Fee Level 5]
	from LU_ROI_SentItemTypes lt
	where ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
	and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	order by [DisplayCode]

else
begin
	set @Return = (select count(*) from LU_ROI_SentItemTypes where displaycode like '%' + @SearchString + '%' and ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) and (isnull(HospitalID, 0) = 0 OR isnull(HospitalID, 0) =  @HospID )) --PR-02277
	if @Return <> 0 
		select  
			[Code] as [ ], 
        		[LUText] as [l],
			(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
			[DisplayCode] as [Code Value],
			[UserDescription] as [Hospital Description],
			convert(varchar(10), [Validfrom], 111) as [Valid from],
			convert(varchar(10), [ValidTo], 111) as [Valid To],
			'$' + ltrim(str(ROIPrice, 10, 2)) as [Fee Level 1],
			'$' + ltrim(str(ROIPrice2, 10, 2)) as [Fee Level 2],
			'$' + ltrim(str(ROIPrice3, 10, 2)) as [Fee Level 3],
			'$' + ltrim(str(ROIPrice4, 10, 2)) as [Fee Level 4],
			'$' + ltrim(str(ROIPrice5, 10, 2)) as [Fee Level 5]
		from LU_ROI_SentItemTypes lt
		where ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
		and [DisplayCode] like '%' + @SearchString + '%' 
		and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by [DisplayCode]
	else
		select 
			[Code] as [ ],  
        		[LUText] as [l],
			(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
			[DisplayCode] as [Code Value],
			[UserDescription] as [Hospital Description],
			convert(varchar(10), [Validfrom], 111) as [Valid from],
			convert(varchar(10), [ValidTo], 111) as [Valid To],
			'$' + ltrim(str(ROIPrice, 10, 2)) as [Fee Level 1],
			'$' + ltrim(str(ROIPrice2, 10, 2)) as [Fee Level 2],
			'$' + ltrim(str(ROIPrice3, 10, 2)) as [Fee Level 3],
			'$' + ltrim(str(ROIPrice4, 10, 2)) as [Fee Level 4],
			'$' + ltrim(str(ROIPrice5, 10, 2)) as [Fee Level 5]
		from LU_ROI_SentItemTypes lt
		where ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo]) 
		and [UserDescription] like '%' + @SearchString + '%' 
		and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by [UserDescription]
end



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_LookUpSpecialProjectQuestion]
  	@SearchString as varchar(50),
  	@UseDate as varchar(10),
  	@LookupTable as varchar(100),
  	@HospitalID as int
as 
--ED - 02385
declare @i int 
set @i = 1
print ''
if @SearchString = '' 
	select  
		[Code] as [ ], 
        [LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
        [DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description],
		--[DefaultDescription] as [Default Description],
		[CIHIValue] as [CIHI Value],	 
		convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To] 
	from LU_CodeFile lt
	where LookupID = cast(@LookUpTable as int) and ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo])
else
begin
	select 
		[Code] as [ ], 
        [LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
        [DisplayCode] as [Code Value],
		[UserDescription] as [Hospital Description], 
		--[DefaultDescription] as [Default Description],
		[CIHIValue] as [CIHI Value], 
		convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To] 				
	from LU_CodeFile lt 
	where LookupID = cast(@LookUpTable as int) 
		and ([Validfrom] <= @UseDate) and (@UseDate <= [ValidTo])
		and ([DisplayCode] like '%' + @SearchString + '%' or
			 [CIHIValue] like '%' + @SearchString + '%')
			  --or			 [UserDescription] like '%' + @SearchString + '%')
		and (isnull(HospitalID, 0) = 0 or isnull(@HospitalID, 0) = (case @HospitalID when 0 then 0 else isnull(HospitalID, 0) end)) 

	order by CIHIValue
end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec P_LookUpStandard 'LU_Project', '', 0, '2020/12/31', 0


CREATE    PROCEDURE [P_LookUpStandard]
	@SearchTable as varchar(50),
	@SearchString as varchar(50),
	@SearchCode as varchar(50) = '0',
	@UseDate as varchar(10),
	@HospID as varchar(100) = '0'
as 

declare @Return int
declare @sql varchar(5000)
declare @s varchar(2500)
declare @w varchar(2400)
declare @o varchar(100)
--20585 duplicate ICD_EDInterventionValueSet value
set @s = 'select 
		[Code] as [ ], 
        [LUText] as [l],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
        [DisplayCode] as [Code Value],
		[UserDescription] ' + (case when @SearchTable = 'ICD_EDInterventionValueSet' 
                                then ' + '' - '' + [ShortDescription] '
                                else ''
                            end) + ' as [Hospital Description], 
		[DefaultDescription] as [Default Description],
		[CIHIValue] as [CIHI Value], 
		convert(varchar(10), [Validfrom], 111) as [Valid from],
		convert(varchar(10), [ValidTo], 111) as [Valid To] 				
	from ' + @SearchTable + ' lt '

set @o = ' order by [DisplayCode] '

if @SearchCode <> '0'
	set @w = ' where [Code] = ' + @SearchCode + ' 
            		and ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo]) '

else if @SearchString = ''
	set @w = ' where ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo]) 
	            	and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
else
begin	
	execute @Return = P_CheckLUDisplayCode @SearchTable, @SearchString, @UseDate, @HospID --PR-02277

	if @Return <> 0 
	begin
		if @SearchTable = 'ICD_EDInterventionValueSet'
			set @w = ' where ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo]) 
                			and replace(replace([DisplayCode], ''.'', ''''), ''-'', '''') like ''%' + replace(replace(@SearchString, '.', ''), '-', '') + '%'' 
		            		and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
		else
			set @w = ' where ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo]) 
                			and [DisplayCode] like ''%' + @SearchString + '%'' 
		            		and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
	end
	else
	begin
        if @SearchTable = 'ICD_EDInterventionValueSet'
    		set @w = ' where ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo]) 
    				and ([UserDescription] like ''%' + @SearchString + '%'' or [ShortDescription] like ''%' + @SearchString + '%'' )
		            	and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
        else
    		set @w = ' where ([Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= [ValidTo]) 
    				and [UserDescription] like ''%' + @SearchString + '%'' 
		            	and (isnull(HospitalID, 0) = 0 or ' + @HospID + ' = case ' + @HospID + ' when 0 then 0 else isnull(HospitalID, 0) end) '
    		
		set @o = ' order by [UserDescription]'
	end
end

set @sql = @s + @w + @o
--print @sql
execute (@sql)






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [P_LookUpTophoCode]
   @SearchString as varchar(250) = '',
   @SearchCode as varchar(10) = '0',
   @UseDate as varchar(10),
   @HospID as varchar(100) = '0',
   @FieldID as integer,             -- 'PR - 03322 : Added FieldID 
   @CSVersion as varchar(10) = '',   ---'ED - 02179 : Staging Version
   @MorphoCode as varchar(10) = '' ---'ED - 02192 : Morphology Code
as 

declare @Return int
declare @sql varchar(5000)
declare @where as varchar(500)
declare @order as varchar(100)
declare @sqltext as varchar(50)

--- Feb 20, 2008 Change names of tables 
--LU_CC_SITE_GROUP         = CC_SITE_GROUP
--LLU_CC_STAGE_VALUE       = CC_STAGE_VALUE
--LLU_CC_Topo03_ICD10CA    = CC_Topo03_ICD10CA

-- This Store Proc is execute when Datatype = 69 for these fields:
-- 9062: Topography Code
-- 9064: Morphology Code -O3						ED - 02192
-- 9101: Clinical Stage at Diagnosis
-- 9105: Pathological Stage at Diagnosis
-- 9118: Laterality


-- 04/18/2008: Changes
-- PR - 03496: Clinical Stage at Diagnosis not allowing manual data entry
-- PR - 03495: Laterality table change DisplayCode for CIHIVAlue

--'ED - 02179 : Staging Version only exists 2 data versions: 06 and 07 even thought there are more types of versions.
--'PR - 05045 : Remove link with ICD_DiagFile10 t1 SINCE the search should be base on Topography Code
--'PR - 05131 : Checked all the conditions to get each Field to work as an standard WR-field: F2/free text/enter code

if @CSVersion != '07' and @CSVersion != '06' and @CSVersion != '09' set @CSVersion = '08' 


if @FieldID = 9062    --Topography Code
   begin
   set @sql = 'select distinct
           lt.[Code] as [ ], 
               lt.[LUText] as [l],
           (select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
               lt.[DisplayCode] as [Code Value],
           lt.[UserDescription] as [Hospital Description], 
           lt.[DefaultDescription] as [Default Description],
           lt.[CIHIValue] as [CIHI Value], 
           convert(varchar(10), lt.[Validfrom], 111) as [Valid from],
           convert(varchar(10), lt.[ValidTo], 111) as [Valid To]               
       from LU_CC_Topography lt, ICD_DiagFile10 t1, LLU_CC_Topo03_ICD10CA  t2 where
       t2.ICD10CA = t1.[CIHIValue] and t2.topographyICD_03 = lt.[CIHIValue]   
       and (lt.[Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= lt.[ValidTo])' -- 2.x-1548 replace lt.[DisplayCode] with lt.[CIHIValue]

   set @order =    '  order by lt.[DisplayCode] '
   
   if @SearchString = '0'  -- Look for the code selected after F2
		  set @where  = '  and lt.[Code] = ' + @SearchCode + ''

   else if @SearchString = ''  --- F2 
           set @where = ' and t1.[CIHIValue] like ''%' + @SearchCode  + '%'''   -- PR - 03338' -- 2.x-1548 replace lt.[DisplayCode] with lt.[CIHIValue]

   else         -- Typing the code or free text directly 
     begin
       set @SearchString = ltrim(rtrim(@SearchString))
       set @SearchString = replace(@SearchString, '  ', ' ')

		       
         set @where = ' and ((lt.[UserDescription] like ''%' + @SearchString + '%''  
                 and t1.[CIHIValue] like ''%' + @SearchCode  + '%'') or '   -- PR - 03338 -- 2.x-1548 replace lt.[DisplayCode] with lt.[CIHIValue]
             + ' (lt.[DisplayCode] like ''%' + @SearchString + '%''  
                 and t1.[CIHIValue] like ''%' + @SearchCode  + '%''))'      -- 2.x-1548 replace lt.[DisplayCode] with lt.[CIHIValue]
                 
     end

   end 
else if @FieldID in (9101, 9105, 9126) -- For Clinical & Pathological Stage at Diagnosis --2.x-1503 Add Post Therapy Stage
   begin  
	   -- ED - 02192: Add Morphology Code -03 filter (use LLU_CC_ICD03_Topo_Morpho instead of LLU_CC_SITE_GROUP)
      set @sql = 'select distinct 
           t2.[Code] as [ ], 
               NULL as [l],
           NULL as [H Link],
               t2.[STAGE] as [Hospital Description], 
           (case when  isnumeric(t2.[AJCC_SITE_GRP]) = 1 then 
                 (select UserDescription from dbo.LU_AJCC7_SITE_GRP where DisplayCode like isnull(t2.[AJCC_SITE_GRP], '''') and t2.[Staging_Version] = LU_AJCC7_SITE_GRP.Staging_Version)
                else t2.[AJCC_SITE_GRP] end) as [Code Value],
            (case when  isnumeric(t2.[AJCC_SITE_GRP]) = 1 then 
                 (select UserDescription from dbo.LU_AJCC7_SITE_GRP where DisplayCode like isnull(t2.[AJCC_SITE_GRP], '''') and t2.[Staging_Version] = LU_AJCC7_SITE_GRP.Staging_Version )
                else t2.[AJCC_SITE_GRP] end) as [Default Description],
           '''' as [CIHI Value], 
           convert(varchar(20), t2.ValidFrom, 111) as [Valid from],
           convert(varchar(20), t2.ValidTo,   111) as [Valid To]               
       from LLU_CC_ICD03_Topo_Morpho gp, LLU_CC_STAGE_VALUE t2 where gp.AJCC_SITEGRP_CD =   t2.AJCC_SITE_GRP and gp.[Staging_Version] = t2.[Staging_Version]
       AND gp.Stageable_Flag = ''Y'' and ''' + @UseDate + ''' between t2.ValidFrom and t2.ValidTo ' 
      + ' and gp.Staging_Version = ''' + @CSVersion + ''' and gp.ICDO3_Morpho = substring(''' 
      + @MorphoCode + ''' , 1, 4)' --'ED - 02179 
      
   set @order =     '  order by t2.[Code], t2.[STAGE] '
   
   if @SearchString = ''   --- F2                                                     
           set @where = ' and gp.ICDO3_TOPO like ''%' + @SearchCode  + '%'''   
   else
     begin
		   set @SearchString = ltrim(rtrim(@SearchString))
		   set @SearchString = replace(@SearchString, '  ', ' ')
	   
    	  if isnumeric(@SearchCode) = 1 
			   set  @where =  ' and t2.[Code] = ' +  @SearchCode + ''
		  else                                                         
		    begin 
		           if  @CSVersion in ('07', '08') and isnumeric(@SearchString) <> 1   --case1: @SearchString "Pros" ; @SearchCode "c619"
		               begin 
						   select @sqlText = DisplayCode from dbo.LU_AJCC7_SITE_GRP where userDescription like isnull('%' + @SearchString + '%', '')
						   
						   set @where = ' and ((t2.[AJCC_SITE_GRP] like ''%'  + @sqlText + '%'' and gp.ICDO3_TOPO like ''%' + @SearchCode  + '%'') or '   
												   +  ' (  t2.[STAGE] like ''%' + @SearchString + '%''   and gp.ICDO3_TOPO like ''%' + @SearchCode  + '%''))'
												   
					   end 
					 else if @CSVersion in ('07', '08') and isnumeric(@SearchString)  = 1 --case2:@SearchString "3" ; @SearchCode "c619"
							   set @where = ' and ( t2.[STAGE]  like ''%' + @SearchString + '%'') and gp.ICDO3_TOPO like ''%' + @SearchCode  + '%''' 
							   
				     else if  @CSVersion = '06' -- case3: -----@SearchString 'Prostate', @SearchCode 'C619', version '06'
						       set @where = ' and ( t2.[AJCC_SITE_GRP] + t2.[STAGE]  like ''%' + @SearchString + '%'')and gp.ICDO3_TOPO like ''%' + @SearchCode  + '%''' 
			end  
     end
   end
else if @FieldID = 9118 -- Laterality
    begin
				   
   set @sql = 'select distinct
           lt.[Code] as [ ], 
               lt.[LUText] as [l],
           (select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
               lt.[DisplayCode] as [Code Value],
               lt.[UserDescription] as [Hospital Description], 
               lt.[DefaultDescription] as [Default Description],
               lt.[CIHIValue] as [CIHI Value], 
               convert(varchar(10), lt.[Validfrom], 111) as [Valid from],
               convert(varchar(10), lt.[ValidTo], 111) as [Valid To]               
       from LU_CodeFile lt, LLU_CC_Topo03_Laterality t2  where 
       t2.LateralityCode = lt.[DisplayCode]   and LookupID  = 1002
       and (lt.[Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= lt.[ValidTo])
       and (t2.[Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= t2.[ValidTo])'

   set @order =    '  order by lt.[DisplayCode] '
   
   if @SearchString = ''    --- F2 
			   -- PR - 03495: set @where = ' and t1.[DisplayCode] like ''%' + @SearchCode  + '%''' 
       set @where = ' and t2.[TopographyICD_03] like ''%' + @SearchCode  + '%''' 

   else    -- Typing the code directly 
     begin
		   set @SearchString = ltrim(rtrim(@SearchString))
		   set @SearchString = replace(@SearchString, '  ', ' ')

		   set @where = ' and (lt.[DisplayCode] + lt.[UserDescription] like ''%' + @SearchString + '%''
					   and t2.[TopographyICD_03] like ''%' + @SearchCode  + '%'')'
	       
		   -- PR - 05131: added this condition when Look for the code selected after F2           
		   if isnumeric(@SearchCode) = 1 
			   set  @where =  @where +  ' OR lt.[Code] = ' +  @SearchCode + ''
	                 
     end

    end 
    else if @FieldID in (9064) -- Morphology Code -O3  ED - 02192
    --	Get data to populate this field based on the Topo code 03 selected.
       begin
   set @sql = 'select distinct
           lt.[Code] as [ ], 
               lt.[LUText] as [l],
           (select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
               lt.[DisplayCode] as [Code Value],
           lt.[UserDescription] as [Hospital Description], 
           lt.[DefaultDescription] as [Default Description],
           lt.[CIHIValue] as [CIHI Value], 
           convert(varchar(10), lt.[Validfrom], 111) as [Valid from],
           convert(varchar(10), lt.[ValidTo], 111) as [Valid To]               
       from LU_CC_Morphology_O3 lt, LLU_CC_ICD03_Topo_Morpho t1 where
       SUBSTRING(lt.[CIHIValue],1,4)= t1.ICDO3_Morpho and 
       (t1.[Validfrom] <= ''' + @UseDate + ''') and (''' + @UseDate + ''' <= t1.[ValidTo])'
 
    set @order =    '  order by lt.[DisplayCode] '

   if @SearchString = '0'  -- Look for the code selected after F2
       set @where  = '  and lt.[Code] = ' + @SearchCode + ''

   else if @SearchString = ''  --- F2 
           set @where = ' and t1.[ICDO3_TOPO] like ''%' + @SearchCode  + '%'''   -- PR - 03338' 

   else         -- Typing the code directly 
     begin
       set @SearchString = ltrim(rtrim(@SearchString))
       set @SearchString = replace(@SearchString, '  ', ' ')

                   
       set @where = ' and  (lt.[DisplayCode] + lt.[UserDescription] + lt.[cihivalue] like ''%' + @SearchString + '%'' )
                   and t1.[ICDO3_TOPO] like ''%' + @SearchCode  + '%''' 
     end
   end 

set @sql = @sql + @where + @order

--print @sql
execute (@sql)

return @@ROWCOUNT
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [P_LookUpUsers]
	@SearchString as VARCHAR(50) = '',
	@SearchCode as INTEGER = 0,
	@CurrentUser as INTEGER = 0,
	@HospID as int = 0

as 
declare @Return int
declare @count int 

if @SearchCode <> 0
	select distinct 
		F.UserID as [ ],
    		U.LUText as [  ],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(U.HospitalID, 0)) as [H Link],
		U.DisplayCode as [Code Value], 
		U.UserDescription as [Description]
	from U_Users U inner join (select distinct userid from u_usersfields) f on U.Code = F.UserID
	where F.UserID = @SearchCode

else if @SearchString = ''
	select distinct 
		F.UserID as [ ],
    		U.LUText as [  ],
		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(U.HospitalID, 0)) as [H Link],
		U.DisplayCode as [Code Value], 
		U.UserDescription as [Description]
	from U_Users U inner join (select distinct userid from u_usersfields) f on U.Code = F.UserID
	where F.UserID <> @CurrentUser
	and isnull(U.RoleID, 0) <= 0
	and U.DisplayCode like '%' + @SearchString + '%'
	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	order by U.DisplayCode 

else
begin
	select @count = count(distinct F.UserID) from U_Users U inner join (select distinct userid from u_usersfields) F on U.Code = F.UserID where F.UserID <> @CurrentUser and isnull(U.RoleID, 0) <= 0 and U.DisplayCode like '%' + @SearchString + '%' and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end) --PR-02277
	if @count > 0
		select distinct 
			F.UserID as [ ],
        		U.LUText as [  ],
			(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(U.HospitalID, 0)) as [H Link],
			U.DisplayCode as [Code Value], 
			U.UserDescription as [Description]
		from U_Users U inner join (select distinct userid from u_usersfields) f on U.Code = F.UserID
		where F.UserID <> @CurrentUser
		and isnull(U.RoleID, 0) <= 0
		and U.DisplayCode like '%' + @SearchString + '%'
		and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by U.DisplayCode 
	else		
		select distinct 
			F.UserID as [ ],
        		U.LUText as [  ],
			(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(U.HospitalID, 0)) as [H Link],
			U.DisplayCode as [Code Value], 
			U.UserDescription as [Description]
		from U_Users U inner join (select distinct userid from u_usersfields) f on U.Code = F.UserID
		where F.UserID <> @CurrentUser
		and isnull(U.RoleID, 0) <= 0
		and U.UserDescription like  '%' + @SearchString + '%' 
		and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
		order by U.UserDescription
end



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [P_LookUpVisit]
	@SearchCode as Integer,
	@ChartNumber as varchar(10),
	@HospID as int = 0
AS 
set nocount on

Create TABLE #visit(
	[UniversalID] [bigint],
	[AbstractID] [int],
    [AppID] int,
	[Hospital] [varchar] (250) COLLATE Latin1_General_CI_AS  ,
    VisitDate datetime,
    VisitTime datetime,
	[CareType] [varchar] (250) COLLATE Latin1_General_CI_AS  ,
	[EncounterNumber] [varchar] (50) COLLATE Latin1_General_CI_AS  ,
	[EncounterSequence] int
) 

if @SearchCode <> 0
begin
    insert into #visit(UniversalID, AbstractID, AppID, Hospital, VisitDate, VisitTime, CareType, EncounterNumber, EncounterSequence)
 	select 
 		UniversalID, AbstractID, AppID, 
 		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)),
 		(case when lt.AppID in (201, 101, 100, 200, 202, 102) then isnull(DischargeDate, AdmitDate) else AdmitDate end),  
 		(case when lt.AppID in (201, 101, 100, 200, 202, 102) then (case when DischargeDate is null then AdmitTime else DischargeTime end) else AdmitTime end),  
 		'Inst:' + isnull(H.CIHIValue, '') + ', Care Type:' + 
 		convert(varchar(1), (select DisplayCode from LU_CareType where Code = AppType)) + 
        '', 
 		isnull(EncounterNumber, ''), EncounterSequence
--PR - 02770
-- 		UniversalID, 
-- 		'' as [LUText], 
-- 		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
-- 		convert(varchar(10), (case when AppID in (201, 101, 100, 200, 202, 102) then DischargeDate else AdmitDate end), 111) as [Visit Date],  
-- 		isnull(ICDType, '') + ': ' + 
-- 		convert(varchar(1), (select DisplayCode from LU_CareType where Code = AppType)) + ': ' + 
-- 		isnull(EncounterNumber, '') + ' - ' + 
-- 		replace(space(3-len(isnull(convert(varchar(3), EncounterSequence), 0))) + isnull(convert(varchar(3), EncounterSequence), 0), ' ', '0')  as [Abstract Information]
	from AB_Main lt
        left join H_InstitutionProfile h on lt.InstitutionNumber = h.code
	where UniversalID = @SearchCode
	and isnull(IsDeleted, 0) = 2 and AppType <> 0
--	order by [Visit Date] desc
end

else
begin
    insert into #visit(UniversalID, AbstractID, AppID, Hospital, VisitDate, VisitTime, CareType, EncounterNumber, EncounterSequence)
 	select 
 		UniversalID, AbstractID, AppID, 
 		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)),
 		(case when lt.AppID in (201, 101, 100, 200, 202, 102) then Isnull(DischargeDate, AdmitDate) else AdmitDate end),  
 		(case when lt.AppID in (201, 101, 100, 200, 202, 102) then (case when DischargeDate is null then AdmitTime else DischargeTime end) else AdmitTime end),  
 		'Inst:' + isnull(H.CIHIValue, '') + ', Care Type:' + 
 		convert(varchar(1), (select DisplayCode from LU_CareType where Code = AppType)) + 
        '', 
 		isnull(EncounterNumber, ''), EncounterSequence
--PR - 02770
-- 		UniversalID, 
-- 		'' as [LUText], 
-- 		(select top 1 DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [H Link],
-- 		convert(varchar(10), (case when AppID in (201, 101, 100, 200, 202, 102) then DischargeDate else AdmitDate end), 111) as [Visit Date],  
-- 		isnull(ICDType, '') + ': ' + 
-- 		convert(varchar(1), (select DisplayCode from LU_CareType where Code = AppType)) + ': ' + 
-- 		isnull(EncounterNumber, '') + ' - ' + 
-- 		replace(space(3-len(isnull(convert(varchar(3), EncounterSequence), 0))) + isnull(convert(varchar(3), EncounterSequence), 0), ' ', '0')  as [Abstract Information]
	from AB_Main lt
        left join H_InstitutionProfile h on lt.InstitutionNumber = h.code
	--PR-00616
	where ChartNumber = @ChartNumber
	and (isnull(lt.HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(lt.HospitalID, 0) end) 	
	and isnull(IsDeleted, 0) = 2 and AppType <> 0
--	order by [Visit Date] desc
end

--PR - 02770
Create index idx_lookupvisit_AbstractID on #visit(AbstractID)
Create index idx_lookupvisit_AppID on #visit(AppID)

--Rehab
if exists (select * from #visit where AppID between 250 and 253)
    update #visit
    set VisitDate = (case AppID when 251 then isnull(r.DischargeDate, r.AdmitDate)
                                when 252 then isnull(isnull(r.FollowUpDate, r.DischargeDate), r.AdmitDate)
                                when 253 then isnull(r.DischargeDate, r.AdmitDate)
                                else v.VisitDate end),
        CareType  = v.CareType + isnull('-' + a.DisplayCode, '')
    from #visit v 
        inner join dbo.RH_ClientInfo r on v.AbstractID = r.AbstractID
        left  join LU_CodeFile a on r.AssessmentType = a.code
    where v.AppID between 250 and 253

--CCRS
if exists (select * from #visit where AppID between 470 and 475)
    update #visit
    set VisitDate = (case when a.CIHIValue in ('02', '03', '04', '05', '10') then isnull(r.A3, r.AdmitDate)
                          when a.CIHIValue in ('06', '07', '08') then isnull(r.DischargeDate, r.AdmitDate)
                          when a.CIHIValue = '00' then isnull(r.Z7, r.AdmitDate)
                          when a.CIHIValue = '09' then isnull(r.AB1b, r.AdmitDate)
                          else v.VisitDate end),
        CareType  = v.CareType + isnull('-' + a.DisplayCode, ''),
        EncounterNumber = r.AA1, 
        EncounterSequence = 0
    from #visit v 
        inner join dbo.CRS_Demographic r on v.AbstractID = r.AbstractID
        left  join LU_CodeFile a on r.AA8 = a.code
    where v.AppID between 470 and 475

--OMHRS
if exists (select * from #visit where AppID between 650 and 654)
    update #visit
    set VisitDate = (case when a.CIHIValue in ('4', '6') then isnull(seca.A1, r.AdmitDate)
                          when a.CIHIValue in ('5') then isnull(secs.X80, r.AdmitDate)
                          else v.VisitDate end),
        CareType  = v.CareType + isnull('-' + a.DisplayCode, ''),
        EncounterNumber = r.AA3, 
        EncounterSequence = 0
    from #visit v 
        inner join dbo.OMHRS_SecAA r on v.AbstractID = r.AbstractID
        left  join LU_CodeFile a on r.Z1 = a.code
        left  join dbo.OMHRS_SecA seca on r.AbstractID = seca.AbstractID
        left  join dbo.OMHRS_SecS secs on r.AbstractID = secs.AbstractID
    where v.AppID between 650 and 654

--Cancer Care
if exists (select * from #visit where AppID between 675 and 676)
    update #visit
    set VisitDate = (case v.AppID when 676 then isnull(n.FirstTreatDate, t.RegisterDate)
                                  else v.VisitDate end) --,
        --CareType  = v.CareType + isnull('-' + a.DisplayCode, '')
    from #visit v 
        inner join dbo.CC_Demographic r on v.AbstractID = r.AbstractID
        left  join dbo.CC_Demographic d on r.AbstractID = d.AbstractID
        left  join dbo.CC_DiseaseRegister t on r.AbstractID = t.AbstractID
        left  join dbo.CC_NDFP n on r.AbstractID = n.AbstractID
    where v.AppID between 675 and 676



	select 
 		UniversalID, 
 		'' as [LUText], 
 		Hospital as [H Link],
        VisitDate as [Visit Date],  
 		CareType + ', ENC:' + isnull(EncounterNumber, '') + 
        (case when isnull(EncounterNumber, '') = '' or isnull(EncounterSequence, 0) = 0 then '' 
              else ' - ' +	replace(space(3-len(isnull(convert(varchar(3), EncounterSequence), 0))) + isnull(convert(varchar(3), EncounterSequence), 0), ' ', '0')  
              end) +
        (case when VisitTime is null then '' else ', Visit Time: ' + left(convert(varchar(20), VisitTime, 114), 5) end) as [Abstract Information]   --0652 -   Add Visit Time to Visit Date LU table
    from #visit
    order by visitdate desc

set nocount off

return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [P_LookUpVolume]
	@SearchString AS varchar(50) = '',
	@SearchCode AS INTEGER = 0,
	@CurrentVolume AS INTEGER = 0,
	@PatientID AS INTEGER = 0,
	@HospID as int = 0
AS 

declare @Return int

if @SearchCode <> 0
	select 
		VolumeID AS [ ], 
    		'' as [  ],
		(select DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [Hospital Link],
		VolumeNumber AS [Code Value], 
		isnull((select DisplayCode from LoanLU_VolumeType where Code = lt.VolumeType), '') + ' - ' + 	
		isnull(convert(varchar(10), VolumeDatefrom, 111), '')+ ' - ' + isnull(convert(varchar(10), VolumenDateTo, 111), '') AS [Description]
	from CM_CPI_Volume lt
	where VolumeID = @SearchCode
	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)

else if @SearchString = ''
	select 
		VolumeID AS [ ], 
		'' as [  ],
		(select DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [Hospital Link],
		VolumeNumber AS [Code Value], 
		isnull((select DisplayCode from LoanLU_VolumeType where Code = lt.VolumeType), '') + ' - ' + 	
		isnull(convert(varchar(10), VolumeDatefrom, 111), '')+ ' - ' + isnull(convert(varchar(10), VolumenDateTo, 111), '') AS [Description]
	from CM_CPI_Volume lt
	where PatientID = @PatientID
	and VolumeID <> @CurrentVolume
	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	order by VolumeNumber

else
	select 
		VolumeID AS [ ], 
     		'' as [  ],
		(select DisplayCode from H_HospitalProfile where Code = isnull(lt.HospitalID, 0)) as [Hospital Link],
		VolumeNumber AS [Code Value], 
		isnull((select DisplayCode from LoanLU_VolumeType where Code = lt.VolumeType), '') + ' - ' + 	
		isnull(convert(varchar(10), VolumeDatefrom, 111), '')+ ' - ' + isnull(convert(varchar(10), VolumenDateTo, 111), '') AS [Description]
	from CM_CPI_Volume lt
	where VolumeNumber like '%' + @SearchString + '%' 
	and PatientID = @PatientID
	and VolumeID <> @CurrentVolume
	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	order by VolumeNumber


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [P_LUPopulate] 
AS 

SELECT * FROM ABz_LU_Default




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_MultipleContacts]
	@EncounterNumber as varchar(20),
	@InstNumber as Int,
	@Chartnumber as varchar(10),
	@AdmitDate as datetime,
	@AdmitTime as datetime --PR-3109
as 

declare @SQL as Nvarchar(1000)
--if @EncounterNumber = '' set @EncounterNumber = 'WXX' --PR - 03658
-- PR-00673
-- PR-02562 -- if @AdmitDate >= '2006/04/01' set @EncounterNumber = 'WXX'

select 
	AbstractID,
	replace(space(3-len(isnull(convert(varchar(3),EncounterSequence), 0))) + isnull(convert(varchar(3),EncounterSequence), 0), ' ', '0') as [Sequence],
	(select DisplayCode + ' - ' + UserDescription from LU_MISCode where Code = MISCode) as [MIS Code]
from AB_Abstract 
where InstitutionNumber	= @InstNumber
and Chartnumber 	= @Chartnumber 
and AdmitDate 		= @AdmitDate 
and isnull(EncounterNumber, '@@')	= @EncounterNumber --PR - 04213 put isnull
and @EncounterNumber <> ''  --????? no multi contact if encounter number is blank
and [dbo].[Get4DigitTime](AdmitTime) = [dbo].[Get4DigitTime](@AdmitTime) --PR-03109
and IsDeleted 	    = 2 
order by EncounterSequence
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE     PROCEDURE [P_MultipleContactsClinic]
	@EncounterNumber AS VarChar(20)
AS 

	SELECT dbo.CR_Visit.AbstractID, 
		REPLACE(SPACE(3-LEN(ISNULL(CONVERT(VARCHAR(3),EncounterSequence), 0))) + ISNULL(CONVERT(VARCHAR(3),EncounterSequence), 0), ' ', '0') AS [Sequence],
		(SELECT DisplayCode FROM LU_Provider WHERE Code = ProviderNumber) AS [Provider]
	FROM dbo.CR_Demographic INNER JOIN dbo.CR_Visit ON dbo.CR_Demographic.AbstractID = dbo.CR_Visit.AbstractID
	WHERE (EncounterNumber = @EncounterNumber) AND IsDeleted = 2
	ORDER BY EncounterSequence



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE           PROCEDURE [P_MultipleNDFP] 
	(@LinkID as int)
as 


select ChartNumber as [Chart Number], CC_NDFP.AbstractID as ID,  NDFPNumber as [NDFP Number] , NDFPVersion as Version,  convert(varchar(20), FirstTreatDate, 111) as [First Treatment] 
from CC_Demographic, CC_NDFP, CC_RecordInfo
where AppID = 676 and CC_Demographic.LinkID = @LinkID and CC_Demographic.AbstractID = CC_NDFP.AbstractID 
and CC_Demographic.AbstractID = CC_RecordInfo.AbstractID   and  IsDeleted  = 2 
order by CC_NDFP.AbstractID

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO












CREATE  PROCEDURE [P_NCoder]
	@DischargeDate as VarChar(10),
	@Gender AS VarChar(1) = '', 
	@ICDType as VarChar(2) = '9',
	@Age AS int,
	@DiagProc as int
AS 

IF @ICDType = '9' and @DiagProc = 1
	BEGIN
		SELECT     Code, DisplayCode, ValidFrom, ValidTo
		FROM         dbo.ICD_DiagFile9
		WHERE     (AgeLow <= @Age) AND (@Age <= AgeHigh) AND (ValidFrom <= @DischargeDate) And 
		(ValidTo >= @DischargeDate) AND (DiagnosisGender = N'' OR DiagnosisGender = @Gender)
	END
ELSE IF @ICDType = '9' and @DiagProc = 2
	BEGIN
		SELECT     Code, DisplayCode, ValidFrom, ValidTo
		FROM         dbo.ICD_ProcFile9
		WHERE     (AgeLow <= @Age) AND (@Age <= AgeHigh) AND (ValidFrom <= @DischargeDate) And 
		(ValidTo >= @DischargeDate) AND (DiagnosisGender = N'' OR DiagnosisGender = @Gender)
	END
ELSE IF @ICDType = 'C' and @DiagProc = 1
	BEGIN
		SELECT     Code, DisplayCode, ValidFrom, ValidTo
		FROM         dbo.ICD_DiagFile9cm
		WHERE     (AgeLow <= @Age) AND (@Age <= AgeHigh) AND (ValidFrom <= @DischargeDate) And 
		(ValidTo >= @DischargeDate) AND (DiagnosisGender = N'' OR DiagnosisGender = @Gender)
	END
ELSE IF @ICDType = 'C' and @DiagProc = 2
	BEGIN
		SELECT     Code, DisplayCode, ValidFrom, ValidTo
		FROM         dbo.ICD_ProcFile9cm
		WHERE     (AgeLow <= @Age) AND (@Age <= AgeHigh) AND (ValidFrom <= @DischargeDate) And 
		(ValidTo >= @DischargeDate) AND (DiagnosisGender = N'' OR DiagnosisGender = @Gender)
	END
ELSE IF @ICDType = 'T' and @DiagProc = 1
	BEGIN
		SELECT     Code, DisplayCode, ValidFrom, ValidTo
		FROM         dbo.ICD_DiagFile10
		WHERE     (AgeLow <= @Age) AND (@Age <= AgeHigh) AND (ValidFrom <= @DischargeDate) And 
		(ValidTo >= @DischargeDate) AND (DiagnosisGender = N'' OR DiagnosisGender = @Gender)
	END
ELSE IF @ICDType = 'T' and @DiagProc = 2
	BEGIN
		SELECT     Code, DisplayCode, ValidFrom, ValidTo
		FROM         dbo.ICD_ProcFile10
		WHERE     (AgeLow <= @Age) AND (@Age <= AgeHigh) AND (ValidFrom <= @DischargeDate) And 
		(ValidTo >= @DischargeDate) AND (DiagnosisGender = N'' OR DiagnosisGender = @Gender)
	END











GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO












CREATE   PROCEDURE [P_NCoderProb]
   @InstNumber as int = 0,
   @KeyDate as Varchar(10),
   @DiagString as Varchar(200)
AS

Declare @SQL as nVarChar(2000)

If @InstNumber = 0
Begin
   Set @SQL = 'SELECT TOP 10 dbo.AB_Intervention.IntervCode AS [ ], COUNT(dbo.AB_Intervention.IntervCode) AS IntCount, dbo.ICD_ProcFile10.DisplayCode, 
   dbo.ICD_ProcFile10.UserDescription FROM dbo.AB_Abstract LEFT OUTER JOIN
   dbo.AB_Diagnosis ON dbo.AB_Abstract.AbstractID = dbo.AB_Diagnosis.AbstractID LEFT OUTER JOIN
   dbo.AB_Intervention LEFT OUTER JOIN
   dbo.ICD_ProcFile10 ON dbo.AB_Intervention.IntervCode = dbo.ICD_ProcFile10.Code ON 
   dbo.AB_Diagnosis.AbstractID = dbo.AB_Intervention.AbstractID
   WHERE (dbo.AB_Diagnosis.DiagnosisCode IN (' + @DiagString + ')) AND (dbo.AB_Diagnosis.DiagnosisICDType = ''T'') AND (ISNULL(dbo.AB_Intervention.IntervCode, 0) <> 0)
   and (dbo.ICD_ProcFile10.ValidTo >= CONVERT(DATETIME, ' + @KeyDate + ', 102)) AND (dbo.AB_Abstract.AdmitDate >= CONVERT(DATETIME, 
   DATEADD ( yy , -1, ' + @KeyDate + ') , 102))
   GROUP BY dbo.AB_Intervention.IntervCode, dbo.ICD_ProcFile10.ValidTo, dbo.ICD_ProcFile10.DisplayCode, dbo.ICD_ProcFile10.UserDescription
   ORDER BY COUNT(dbo.AB_Intervention.IntervCode) DESC'
   exec sp_executesql @SQL
End
Else
Begin
   Set @SQL = 'SELECT distinct TOP 10 dbo.AB_Intervention.IntervCode AS [ ], COUNT(dbo.AB_Intervention.IntervCode) AS IntCount, dbo.ICD_ProcFile10.DisplayCode, 
   dbo.ICD_ProcFile10.UserDescription FROM dbo.AB_Abstract LEFT OUTER JOIN
   dbo.AB_Diagnosis ON dbo.AB_Abstract.AbstractID = dbo.AB_Diagnosis.AbstractID LEFT OUTER JOIN
   dbo.AB_Intervention LEFT OUTER JOIN
   dbo.ICD_ProcFile10 ON dbo.AB_Intervention.IntervCode = dbo.ICD_ProcFile10.Code ON 
   dbo.AB_Diagnosis.AbstractID = dbo.AB_Intervention.AbstractID
   WHERE (dbo.AB_Diagnosis.DiagnosisCode IN (' + @DiagString + ')) AND (dbo.AB_Diagnosis.DiagnosisICDType = ''T'') AND (ISNULL(dbo.AB_Intervention.IntervCode, 0) <> 0)
   and (dbo.ICD_ProcFile10.ValidTo >= CONVERT(DATETIME, ' + @KeyDate + ', 102)) AND (dbo.AB_Abstract.AdmitDate >= CONVERT(DATETIME, 
   DATEADD ( yy , -1, ' + @KeyDate + ') , 102)) AND (dbo.AB_Abstract.InstitutionNumber = ' + Cast(@Instnumber as Varchar(10)) + ') 
   GROUP BY dbo.AB_Intervention.IntervCode, dbo.ICD_ProcFile10.ValidTo, dbo.ICD_ProcFile10.DisplayCode, dbo.ICD_ProcFile10.UserDescription
   ORDER BY COUNT(dbo.AB_Intervention.IntervCode) DESC'
   exec sp_executesql @SQL
End











GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [P_OMHRSCIHIErrorList]
	@AbstractID AS INT,
    @Coder      as int
AS 
set nocount on
declare @CIHIDateSent datetime
set @CIHIDateSent = isnull((select max(CIHIDateSent) from dbo.OMHRS_RecInfo where abstractid = @AbstractID), '1950/01/01')

SELECT distinct
[Element] = ElementCode
, [Err #] = RuleNumber
, [Error] = ErrorMessage
, [CIHI File] = ErrorFileName
FROM dbo.OMHRS_CIHIErrors
WHERE AbstractID = @AbstractID
    and ImportDateTime > @CIHIDateSent
set nocount off

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [P_Rehab_KeyFieldUpdated]
    @AbstractID int
as

--PR - 04347
declare @NewID int
declare @sql varchar(8000)
declare @field varchar(100)
declare @table varchar(100)
declare @cur_table varchar(100)
declare @LinkID int
declare @NewLinkID int
declare @count int

set @LinkID = (select LinkID from RH_ClientInfo where abstractid = @AbstractID)

set @count = 0
declare cur_RH_Selection cursor for
    select AbstractID
    from RH_ClientInfo
    where LinkID = @LinkID and IsDeleted = 2 and IsSubmited = 1
    order by AssessmentType 
open cur_RH_Selection
fetch next from cur_RH_Selection into @AbstractID
while(@@fetch_status = 0)
begin
    set @sql = ''
    declare cur_RH_ClientInfo cursor for
        select column_name from information_schema.columns 
        where table_name = 'RH_ClientInfo' and column_name not in ('AbstractID', 'IsCorrected', 'IsDeleted', 'LinkID')
    open cur_RH_ClientInfo
    fetch next from  cur_RH_ClientInfo into @field
    while(@@fetch_status = 0)
    begin
        set @sql = @sql + ', ' + @field
        fetch next from  cur_RH_ClientInfo into @field
    end
    close cur_RH_ClientInfo
    deallocate cur_RH_ClientInfo

    set @NewID = (select max(abstractid) from dbo.RH_ClientInfo) + 1
    if @count = 0
    begin
        set @count = 1
        set @NewLinkID = @NewID
    end

    set @sql = 'insert into dbo.RH_ClientInfo(AbstractID, LinkID, IsCorrected, IsDeleted' + @sql + ')
        select ' + cast(@NewID as varchar(10)) + ',' + cast(@NewLinkID as varchar(10)) + ', 2, 3' + @sql + ' 
        from dbo.RH_ClientInfo
        where AbstractID = ' + cast(@AbstractID as varchar(10))
    exec (@sql)

    set @sql = ''
    declare cur_RH_Deletion cursor for
        select table_name, column_name from information_schema.columns 
        where table_name in ('RH_Activity', 'RH_Administrative', 'RH_Ancillary', 'RH_BasicOption', 
            'RH_Demographic', 'RH_Diagnosis', 'RH_FIM_Score', 'RH_FollowUpAssess', 'RH_Health', 
            'RH_Intervention', 'RH_Project', 'RH_Provider', 'RH_Rehabilitation', 
            'RH_ServiceInterupt', 'RH_UDAbstracting', 'RH_UpdateHistory')
            and column_name <> 'AbstractID' 
        order by table_name
    open cur_RH_Deletion
    fetch next from  cur_RH_Deletion into @table, @field
    while(@@fetch_status = 0)
    begin
        if isnull(@cur_table, '') = '' set @cur_table = @table
        if @cur_table <> @table
        begin
            set @sql = 'insert into dbo.' + @cur_table + '(AbstractID' + @sql + ')
                select ' + cast(@NewID as varchar(10)) + @sql + ' from ' + @cur_table + ' 
                where AbstractID = ' + cast(@AbstractID as varchar(10))
            exec (@sql)
            set @sql = ''
            set @cur_table = @table
        end
        set @sql = @sql + ', ' + @field
        fetch next from  cur_RH_Deletion into @table, @field
    end
    close cur_RH_Deletion
    deallocate cur_RH_Deletion

    set @sql = 'insert into dbo.' + @cur_table + '(AbstractID' + @sql + ')
        select ' + cast(@NewID as varchar(10)) + @sql + ' from ' + @cur_table + ' 
        where AbstractID = ' + cast(@AbstractID as varchar(10))
    exec (@sql)

    exec dbo.U_AB_Main @NewID, 3

    Insert into dbo.REC_RH_KeyUpdate(AbstractID, OriginalID)
    values(@AbstractID, @NewID)
    
    fetch next from cur_RH_Selection into @AbstractID
end
close cur_RH_Selection
deallocate cur_RH_Selection
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE procedure [P_Rehab_KeyFieldUpdated_Checking]
    @AbstractID int, @IsExists int output 
as
--PR - 04347
--declare @KeepID int
set @IsExists = isnull((select AbstractID from dbo.REC_RH_KeyUpdate where OriginalID = @AbstractID), 0)

--set @IsSubmited = isnull((select IsSubmited from  RH_ClientInfo where AbstractID = @AbstractID), 0)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [P_Rehab_KeyFieldUpdated_Rollback]
    @AbstractID int
as
--PR - 04347
declare @PurgeID int
set @PurgeID = (select AbstractID from dbo.REC_RH_KeyUpdate where OriginalID = @AbstractID)
exec dbo.D_RH_ClientInfo @PurgeID

Update RH_ClientInfo 
set Iscorrected = 1,
    IsDeleted = 2
where AbstractID = @AbstractID

Delete from dbo.REC_RH_KeyUpdate where OriginalID = @AbstractID
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- Called by the Rehab Module to show the 3 record (if all exist together).
CREATE PROCEDURE [P_RehabRecordLink]
	(@LinkID AS INT = 0)
AS 

--SELECT AbstractID AS [ ], 
--	REPLACE(SPACE(10-LEN(ChartNumber)) + ChartNumber, ' ', '0') AS [Chart #],
--	(SELECT DisplayCode FROM LU_CodeFile WHERE LookUpID = 25026 AND Code = AssessmentType) AS [Assess Type]
--FROM dbo.RH_ClientInfo 			
--WHERE LinkID = @LinkID
--ORDER BY [Assess Type]


-- REHAB ADMISSION
	SELECT AbstractID AS [ ] -- , 250 AS [ ]
		, CONVERT(VarChar(10), AdmitDate, 111) AS [Visit Date]
    	, (SELECT DisplayCode FROM LU_CodeFile WHERE Code = AssessmentType) AS [Assess Type]
		--, (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]		
	FROM RH_ClientInfo 
    	WHERE LinkID = @LinkID AND IsDeleted = 2
	AND AssessmentType = 134
--	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
	
-- REHAB DISCHARGE
UNION 
	SELECT AbstractID AS [ ] -- , 251 AS [ ]
		, CONVERT(VarChar(10), DischargeDate, 111) AS [Visit Date]
    	, (SELECT DisplayCode FROM LU_CodeFile WHERE Code = AssessmentType) AS [Assess Type]
		--, (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]			
    	FROM RH_ClientInfo 
    	WHERE LinkID = @LinkID AND IsDeleted = 2
	AND AssessmentType = 135
--	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
	
-- REHAB INTERIM
UNION 
	SELECT AbstractID AS [ ] -- , 251 AS [ ]
		, CONVERT(VarChar(10), DischargeDate, 111) AS [Visit Date]
    	, (SELECT DisplayCode FROM LU_CodeFile WHERE Code = AssessmentType) AS [Assess Type]
		--, (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]			
    	FROM RH_ClientInfo 
    	WHERE LinkID = @LinkID AND IsDeleted = 2
	AND AssessmentType = 156
--	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

-- REHAB POST DISCHARGE(EN-00459)
UNION 
	SELECT AbstractID AS [ ] -- , 254 AS [ ]
		, CONVERT(VarChar(10), DischargeDate, 111) AS [Visit Date]
    	, (SELECT DisplayCode FROM LU_CodeFile WHERE Code = AssessmentType) AS [Assess Type]
		--, (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]			
    	FROM RH_ClientInfo 
    	WHERE LinkID = @LinkID AND IsDeleted = 2
	AND AssessmentType = 157
--	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

-- REHAB FOLLOW UP
UNION 
	SELECT AbstractID AS [ ] -- , 252 AS [ ]
		, CONVERT(VarChar(10), FollowUpDate, 111) AS [Visit Date]
    	, (SELECT DisplayCode FROM LU_CodeFile WHERE Code = AssessmentType) AS [Assess Type]
		--, (SELECT CIHIValue FROM LU_AbstractStatus WHERE Code = IsCompleted)  AS [Status]			
    	FROM RH_ClientInfo 
    	WHERE LinkID = @LinkID AND IsDeleted = 2
	AND AssessmentType = 136
--	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

ORDER BY [Visit Date] desc


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE Procedure [P_ResetProviderCurrentLevel]
    @ProviderID int
as

    declare @MinDeficiency int
    Declare @PID int, @ProvdrMaxLetter int, @Total int, @MaxLevel int, @CurLetter int, @CurLevel int
    declare @IsUpdate int

    set @MinDeficiency = isnull((select Max(MinDeficiency) from H_HospitalProfile), 0)

    declare cur_Prov_letter cursor for
    select p.code, (case when isnull(p.ProvdrMaxLetter, 0) = 0 then 5 else p.ProvdrMaxLetter end) as ProvdrMaxLetter, 
        isnull(l.cc, 0) as Total, l.maxLetter, 
        isnull(p.ProvdrCurLetter, 0) as ProvdrCurLetter, isnull(p.ProvdrCurLevel, 0) as ProvdrCurLevel, 
        isnull((case when isnull(p.MinDeficiency, 0) = 0 then @MinDeficiency else p.MinDeficiency end), 0) as MinDeficiency
    from dbo.LU_Provider P
        left join H_HospitalProfile H on P.HospitalID = H.Code
        left join 
        (select DefDrNumber, count(*) cc, max((case when DefMainStatus in (1, 7) then 0 else DefMainStatus end) - 1) maxLetter
        from def_slipmain 
        where DefMainStatus < 8
        group by DefDrNumber) l on p.Code = l.DefDrNumber
    where p.Code = @ProviderID or (@ProviderID = 0 and (l.DefDrNumber is not null or (l.DefDrNumber is null and ProvdrCurLevel > 0)))

    open cur_Prov_letter
    fetch next from cur_Prov_letter into  @PID, @ProvdrMaxLetter, @Total, @MaxLevel, @CurLetter, @CurLevel, @MinDeficiency
    while (@@fetch_status = 0)
    begin
        set @IsUpdate = 0
        if @Total = 0 
        begin
            if @CurLevel > 0
            begin
                set @IsUpdate = 1
                set @CurLevel = 0
            end
        end
        else if @Total < @MinDeficiency
        begin
            if @CurLevel > 0
            begin
                set @IsUpdate = 1
                set @CurLevel = 0
            end
        end
        else 
        begin
            if @MaxLevel > @CurLetter
            begin
                if @CurLetter < @ProvdrMaxLetter
                begin
                    if @CurLevel <> (@CurLetter + 1)
                    begin
                        set @IsUpdate = 1
                        set @CurLevel = @CurLetter + 1
                    end
                end
                else if @CurLetter <> @CurLevel
                begin
                    set @IsUpdate = 1
                    set @CurLevel = @ProvdrMaxLetter
                end
            end
            else if @CurLevel <> @MaxLevel
            begin
                set @IsUpdate = 1
                set @CurLevel = @MaxLevel
            end        
        end
        if @IsUpdate = 1
            update LU_Provider set ProvdrCurLevel = @CurLevel where code = @PID --and isnull(ProvdrCurLevel, 0) <> isnull(@CurLevel, 0)

        fetch next from cur_Prov_letter into  @PID, @ProvdrMaxLetter, @Total, @MaxLevel, @CurLetter, @CurLevel, @MinDeficiency
    end
    close cur_Prov_letter
    deallocate cur_Prov_letter



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO

-- This is called by the first people who log in WinRecs.
-- PR - 01072
-- PR - 02918
CREATE PROCEDURE [P_ResetProviderStatus]
	@ProviderID [int]
AS 
    Update LU_Provider
    set ProvdrState = isnull(aa.Status, 'A')
    from (
        select ProviderID, Status = 'U' from dbo.LLU_Provider_UnAvailable where getdate() between DateFrom and DateTo)  aa
        right join LU_Provider P on P.Code = aa.ProviderID
    where P.Code = @ProviderID or isnull(@ProviderID, 0) = 0
        and not (isnull(P.ProvdrState, '') = 'A' and aa.ProviderID is null)

    Update LU_Provider
    set ProvdrState = aa.Status
    from (
        select ProviderID, Status = 'S' from dbo.LLU_Provider_Suspention where getdate() between DateFrom and DateTo
        ) aa
        inner join LU_Provider P on P.Code = aa.ProviderID
    where P.Code = @ProviderID or isnull(@ProviderID, 0) = 0

    -- Do we need to update deficiency provider status at the same time.
    Update Def_SlipMain
    set DefDrStatus = ProvdrState
    from Def_SlipMain D
        inner join LU_Provider P on D.DefDrNumber = P.Code
    where isnull(DefDrStatus, '') <> isnull(ProvdrState, '')
        and DefMainStatus not in (8, 11)
    -- PR - 01841
    exec P_ResetProviderCurrentLevel @ProviderID

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


-- This is called by the Deficiency Letters to roll back the status to show that a in the Provider Maint that it was done
CREATE PROCEDURE [P_RollBackDeficiencyLevel]
	(@DefID	[int],
	 @Provider	[int],
	 @Coder 	[int],
	 @Level	[int])
AS 

DECLARE @MSG AS Varchar(500)

--EN-00183
Declare @DeficiencyID as int
set @DeficiencyID = (select top 1 DefeciencyID from Def_SlipMain where DefID = @DefID)

-- The level comming in will be 1 below the sys code (e.g. 0 value is 1 sys code, 1 value is 2 sys code) so just leave the value as is
-- unless it's 0 then we need it to be 7 (the sys code for Active)
SET @MSG = 'Deficiency level ' + CONVERT(varchar(10), @Level) + ' rolled back to ' + CONVERT(varchar(10), @Level - 1) + '  for ' + CONVERT(varchar(100), @DefID) 
IF @Level = 0 
BEGIN	
	SET @Level = 7
	SET @MSG = 'Deficiency level 0 rolled back to A for ' + CONVERT(varchar(100), @DeficiencyID)
END

-- Update the Deficiency.
--EN-00183
UPDATE Def_SlipMain SET DefMainStatus = @Level WHERE DefID = @DefID  --DefeciencyID = @DefID

-- Insert a new Provider Log entry.
INSERT INTO [dbo].[REC_Notes] 
	([LogID], [AppID], [RecordID], [LogNote], [LogDate], [LogTime], [LogCoder]) 
	SELECT ISNULL(MAX(LogID), 0) + 1,  1104, @Provider,  @MSG, GetDate(), GetDate(), @Coder FROM REC_Notes


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- Called by CCRS if a record is Deleted or Recovered we will need to reset the IsCurrent flag
CREATE     PROCEDURE [P_SetCCRSIsCurrent]
	@AbstractID AS INT
AS 

DECLARE @LinkID AS INT
SELECT @LinkID = LinkID FROM CRS_Demographic WHERE AbstractID = @AbstractID

UPDATE CRS_Demographic SET IsCurrent = 0 WHERE LinkID = @LinkID
UPDATE CRS_Demographic SET IsCurrent = 1 WHERE AbstractID = @AbstractID



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- Called by OMHRS if a record is Deleted or Recovered we will need to reset the IsCurrent flag
CREATE     PROCEDURE [P_SetOMHRSIsCurrent]
	@AbstractID as int
AS 

declare @LinkID as int 
select @LinkID = LinkID from OMHRS_SecAA where AbstractID = @AbstractID

update OMHRS_SecAA set IsCurrent = 0 where LinkID = @LinkID
update OMHRS_SecAA set IsCurrent = 1 where AbstractID = @AbstractID


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE    PROCEDURE [P_SHD_GetDiagnosis] 
	@Code int --In system code
AS
set nocount on
   DECLARE @InICD9Code  varchar(10)	--ICD 9 Diganosis
   Declare   @OutCode int 
    
--Next line gets ICD9 Code from ICD10 table
set @InICD9Code = (SELECT Top 1 Icd9 From ICD_DiagFile10 where Code = @Code)
 
set @InICD9Code = left( @InICD9Code,3) --Trim the CODE  
--print @InICD9Code

--Get System Code from LU-Codefile 
set @OutCode = (SELECT Top 1 Code from  Lu_CodeFile where CIHIValue = @InICD9Code AND LookUpId = 45115)
 
 	if  @OutCode = 0  -- we don't have a match
        	begin             
                   
             set @InICD9Code = left( @InICD9Code,2) --take only the two digits
             set @OutCode = ( SELECT Top 1 Code  from  Lu_CodeFile where left( CIHIValue,2)  = @InICD9Code AND LookUpId = 45115)
          		if   @OutCode = 0 -- we don't have a match
	         	    begin
	                     set @OutCode = 0
	                 end
              
	end

	return @OutCode



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [P_SHD_Insert] 
   @Institution int,
   @DateFrom varchar(10),
   @DateTo varchar (10),
   @ProviderNumber int
AS
   DECLARE         @AbstractExist int
   DECLARE         @AbstractID int
   DECLARE         @AmCareID int
   DECLARE         @ChartNumber varchar(10)
   DECLARE         @HealthCareNumber varchar(12)
   DECLARE @HCNVersion varchar(2)
   DECLARE @MaidenName varchar(35)
   DECLARE @LastName varchar(40)
   DECLARE @MiddleName varchar(15)
   DECLARE @FirstName varchar(35)
   DECLARE @Gender int
   DECLARE @BirthDate datetime
   DECLARE @IsCompleted int
   DECLARE @IsValidated int
   DECLARE @IsSubmitted int
   DECLARE @IsCorrected int
   DECLARE @IsDeleted int
   DECLARE @BillDate  datetime
   DECLARE @BillNumber varchar(8)
   DECLARE @HCNProvince int

   --AB_Diagnosis
   DECLARE         @DiagnosisOccurrence int
   DECLARE @DiagnosisCode  int
   DECLARE @ServiceCode int
   DECLARE @ServiceQty int
   DECLARE @ServiceFee money
   DECLARE @ServiceTotal money
   DECLARE @ServiceSuffix  varchar(50)

   DECLARE @GeneralFee money
   DECLARE @AssistantFee money
   DECLARE @SpecialistFee money
   DECLARE @AnaesthetistFee money
   DECLARE @NonAnaesthetistFee money

   --AB_Vistit
   DECLARE         @IsMultiContact int 
   DECLARE         @EncounterNumber        varchar (12) 
   DECLARE         @EncounterSequence      varchar (3) 
   DECLARE         @AdmitDate              datetime
   DECLARE         @AdmitTime              datetime
   DECLARE         @ArrivalTime            datetime
   DECLARE         @TimePatientSeen        datetime
   DECLARE         @DischargeTime  datetime
   DECLARE         @VisitLocation          int
   DECLARE         @VisitType              int
   DECLARE         @VisitTypeMethod        int
   DECLARE         @VisitTypeMode  int
   DECLARE         @IntervDescProvider     varchar(255)
   DECLARE         @IntervDescPatient       varchar (255)
   DECLARE         @RefLabNumber   varchar(50)
   DECLARE         @ReferenceProvider      varchar(6) 
   DECLARE         @PaymentProgram         int
   DECLARE         @Payee          int
   DECLARE         @ManualReviewInd        int 
   DECLARE         @InpatAdmitDate         datetime
   DECLARE         @ProviderSpecialty      int
   DECLARE         @InstitutionNumber      int 
   DECLARE         @MOH_Code               varchar(1) 
   DECLARE         @LocationCode   varchar(4)
   DECLARE         @MRINotes               varchar(255)
   DECLARE         @IntervDateOfOnset      datetime

   --Open Cursur to get all Abstaracts that are not in the CR_Demographics
   declare  Cur_XReference cursor   fast_forward for
           SELECT     dbo.AB_Abstract.AbstractID, dbo.AB_Abstract.ChartNumber, dbo.AB_Abstract.HealthCareNumber, dbo.AB_Abstract.HCNVersion, 
                      dbo.AB_Abstract.MaidenName, dbo.AB_Abstract.LastName, dbo.AB_Abstract.MiddleName, dbo.AB_Abstract.FirstName, dbo.AB_Abstract.Gender, 
                      dbo.AB_Abstract.BirthDate, dbo.AB_Abstract.IsCompleted, dbo.AB_Abstract.IsValidated, dbo.AB_Abstract.IsCorrected, dbo.AB_Abstract.IsDeleted, 
                      dbo.AB_Abstract.HCNProvince, dbo.AB_Abstract.AdmitDate, dbo.AB_Abstract.AdmitTime, dbo.AB_Abstract.EncounterNumber, 
                      dbo.AB_Abstract.EncounterSequence, dbo.AB_Abstract.ArrivalTime, dbo.AB_Abstract.AssessmentTime, dbo.AB_Abstract.DischargeTime, 
                      dbo.AB_Abstract.VisitType, dbo.H_InstitutionProfile.MOHOfficeCode,LocationCode , RefLabNumber
           FROM       dbo.H_InstitutionProfile 
           INNER JOIN dbo.AB_Abstract ON dbo.H_InstitutionProfile.Code = dbo.AB_Abstract.InstitutionNumber
           WHERE     (dbo.AB_Abstract.InstitutionNumber = @Institution) 
           AND (dbo.AB_Abstract.IsCompleted = 4) AND (dbo.AB_Abstract.CareType = 5)
                   AND AdmitDate between @DateFrom AND @DateTo 
                   AND  (dbo.AB_Abstract.AbstractID NOT IN (SELECT AmCareID FROM  CR_Demographic))

   Open Cur_XReference
   fetch next from Cur_XReference into @AbstractID,@ChartNumber,@HealthCareNumber,@HCNVersion,
               @MaidenName, @LastName ,@MiddleName , @FirstName, @Gender , @BirthDate ,@IsCompleted,
               @IsValidated, @IsCorrected ,@IsDeleted ,@HCNProvince ,@AdmitDate,@AdmitTime ,@EncounterNumber,
               @EncounterSequence ,@ArrivalTime,@TimePatientSeen,@DischargeTime,@VisitType,@MOH_Code,@LocationCode, @ReferenceProvider
   while @@fetch_status = 0
   begin 
           SET @AmCareID = @AbstractID
           set @BillNumber = @AbstractID  

                   EXEC @AbstractID = I_CR_Demographic @AbstractID,@AmCareID,@ChartNumber, @HealthCareNumber,@HCNVersion,
                   @MaidenName , @LastName,@MiddleName, @FirstName, @Gender, @BirthDate, @IsCompleted      ,
                   @IsValidated, @IsSubmitted      , @IsCorrected, @IsDeleted, @AdmitDate, @BillNumber, @HCNProvince
   
           set @Payee = 14297 --ALWAYS = 'P'
           set @PaymentProgram = 14293 --ALWAYS = 'HCP' 
           set @ProviderSpecialty =( SELECT dbo.LU_CodeFile.DisplayCode
                   FROM dbo.LU_Provider 
                   INNER JOIN dbo.LU_CodeFile ON dbo.LU_Provider.ProvdrBillSpecialty = dbo.LU_CodeFile.Code
                   WHERE LU_Provider.Code   =  @ProviderNumber)

                   exec I_CR_Visit   @AbstractID, @IsMultiContact, @ProviderNumber,@EncounterNumber,       
                           @EncounterSequence, @AdmitDate,@AdmitTime, @ArrivalTime,@TimePatientSeen,@DischargeTime,         
                   @VisitLocation, @VisitType,@VisitTypeMethod, @VisitTypeMode, @IntervDescProvider, @IntervDescPatient,    
                   @RefLabNumber,  @ReferenceProvider, @PaymentProgram, @Payee, @ManualReviewInd, @AdmitDate,       
                   @ProviderSpecialty, @Institution, @MOH_Code, @LocationCode, @MRINotes, @IntervDateOfOnset        
    
                    --INSERT INTO CR VISIT
                   --GET ABSTRACTID AND GO TO AB_Diagnosis and GET records and fill CR_DIAGNOSIS
                   declare  Cur_X  cursor   fast_forward for
                           SELECT  DiagnosisOccurrence ,ProvinceDiagCode ,ServiceCode ,ServiceSuffix ,
                                   dbo.LU_OhipFeeCodes.GeneralFee,dbo.LU_OhipFeeCodes.AssistantFee  ,
                                   dbo.LU_OhipFeeCodes.SpecialistFee  ,dbo.LU_OhipFeeCodes.AnaesthetistFee,
                                   dbo.LU_OhipFeeCodes.NonAnaesthetistFee
                           FROM    AB_Diagnosis 
                   INNER JOIN dbo.LU_OhipFeeCodes ON dbo.AB_Diagnosis.ServiceCode = dbo.LU_OhipFeeCodes.code
                           WHERE ABSTRACTID = @AmcareID

                   Open Cur_X
                   fetch next from Cur_X into @DiagnosisOccurrence,@DiagnosisCode,@ServiceCode,    
                                   @ServiceSuffix,@GeneralFee,@AssistantFee,@SpecialistFee,
                                   @AnaesthetistFee,@NonAnaesthetistFee
                                
                   while @@fetch_status = 0
                   begin
                           set @ServiceTotal = @GeneralFee + @AssistantFee + @SpecialistFee + @AnaesthetistFee + @NonAnaesthetistFee                               
                           exec I_CR_Diagnosis @AbstractID, @DiagnosisOccurrence, @DiagnosisCode, @ServiceCode, 1, @GeneralFee,  @ServiceTotal, @ServiceSuffix
                           fetch next from Cur_X into @DiagnosisOccurrence,@DiagnosisCode,@ServiceCode, @ServiceSuffix,@GeneralFee,@AssistantFee,@SpecialistFee, @AnaesthetistFee,@NonAnaesthetistFee
                   end

                   Close Cur_X 
                   deallocate Cur_X         
    
                   fetch next from Cur_XReference into @AbstractID,@ChartNumber,@HealthCareNumber,@HCNVersion,
                                   @MaidenName, @LastName ,@MiddleName , @FirstName, @Gender , @BirthDate ,@IsCompleted,
                                   @IsValidated, @IsCorrected ,@IsDeleted ,@HCNProvince ,@AdmitDate,@AdmitTime,@EncounterNumber,
                                   @EncounterSequence, @ArrivalTime,@TimePatientSeen,@DischargeTime,@VisitType,@MOH_Code,
                                   @LocationCode,@ReferenceProvider
           end

   Close Cur_XReference
   deallocate Cur_XReference




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_UniqueAbstracting] 
   @ChartNumber as VarChar(10), 
   @DischargeDate as VarChar(10), 
   @DischargeTime as VarChar(5), 
   @AppID as int,  
   @AbstractID as int,
   @HospID as int = 0
AS  
 
   If @AppID = 100 
           SELECT AbstractID FROM dbo.AB_Abstract 
           WHERE (ChartNumber = @ChartNumber) AND (DischargeDate IS NULL) AND (AbstractID <> @AbstractID) 
           and icdtype in ('9', 'C') and caretype = 1 
   Else if @AppID = 200 
           SELECT AbstractID FROM dbo.AB_Abstract 
           WHERE (ChartNumber = @ChartNumber) AND (DischargeDate IS NULL) AND (AbstractID <> @AbstractID) 
           and icdtype = 'T' and caretype = 1 
   --PR - 05869 
   Else 
           SELECT AbstractID FROM dbo.AB_Abstract WHERE (ChartNumber = @ChartNumber)  
           AND (DischargeDate = @DischargeDate) AND (isnull(convert(NVarChar(5), DischargeTime, 14), '') =  isnull(@DischargeTime, ''))  
           AND (AbstractID <> @AbstractID) 
           --SELECT AbstractID FROM dbo.AB_Abstract WHERE (ChartNumber = @ChartNumber)  
           --AND (DischargeDate = @DischargeDate) AND (convert(NVarChar(5), DischargeTime, 14) =  @DischargeTime)  
           --AND (AbstractID <> @AbstractID) 
 
   Return @@RowCount
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE      PROCEDURE [P_UniqueAmcare]
	@ChartNumber as VarChar(10),
	@EncounterNumber as VarChar(20),
	@EncounterNumberSeq as Int,
	@AbstractID as Int,
	@HospID as int = 0
AS 

	SELECT  AbstractID FROM dbo.AB_Abstract WHERE (EncounterSequence = @EncounterNumberSeq) 
	AND (EncounterNumber = @EncounterNumber) And (AbstractID <> @AbstractID)
	AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
	Return @@RowCount





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE        PROCEDURE [P_UniqueAmcare10]
	@ChartNumber as VarChar(10),
	@AdmitDate as VarChar(10),
	@AdmitTime as VarChar(5),
	@EncounterNumber as VarChar(20),
	@EncounterNumberSeq as Int,	
	@AbstractID as int,
	@CIHI_ID as varchar(50),
	@HospID as int = 0
AS 

-- PR-00673 -- PR-01272
--if @AdmitDate >= '2006/04/01' 
--	select AbstractID 
--	from dbo.AB_Abstract 
--	where ChartNumber 			= @ChartNumber
--	--and EncounterSequence 			= @EncounterNumberSeq
--	--and EncounterNumber 				= @EncounterNumber
--	and AdmitDate 				= @AdmitDate
--	and convert(nvarchar(5), AdmitTime, 14)	=  @AdmitTime
--	and AbstractID 				<> @AbstractID
--	and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
--else

	set nocount on
	select AbstractID, CIHI_AbstractID, ChartNumber, EncounterSequence, EncounterNumber, AdmitDate,AdmitTime,
		HospitalID into #UniqueAB from AB_Abstract 
		where ChartNumber 	= @ChartNumber
		and AdmitDate 		= @AdmitDate
	set nocount off
	--ED-00659
	if @CIHI_ID > 9000000
		select AbstractID 
		from dbo.#UniqueAB 
		where (CIHI_AbstractID = @CIHI_ID) 
		and ChartNumber 	= @ChartNumber
		and EncounterSequence 	= @EncounterNumberSeq
		and EncounterNumber 	= @EncounterNumber
		and AdmitDate 		= @AdmitDate
		and convert(nvarchar(5), AdmitTime, 14)	=  @AdmitTime
		and AbstractID 		<> @AbstractID
		and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	else
		select AbstractID 
		from dbo.#UniqueAB 
		where ChartNumber 	= @ChartNumber
		and EncounterSequence 	= @EncounterNumberSeq
		and EncounterNumber 	= @EncounterNumber
		and AdmitDate 		= @AdmitDate
		and convert(nvarchar(5), AdmitTime, 14)	=  @AdmitTime
		and AbstractID 		<> @AbstractID
		and (isnull(HospitalID, 0) = 0 or @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)
	
return @@rowcount




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [P_UniqueCancerCare] 
   @ChartNumber as varchar(50), 	
   @InstitutionNumber as int,		
   @RegisterDate as datetime,  			
   @AbstractID as int
AS  

--PR - 03305

	-- DISEASE REGISTRATION

	select demo.AbstractID from CC_Demographic demo, CC_DiseaseRegister dise
	where   demo.AbstractID = dise.AbstractID
	and isnull(InstitutionNumber, 0) = isnull(@InstitutionNumber, 0)
	and isnull(ChartNumber, '') = isnull(@ChartNumber, '')
	and isnull(RegisterDate, '') = isnull(@RegisterDate, '')
	and isnull(demo.AbstractID, 0) <> isnull(@AbstractID, 0)
	
	return @@RowCount



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE    PROCEDURE [P_UniqueCJRR] 
         @RecordType			[int]    
        ,@InterventionCIHI		[varchar](50)
        ,@InstitutionNumber		[int] 
        ,@ChartNumber			[varchar](50)        
        ,@SurgeryDate			[datetime]        
        ,@ReplacementType		[int]
        ,@SideLocation			[int]        
        ,@RecordID				[int]
        ,@HospID				[int]
as  
 
select [RecordID] 
from CJRR_Abstract 
where [RecordType]		= @RecordType
--and [InterventionCIHI]	= @InterventionCIHI --EN - 00561
and [InstitutionNumber] = @InstitutionNumber
and [ChartNumber]		= @ChartNumber
and [SurgeryDate]		= @SurgeryDate
and [Replacementtype]	= @ReplacementType
and [SideLocation]		= @SideLocation
and RecordID			<> @RecordID
 
return @@RowCount

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO









CREATE     PROCEDURE [P_UniqueCPI]
	@ChartNumber as VarChar(10),
	@PatientID as Int,
	@HospID as int = 0
AS 

	SELECT PatientID, ChartNumber FROM dbo.CM_CPI 
	WHERE (ChartNumber = @ChartNumber) AND (PatientID <> @PatientID)
	AND ISNULL(HospitalID, 0) = @HospID -- RM: 2008/02/27
	--AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
	
	Return @@RowCount
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE       PROCEDURE [P_UniqueCPI_Volume]
	@VolumeNumber as VarChar(12),
	@VolumeID as Int,
	@PatientID as Int,
	@HospID as int = 0,
 	@VolumeType as int = 0
AS 

	select VolumeID, VolumeNumber 
	from CM_CPI_Volume 
	where VolumeNumber = @VolumeNumber
	and PatientID = @PatientID
	and VolumeID <> @VolumeID
	and isnull(HospitalID, 0) = @HospID
	and isnull(VolumeType, 0) = @VolumeType
	--and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end)	--NP-00025

	return @@RowCount



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE  PROCEDURE [P_UniqueOMHRS] 
   @InstitutionNumber as int,
--   @HealthCareNumber as varchar(50),
--   @HCNProvince as int,
   @ChartNumber as varchar(50), 
--   @AdmitDate as datetime, 
   @A1 as datetime, 
   @AA3 as varchar(50),
   @AbstractID as int,
   @HospID as int = 0
AS  

--12523
    select AA.AbstractID 
    from OMHRS_SecAA AA inner join OMHRS_SecA A on AA.AbstractID = A.AbstractID
    where isnull(InstitutionNumber, 0) = isnull(@InstitutionNumber, 0)
--    and isnull(HealthCareNumber, '') = isnull(@HealthCareNumber, '')
--    and isnull(HCNProvince, 0) = isnull(@HCNProvince, 0)
    and isnull(ChartNumber, '') = isnull(@ChartNumber, '')
--    and isnull(AdmitDate, '') = isnull(@AdmitDate, '')
    and isnull(A1, '') = isnull(@A1, '')
    and isnull(AA3, '') = isnull(@AA3, '')
    and isnull(AA.AbstractID, 0) <> isnull(@AbstractID, 0)
    
   Return @@RowCount

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE   PROCEDURE [P_UniqueOMHRS_Episode]
   @InstitutionNumber as int,
   @ChartNumber as varchar(50), 
   @AA3 as varchar(50),
   @AbstractID as int,
   @HospID as int = 0
AS  

--12526
    select AbstractID 
    from OMHRS_SecAA 
    where (Z1 = 200373 or Z1 = 200377) -- or Z1 = 200375) --[RM]: This should not include discharge
    and isnull(InstitutionNumber, 0) = isnull(@InstitutionNumber, 0)
    and isnull(ChartNumber, '') = isnull(@ChartNumber, '')
    and isnull(AA3, '') = isnull(@AA3, '')
    and isnull(AbstractID, 0) <> isnull(@AbstractID, 0)
    
   Return @@RowCount

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [P_UniqueRehab] 
   @ChartNumber as varchar(50), 
   @InstitutionNumber as int,
   @VisitDate as datetime,
   @AppID as int,
   @AbstractID as int,
   @HospID as int = 0
AS  

--PR-00338

if @AppID = 250
begin
	select AbstractID from RH_ClientInfo
	where isnull(InstitutionNumber, 0) = isnull(@InstitutionNumber, 0)
	and isnull(ChartNumber, '') = isnull(@ChartNumber, '')
	and isnull(AdmitDate, '') = isnull(@VisitDate, '')
	and isnull(AbstractID, 0) <> isnull(@AbstractID, 0)
	and AssessmentType = 134 --PR-00645

	return @@RowCount
end

else if @AppID = 251 or @AppID = 253
begin
	select AbstractID from RH_ClientInfo
	where isnull(InstitutionNumber, 0) = isnull(@InstitutionNumber, 0)
	and isnull(ChartNumber, '') = isnull(@ChartNumber, '')
	and isnull(DischargeDate, '') = isnull(@VisitDate, '')
	and isnull(AbstractID, 0) <> isnull(@AbstractID, 0)
	and (AssessmentType = 135 or AssessmentType = 156) --PR-00645

	return @@RowCount
end

else if @AppID = 252
begin
	select AbstractID from RH_ClientInfo
	where isnull(InstitutionNumber, 0) = isnull(@InstitutionNumber, 0)
	and isnull(ChartNumber, '') = isnull(@ChartNumber, '')
	and isnull(FollowUpDate, '') = isnull(@VisitDate, '')
	and isnull(AbstractID, 0) <> isnull(@AbstractID, 0)
	and AssessmentType = 136 --PR-00645

	return @@RowCount
end

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE   PROCEDURE [P_UniqueROI]
	@RequestNumber as VarChar(15),
	@InvoiceNumber as VarChar(30),
	@ROIID as Int,
	@HospID as int = 0
AS 
	
select ROIID, RequestNumber from ROI_Main where RequestNumber = @RequestNumber and ROIID <> @ROIID and HospitalID = @HospID

-- If the A duplicate Request Number is not found and there is an Invoice Number. Check it.
if @@RowCount = 0 and len(isnull(@InvoiceNumber, '')) <> 0
	select ROIID, InvoiceNumber from ROI_Main where (InvoiceNumber = @InvoiceNumber) and (ROIID <> @ROIID) and HospitalId = @HospID

return @@RowCount

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE  PROCEDURE [P_UniqueSchedule]
	@AppointmentID as int = 0,
	@Location as int,
	@Room as int,
	@Duration as int,
	@Date as VarChar(10),
	@Time as datetime
AS
	Declare @TimePlus as datetime

	Set @TimePlus = DATEADD(mi, @Duration, @Time)

	SELECT AppointmentID, convert(varchar(5), AppointmentTime, 108) as [Time], cast(Duration as varchar(6)) as [Min.], 
	ISNULL( LastName, '') + ', ' + ISNULL(FirstName, '') AS Patient
	FROM SH_Appointments LEFT OUTER JOIN dbo.CM_CPI ON dbo.SH_Appointments.Patientid = dbo.CM_CPI.PatientID
	where AppointmentID <> @AppointmentID and AppointmentDate = @Date and Room = @Room and Location = @Location
	and (@Time between AppointmentTime and DATEADD(mi, duration, AppointmentTime) or 
	@TimePlus between AppointmentTime and DATEADD(mi, duration, AppointmentTime))





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE   PROCEDURE [P_UniqueUser]
	@UserName as VarChar(50),
	@UserPassword as VarChar(50),
	@SystemID as int
AS 

/*	Set @UserPassword = replace(isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 1, 1)) - 10), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 2, 1)) - 11), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 3, 1)) - 12), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 4, 1)) - 13), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 5, 1)) - 14), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 6, 1)) - 15), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 7, 1)) - 16), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 8, 1)) - 17), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 9, 1)) - 18), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 10, 1)) - 19), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 11, 1)) - 20), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 12, 1)) - 21), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 13, 1)) - 22), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 14, 1)) - 23), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 15, 1)) - 24), ''), '               ', '')

	SELECT Code FROM dbo.U_Users
	WHERE (UserName = @UserName) AND (UserPassword =  @UserPassword) AND (Code <> @SystemID)

*/

	-- Change it so that the User Name  is Unique
	SELECT Code FROM dbo.U_Users WHERE (UserName = @UserName) AND (Code <> @SystemID) and len(@UserName) > 0
	RETURN @@RowCount



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE   PROCEDURE [P_UnSeenAppointment]
	@AppntID as int
AS 
	-- We DO NOT want the record to be saved if it's already flagged as seen	
	SELECT AppointmentID FROM [dbo].[SH_Appointments] WHERE ([AppointmentID] = @AppntID AND [Status] = 11735)
	RETURN @@RowCount



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is called when a Chart is Changed or Merged to set up the Abstracts for Corrections
CREATE PROCEDURE [P_UpdateAbstractForCorrection]
    @AbstractID	int,
    @NewChart 	varchar(12),
    @ICDType	varchar(1),
    @CareType 	varchar(1),
    @MergeID as uniqueidentifier = null
AS

declare @OrigAbstID int
declare @CType int
declare @OrigChart varchar(50) --PR-02208
declare @ID int
declare @sql nvarchar(4000) --PR - 04020
declare @x1 int -- PR - 04465

--PR - 04076 The Amcare should be the same as DAD
--AMCARE ICD 10
--if @CareType = 'B' AND @ICDType = 'T'
--begin
--	--update the new chart number and set it up for update
--	update AB_Abstract set 		
--		IsCorrected = (case IsSubmited when 1 then 2 else 1 end), 
--		CIHIReturnStatus = (case IsSubmited when 1 then 4 else 1 end)
--    	where AbstractID = @AbstractID
--
--    	exec U_AB_Main @AbstractID, 5
--end

-- 12111: INPATIENT/SDS ICD 10
--else if @CareType in ('A', 'D') and @ICDType = 'T'
if @CareType in ('A', 'D', 'B') and @ICDType = 'T'
begin
	--Copy the Abstract to a new record and set it up for insertion
	select @OrigAbstID = (select isnull(max(AbstractID), 0) from AB_ABSTRACT) + 1
	select @OrigChart = (select ChartNumber from AB_Abstract where AbstractID = @AbstractID) --PR-02208

    if @MergeID is not null and @OrigChart = @NewChart
    begin
        set @OrigChart = (select top 1 ChartNumberFrom from dbo.MRG_Main where ID = @MergeID)
    end
	insert into AB_Abstract (
		AbstractID, 
		VolumeID, 
		IsCorrected, CIHIReturnStatus, IsSubmited, 
		IsValidated, IsCompleted, 
		IsDeleted, 
		ICDType, CareType, CIHIDateSent, BatchYear, BatchPeriod, BatchNumber, AbstractNumber, ProvinceNumber, 
		InstitutionNumber, SiteNumber, EncounterNumber, EncounterSequence, ChartNumber, CoderNumber, MaidenName, 
		LastName, MiddleName, FirstName, Gender, BirthDate, BirthDateEstimated, MaritalStatus, LanguageCode, 
		PostalCode, ResidenceCode, ResponsiblePayment, FamilyPhysician, EducationLevel, Occupation, LivingArrangement, 
		ResidenceType, HCNProvince, HealthCareNumber, HCNVersion, AdmitDate, AdmitTime, ArrivalMode, ArrivalDate, 
		ArrivalTime, RegisterNumber, SecondChartRegNumber, AgeCode, AgeNumber, EntryCode, DecisionAdmitDate, 
		DecisionAdmitTime, DecisionAdmitDifference, TransferOverloadDate, TransferOverloadTime, TransferOverloadDifference, 
		NextSchedVisitDate, NextSchedVisitTime, WaitTimeER, Weight, AdmitCategory, AdmitAmbulance, AmbulanceReportNumber, 
		Institutionfrom, Program, MISCode, ContactMode, Referredfrom, VisitType, VisitStatus, ReAdmitCode, UnplanReAdmit, 
		AttendingPhysician, AdmittingDiagnosis, ChiefComplaint, Injury, InjuryDate, InjuryLocation, InjuryActivity, 
		InjuryActivityDescription, TriageLevel, TriageDate, TriageTime, ArrivalTriageDifference, AssessmentDate, 
		AssessmentTime, WaitAssessmentDifference, NurseAssessDate,  NurseAssessTime, NurseAssessDiff, AdmittingNurseArea, 
		PreAdmitWorkUp, DischargeDate, DischargeTime, EstimatedDischargeDate, DischargeNurseArea, LOSDays, LOSTime, LOSMinutes, 
		LOSTotal, PhysicianEstimatedLOS, DischargeAge, ExitCode, DispositionCode, ReferredTo, DischargePlanning, DateReadyDischarge, 
		DateLeftER, TimeLeftER, InstitutionTo, SocialService, NewbornChart, NewbornDischargeDate, AcuteLOS, ALCLOS, GlasgowComaScale, 
		Complication, SurgicalCase, PreOpDays, PostOpDays, InterfaceDate, InterfaceTime, InterfaceCoder, InputDate, InputTime, 
		DataEntryCoder, FinishDate, FinishTime, Secret, AbstractOverflow, TSIDate, TSITime, TSICoder, 
        UniqiueLifetimeID, DecisionAdmitTimeUnknown, HospitalID, AgeGroup, TimeLeftERUnknown, DischargeTimeUnknown, RefPhysician,
        TriageTimeUnknown, AmbulanceArrDate, AmbulanceArrTime, AmbulanceTranDate, AmbulanceTranTime, CDUArrivalDate, CDUArrivalTime, IsReciprocalBilling, CDUFlag, CDUOutDate, CDUOutTime, CDUInTimeUnknown, CDUOutTimeUnknown, AccessCareCode, SubmissionLevel, AmbulanceArrTimeUnknown, AmbulanceTranTimeUnknown, 
        IsSubmitLevel1, IsCorrectLevel1, IsValidLevel1, CIHIReturnStatusLevel1, CIHIDateSentLevel1, AdmitTimeUnknown,
        ArrivalTimeUnknown, RegionalPatientID, FixedChartNumber
    )
	select @OrigAbstID, VolumeID, (case when IsSubmited = 1 then 2 else IsCorrected end), 
	    CIHIReturnStatus = (case when IsSubmited = 1 then 2 else CIHIReturnStatus end), --PR - 05326 the flag is not changed and cause submission run time error
	    IsSubmited, IsValidated, IsCompleted, 3, ICDType, CareType, CIHIDateSent, BatchYear, BatchPeriod, BatchNumber, AbstractNumber, 
		ProvinceNumber, InstitutionNumber, SiteNumber, EncounterNumber, EncounterSequence, ChartNumber = @OrigChart, CoderNumber, MaidenName, LastName, MiddleName, FirstName, Gender, BirthDate, BirthDateEstimated, MaritalStatus, LanguageCode, PostalCode, ResidenceCode, ResponsiblePayment, FamilyPhysician, EducationLevel, Occupation, LivingArrangement, ResidenceType, HCNProvince, HealthCareNumber, HCNVersion, AdmitDate, 
		AdmitTime, ArrivalMode, ArrivalDate, ArrivalTime, RegisterNumber, SecondChartRegNumber, AgeCode, AgeNumber, EntryCode, DecisionAdmitDate, DecisionAdmitTime, DecisionAdmitDifference, TransferOverloadDate, TransferOverloadTime, TransferOverloadDifference, NextSchedVisitDate, NextSchedVisitTime, WaitTimeER, Weight, AdmitCategory, AdmitAmbulance, AmbulanceReportNumber, Institutionfrom, Program, MISCode, ContactMode, Referredfrom, VisitType, VisitStatus, ReAdmitCode, UnplanReAdmit, AttendingPhysician, AdmittingDiagnosis, 
		ChiefComplaint, Injury, InjuryDate, InjuryLocation, InjuryActivity, InjuryActivityDescription, TriageLevel, TriageDate, TriageTime, ArrivalTriageDifference, AssessmentDate, AssessmentTime, WaitAssessmentDifference, NurseAssessDate, NurseAssessTime, NurseAssessDiff, AdmittingNurseArea, PreAdmitWorkUp, DischargeDate, DischargeTime, EstimatedDischargeDate, DischargeNurseArea, LOSDays, LOSTime, LOSMinutes, LOSTotal, PhysicianEstimatedLOS, DischargeAge, ExitCode, DispositionCode, ReferredTo, DischargePlanning, DateReadyDischarge, DateLeftER, 
		TimeLeftER, InstitutionTo, SocialService, NewbornChart, NewbornDischargeDate, AcuteLOS, ALCLOS, GlasgowComaScale, Complication, SurgicalCase, PreOpDays, PostOpDays, InterfaceDate, InterfaceTime, InterfaceCoder, InputDate, InputTime, DataEntryCoder, FinishDate, FinishTime, Secret, AbstractOverflow, TSIDate, TSITime, TSICoder,
        UniqiueLifetimeID, DecisionAdmitTimeUnknown, HospitalID, AgeGroup, TimeLeftERUnknown, DischargeTimeUnknown, RefPhysician,
        TriageTimeUnknown, AmbulanceArrDate, AmbulanceArrTime, AmbulanceTranDate, AmbulanceTranTime, CDUArrivalDate, CDUArrivalTime, IsReciprocalBilling, CDUFlag, CDUOutDate, CDUOutTime, CDUInTimeUnknown, CDUOutTimeUnknown, AccessCareCode, SubmissionLevel, AmbulanceArrTimeUnknown, AmbulanceTranTimeUnknown,  
        IsSubmitLevel1, (case when IsSubmitLevel1 = 1 and IsSubmited = 2 then 2 else IsCorrectLevel1 end), IsValidLevel1, CIHIReturnStatusLevel1, CIHIDateSentLevel1, AdmitTimeUnknown,
        ArrivalTimeUnknown, RegionalPatientID, FixedChartNumber
	from AB_Abstract 
	where AbstractID = @AbstractID

	--update the original for deletion			
	update AB_Abstract set IsCorrected = 1, CIHIReturnStatus = '', IsSubmited = 2, CIHIDateSent = '', BatchYear = null, BatchPeriod = null, BatchNumber = null, AbstractNumber = null,
        IsCorrectLevel1 = 1, IsSubmitLevel1 = 2, CIHIDateSentLevel1 = null, CIHIReturnStatusLevel1 = 1, CIHI_AbstractID = null
    where AbstractID = @AbstractID
	
--	insert into AB_Ancillary (AbstractID, AncillaryField1, AncillaryField2, AncillaryField3, AncillaryField4, AncillaryField5, AncillaryField6, AncillaryField7, AncillaryField8, AncillaryField9, AncillaryField10, AncillaryField11, AncillaryField12, AncillaryField13, AncillaryField14, AncillaryField15, AncillaryField16, AncillaryField17) 
--	select @OrigAbstID, AncillaryField1, AncillaryField2, AncillaryField3, AncillaryField4, AncillaryField5, AncillaryField6, AncillaryField7, AncillaryField8, AncillaryField9, AncillaryField10, AncillaryField11, AncillaryField12, AncillaryField13, AncillaryField14, AncillaryField15, AncillaryField16, AncillaryField17 from AB_Ancillary where AbstractID = @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_Ancillary')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into AB_BasicOption (AbstractID, BasicOption1, BasicOption2, BasicOption3, BasicOption4, BasicOption5, BasicOption6, BasicOption7, BasicOption8, BasicOption9, BasicOption10, BasicOption11, BasicOption12, BasicOption13, BasicOption14, BasicOption15, BasicOption16, BasicOption17, BasicOption18, BasicOption19) 
--	select @OrigAbstID, BasicOption1, BasicOption2, BasicOption3, BasicOption4, BasicOption5, BasicOption6, BasicOption7, BasicOption8, BasicOption9, BasicOption10, BasicOption11, BasicOption12, BasicOption13, BasicOption14, BasicOption15, BasicOption16, BasicOption17, BasicOption18, BasicOption19 from AB_BasicOption where AbstractID = @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_BasicOption')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into AB_Blood (AbstractID, TransfusionIndicator, RedBloodCell, RedCellTyped, RedCellUnits, RedCellXMatch, Platelets, PlateletsTyped, PlateletsUnits, PlateletsXMatch, Plasma, PlasmaTyped, PlasmaUnits, PlasmaxMatch, Albumin, AlbuminTyped, AlbuminUnits, AlbuminXMatch, OtherBlood, OtherBloodTyped, OtherBloodUnits, OtherBloodXMatch, AutoTransfusion) 
--	select @OrigAbstID, TransfusionIndicator, RedBloodCell, RedCellTyped, RedCellUnits, RedCellXMatch, Platelets, PlateletsTyped, PlateletsUnits, PlateletsXMatch, Plasma, PlasmaTyped, PlasmaUnits, PlasmaxMatch, Albumin, AlbuminTyped, AlbuminUnits, AlbuminXMatch, OtherBlood, OtherBloodTyped, OtherBloodUnits, OtherBloodXMatch, AutoTransfusion from AB_Blood where AbstractID = @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_Blood')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into AB_CancerStaging (AbstractID, ClinicalTumor, ClinicalNode, ClinicalMetastasis, PathTumor, PathNode, PathMetastasis, SummaryStage) 
--	select @OrigAbstID, ClinicalTumor, ClinicalNode, ClinicalMetastasis, PathTumor, PathNode, PathMetastasis, SummaryStage from AB_CancerStaging where AbstractID = @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_CancerStaging')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into AB_DeathInformation (AbstractID, AutopsyPerformed, CoronerCase, DeathInSCU, DeathInOR, DeathLessTwoPO, DeathTwoTenPO, DeathGreaterTenPO, DeathAfterAdmit, DeathOnArrival, DeathInER, TraumaDeath,	 PregnancyDeath, OtherDeath) 
--	select @OrigAbstID, AutopsyPerformed, CoronerCase, DeathInSCU, DeathInOR, DeathLessTwoPO, DeathTwoTenPO, DeathGreaterTenPO, DeathAfterAdmit, DeathOnArrival, DeathInER, TraumaDeath, PregnancyDeath, OtherDeath from AB_DeathInformation where AbstractID = @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_DeathInformation')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into AB_Diagnosis (AbstractID, DiagnosisOccurrence, DiagnosisICDType, DiagnosisPrefix, DiagnosisCode, DiagnosisSuffix, DiagnosisType) 
--	select @OrigAbstID, DiagnosisOccurrence, DiagnosisICDType, DiagnosisPrefix, DiagnosisCode, DiagnosisSuffix, DiagnosisType from AB_Diagnosis where AbstractID = @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_Diagnosis')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into AB_Intervention (AbstractID, IntervOccurrence, IntervICDType, IntervDate, IntervCode, IntervSuffix, IntervAttribStatus, IntervAttribLocation, IntervAttribExtent, IntervEUL, IntervExtra, IntervOOHIndicator, IntervOOHInstitution, IntervProviderNumber, IntervProviderService, IntervTissueCode, IntervDateIn, IntervTimeIn, IntervDateOut, IntervTimeOut, IntervTimeMinutes, IntervLocation, IntervAnaestID, IntervAnaestTechnique, IntervUnplanReturn) 
--	select @OrigAbstID, IntervOccurrence, IntervICDType, IntervDate, IntervCode, IntervSuffix, IntervAttribStatus, IntervAttribLocation, IntervAttribExtent, IntervEUL, IntervExtra, IntervOOHIndicator, IntervOOHInstitution, IntervProviderNumber, IntervProviderService, IntervTissueCode, IntervDateIn, IntervTimeIn, IntervDateOut, IntervTimeOut, IntervTimeMinutes, IntervLocation, IntervAnaestID, IntervAnaestTechnique, IntervUnplanReturn from AB_Intervention where AbstractID = @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_Intervention')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into AB_Manitoba ([AbstractID], [AbstractType], [PreviousName], [PrimaryPhone], [PrimaryAddress], [PrimaryAddress2], [EmployerName], [RegistrantLastName], [RegistrantFirstName], [DeclarationNumber], [MHInstfrom], [MHInstTo], [AnestheticLabor], [PrenatalVisitDate], [NumberPrenatalVisits], [Gravida], [Parity], [ObsEducation], [SmokingPerDay], [SmokingQuitDate], [AlcoholDuringPregnancy], [Days_WeekAlcoholConsumed], [DrinksPerday], [PreConceptionalFolicAcid], [PostConceptionalFolicAcid], [FirstStageDate], [FirstStageTime], [FirstStageDuration], [SecondStageDate], [SecondStageTime], [SecondStageDuration], [Presentation], 
--				[RoutineCare], [FreeFlowOxygen], [BagVentilation], [IntubationNotMeconium], [MedicationResuscitation], [NarconMaloxone], [ChestCompressions], [Feeding], [Meconium], [Apgar1Min], [Apgar5Min], [Gestation], [MotherPHIN], [Elopements], [LeaveCertificates], [FirstStageDateUnknown], [SecondStageDateUnknown], [PrenatalVisitDateUnknown], [SmokingQuitDateUnknown], [ALC_TotalDays], [MB_Autopsy], [MB_Weight])
--	select @OrigAbstID, AbstractType, PreviousName, PrimaryPhone, PrimaryAddress, PrimaryAddress2, EmployerName, RegistrantLastName, RegistrantFirstName, DeclarationNumber, MHInstfrom, MHInstTo, AnestheticLabor, PrenatalVisitDate, NumberPrenatalVisits, Gravida, Parity, ObsEducation, SmokingPerDay, SmokingQuitDate, AlcoholDuringPregnancy, Days_WeekAlcoholConsumed, DrinksPerday, PreConceptionalFolicAcid, PostConceptionalFolicAcid, FirstStageDate, FirstStageTime, FirstStageDuration, SecondStageDate, SecondStageTime, SecondStageDuration, Presentation, RoutineCare, FreeFlowOxygen, BagVentilation, IntubationNotMeconium, 
--			MedicationResuscitation, NarconMaloxone, ChestCompressions, Feeding, Meconium, Apgar1Min, Apgar5Min, Gestation, MotherPHIN, Elopements, LeaveCertificates, FirstStageDateUnknown, SecondStageDateUnknown, PrenatalVisitDateUnknown, SmokingQuitDateUnknown, ALC_TotalDays, MB_Autopsy, MB_Weight from AB_Manitoba where AbstractID = @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_Manitoba')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into AB_MB_ALC ([AbstractID], [Occurrence], [DateDesignatedALC], [DateReassignedAcute], [ALCReasonCode], [ALCDays])
--	select @OrigAbstID, Occurrence, DateDesignatedALC, DateReassignedAcute, ALCReasonCode, ALCDays from AB_MB_ALC where AbstractID = @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_MB_ALC')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into AB_MB_FacilityStudy ([AbstractID], [Occurrence], [FacilityDateStudy], [FacilityStudyCode])
--	select @OrigAbstID, Occurrence, FacilityDateStudy, FacilityStudyCode from AB_MB_FacilityStudy where AbstractID = @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_MB_FacilityStudy')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into AB_MB_NonALC ([AbstractID], [Occurrence], [NonALCDelayReason], [DaysNonALCDelay])
--	select @OrigAbstID, Occurrence, NonALCDelayReason, DaysNonALCDelay from AB_MB_NonALC where AbstractID = @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_MB_NonALC')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into AB_MentalHealth (AbstractID, MentalReferralSource, MentalAdmitMethod, MentalLegalStatus, MentalAWOL, MentalSuicide, MentalPrevPsych, MentalReferralTo, MentalECTTreatment, MentalNumberECT, MentalEducation, MentalEmployment, MentalFinancial) 
--	select @OrigAbstID, MentalReferralSource, MentalAdmitMethod, MentalLegalStatus, MentalAWOL, MentalSuicide, MentalPrevPsych, MentalReferralTo, MentalECTTreatment, MentalNumberECT, MentalEducation, MentalEmployment, MentalFinancial from AB_MentalHealth where AbstractID = @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_MentalHealth')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into AB_MIS (AbstractID, MISOccurrence, MISCode, DirectCost, IndirectCost, SupplyCost) 
--	select @OrigAbstID, MISOccurrence, MISCode, DirectCost, IndirectCost, SupplyCost from AB_MIS where AbstractID = @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_MIS')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into dbo.AB_PatientService (AbstractID, ServiceOccurrence, PatientService, ServiceType, ServiceDays, ServiceNursingArea, ServiceNursingUnits, ServiceTransferInDate, ServiceTransferInTime, ServiceTransferOutDate, ServiceTransferOutTime) 
--	select @OrigAbstID, ServiceOccurrence, PatientService, ServiceType, ServiceDays, ServiceNursingArea, ServiceNursingUnits, ServiceTransferInDate, ServiceTransferInTime, ServiceTransferOutDate, ServiceTransferOutTime from AB_PatientService where AbstractID = @AbstractID 
    set @sql = dbo.GetCorrectionForMerge('AB_PatientService')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into AB_Project (AbstractID, ProjectOccurrence, ProjectNumber, Question1, Question2, Question3, Question4, Question5, Question6, Question7, Question8, Question9, Question10, Question11, Question12, Question13, Question14, Question15, Question16, Question17) 
--	select @OrigAbstID, ProjectOccurrence, ProjectNumber, Question1, Question2, Question3, Question4, Question5, Question6, Question7, Question8, Question9, Question10, Question11, Question12, Question13, Question14, Question15, Question16, Question17 from AB_Project where AbstractID = @AbstractID 
    set @sql = dbo.GetCorrectionForMerge('AB_Project')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into AB_Provider (AbstractID, ProviderOccurrence, ProviderType, ProviderNumber, ProviderService, ProviderSpecialty, ProviderCallDate, ProviderCallTime, ProviderArriveDate, ProviderArriveTime, ProviderTotalTime) 
--	select @OrigAbstID, ProviderOccurrence, ProviderType, ProviderNumber, ProviderService, ProviderSpecialty, ProviderCallDate, ProviderCallTime, ProviderArriveDate, ProviderArriveTime, ProviderTotalTime from AB_Provider where AbstractID = @AbstractID 
    set @sql = dbo.GetCorrectionForMerge('AB_Provider')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into AB_ReproductiveCare (AbstractID, PrevTermDelivery, PrevPreTermDelivery, PrevSpontAbortions, PrevInduceAbortions, PrevLiveBirths, GestationalAge, DeliveryDate, DeliveryTime, LastMensesDate, BreastFeeding, InitialOR, SubsequentOR, Sterilization, Complication1, Complication2, Complication3, ReprodComments) 
--	select @OrigAbstID, PrevTermDelivery, PrevPreTermDelivery, PrevSpontAbortions, PrevInduceAbortions, PrevLiveBirths, GestationalAge, DeliveryDate, DeliveryTime, LastMensesDate, BreastFeeding, InitialOR, SubsequentOR, Sterilization, Complication1, Complication2, Complication3, ReprodComments from AB_ReproductiveCare where AbstractID = @AbstractID 
    set @sql = dbo.GetCorrectionForMerge('AB_ReproductiveCare')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into AB_SpecialCareUnit (AbstractID, SCUOccurrence, SCUNumber, SCUAdmitDate, SCUAdmitTime, SCUDischDate, SCUDischTime, SCULOS, SCUDiagCode) 
--	select @OrigAbstID, SCUOccurrence, SCUNumber, SCUAdmitDate, SCUAdmitTime, SCUDischDate, SCUDischTime, SCULOS, SCUDiagCode from AB_SpecialCareUnit where AbstractID = @AbstractID 
    set @sql = dbo.GetCorrectionForMerge('AB_SpecialCareUnit')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into AB_Therapeutic (AbstractID, PhysioTherapy, PhysioUnits, OccupationalTherapy, OccupationalUnits, SpeechTherapy, SpeechUnits, RespiratoryTherapy, RespiratoryUnits, FirstOptionTherapy, FirstOptionUnits, SecondOptionTherapy, SecondOptionUnits) 
--	select @OrigAbstID, PhysioTherapy, PhysioUnits, OccupationalTherapy, OccupationalUnits, SpeechTherapy, SpeechUnits, RespiratoryTherapy, RespiratoryUnits, FirstOptionTherapy, FirstOptionUnits, SecondOptionTherapy, SecondOptionUnits from AB_Therapeutic where AbstractID = @AbstractID 
    set @sql = dbo.GetCorrectionForMerge('AB_Therapeutic')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into AB_TransferService ([AbstractID], [Occurrence], [TransService], [TransType], [TransDays], [TransPriority], [TransNursingArea], [TransNursingUnits], [TransInDate], [TransInTime], [TransOutDate], [TransOutTime])
--	select @OrigAbstID, Occurrence, TransService, TransType, TransDays, TransPriority, TransNursingArea, TransNursingUnits, TransInDate, TransInTime, TransOutDate, TransOutTime from AB_TransferService where AbstractID = @AbstractID 
    set @sql = dbo.GetCorrectionForMerge('AB_TransferService')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into AB_UDAbstracting ([Abstractid], [UDDate1], [UDDate2], [UDDate3], [UDDate4], [UDTime1], [UDTime2], [UDTime3], [UDTime4], [UDLookup1], [UDLookup2], [UDLookup3], [UDLookup4], [UDInteger1], [UDInteger2], [UDInteger3], [UDInteger4], [UDText1], [UDText2], [UDText3], [UDText4], [UDSmallText1], [UDSmallText2], [UDSmallText3], [UDSmallText4])
--	select @OrigAbstID, UDDate1, UDDate2, UDDate3, UDDate4, UDTime1, UDTime2, UDTime3, UDTime4, UDLookup1, UDLookup2, UDLookup3, UDLookup4, UDInteger1, UDInteger2, UDInteger3, UDInteger4, UDText1, UDText2, UDText3, UDText4, UDSmallText1, UDSmallText2, UDSmallText3, UDSmallText4 from AB_UDAbstracting where AbstractID = @AbstractID 
    set @sql = dbo.GetCorrectionForMerge('AB_UDAbstracting')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

	update REC_Notes set RecordID = @OrigAbstID where AppID in (200, 201, 202) and RecordID = @AbstractID     
-- 	insert into dbo.REC_Notes (LogID, AppID, RecordID, LogNote, LogDate, LogTime, LogCoder) 
-- 	select isnull(max(LogID), 0) + 1, AppID, @OrigAbstID, LogNote, LogDate, LogTime, LogCoder from REC_Notes where AppID in (200, 201, 202) and RecordID = @AbstractID 

--	insert into AB_VendorAssigned ([AbstractID], [VendorID], [MCC], [CMG], [Plx], [RIW], [DPG])
--	select @OrigAbstID, VendorID, MCC, CMG, Plx, RIW, DPG from AB_VendorAssigned where AbstractID = @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_VendorAssigned')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into dbo.AB_CMG (AbstractID, OccurrenceNumber, CMG_Year, ICD_Type, Diagnosis_Code, Diagnosis_Type, Diagnosis_Grade, CMG, Complexity, MCC, MCC_Surg, CMG_Split, AcuteQuartile, MOHQuartile, CMG_RIW, MOH_RIW, RIW_Dollar, MOH_Dollar, CMG_ELOS, CMG_Trim, CMG_Description, CMGModelType, CMGTenthPercent, CMGTwentyFifthPercent, CMGFiftiethPercent, ExpiryDate, CMGAgeCategory, ComorbidityLevel, FlaggedIntervFactorCount, InterventionEventCount, InterventionOOHCount, InpatientRIWAtypicalCode, InpatientRILevel, IntervCode, CMG_Partition) 
--	select @OrigAbstID, OccurrenceNumber, CMG_Year, ICD_Type, Diagnosis_Code, Diagnosis_Type, Diagnosis_Grade, CMG, Complexity, MCC, MCC_Surg, CMG_Split, AcuteQuartile, MOHQuartile, CMG_RIW, MOH_RIW, RIW_Dollar, MOH_Dollar, CMG_ELOS, CMG_Trim, CMG_Description, CMGModelType, CMGTenthPercent, CMGTwentyFifthPercent, CMGFiftiethPercent, ExpiryDate, CMGAgeCategory, ComorbidityLevel, FlaggedIntervFactorCount, InterventionEventCount, InterventionOOHCount, InpatientRIWAtypicalCode, InpatientRILevel, IntervCode, CMG_Partition
--    from AB_CMG where AbstractID = @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_CMG')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

-- 	insert into dbo.AB_CACS (AbstractID, OccurrenceNumber, CACS_Year, MAC, CACSCell, ACW, CACSDescription,  InterventionCode) 
--	select @OrigAbstID, OccurrenceNumber, CACS_Year, MAC, CACSCell, ACW, CACSDescription,  InterventionCode from AB_CACS where AbstractID = @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_CACS')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

--	insert into dbo.AB_DPG (AbstractID, OccurrenceNumber, DPG_Year, DPG, DPG_RIW, DPG_MOH_RIW, DPG_Description, InterventionCode) 
--	select @OrigAbstID, OccurrenceNumber, DPG_Year, DPG, DPG_RIW, DPG_MOH_RIW, DPG_Description, InterventionCode from AB_DPG where AbstractID = @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_DPG')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

    --New NACRS tables
    set @sql = dbo.GetCorrectionForMerge('AB_Consult')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_PresentingComplaints')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_NACRS')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_DischargeDiagnosis')
    --print @sql
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_CCM_CancerCareInformation')
    --print @sql
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_CCM_Radiation')
    --print @sql
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_CCM_SystemicDrug')
    --print @sql
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID
    --CJRR
    set @sql = dbo.GetCorrectionForMerge('AB_CJRR')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID
    set @sql = dbo.GetCorrectionForMerge('AB_CJRR_Parts')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID
    --ED Intervention Value Set
    set @sql = dbo.GetCorrectionForMerge('AB_EDInterventionValueSet')
    exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @AbstractID

        
	insert into AB_updateAudit ([Abstractid], [Occurrence], [Fieldid], [Coder], [updated], [OldValue], [NewValue], [Appid])
	select @OrigAbstID, Occurrence, FieldID, Coder, updated, OldValue, NewValue, AppID from AB_updateAudit where AppID in (200, 201, 202, 401) and AbstractID = @AbstractID

	--NP-00025
	insert into AB_updateHistory (AbstractID, HospitalID, Coder, updated, UpdateType) 
	select @OrigAbstID, HospitalID, Coder, updated, UpdateType from AB_updateHistory where AbstractID = @AbstractID

	set @CType = case when @CareType = 'A' then 1 when @CareType = 'D' then 2 else 5 end
	exec U_AB_Main @AbstractID, @CType
	exec U_AB_Main @OrigAbstID, @CType

	insert into MRG_SubmitCorrect values ( @OrigAbstID, @OrigChart, @AbstractID, @NewChart, @CType ) --PR-02208
end
--PR - 04020
else if @CareType = 'R'
begin
	set @CType = 3
    select AbstractID into #AllAssessment from RH_ClientInfo where LinkID = @AbstractID and IsSubmited = 1 and IsDeleted = 2

    declare cur_Rehab cursor for
        select AbstractID from #AllAssessment
    open cur_rehab
    fetch from cur_rehab into @ID
    while(@@fetch_status = 0)
    begin
	    --Copy the Abstract to a new record and set it up for insertion
        set @sql = dbo.GetCorrectionForMerge('RH_ClientInfo')
	    select @OrigChart = (select ChartNumber from RH_ClientInfo where AbstractID = @ID) 
	    select @OrigAbstID = (select isnull(max(AbstractID), 0) from RH_ClientInfo) + 1
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
	    --update the original for deletion			
	    update RH_ClientInfo set IsCorrected = 1, IsSubmited = 2, CIHIDateSent = '', BatchYear = null, BatchPeriod = null, AbstractNumber = null 
        where AbstractID = @ID

        set @sql = dbo.GetCorrectionForMerge('RH_Activity')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('RH_Administrative')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('RH_Ancillary')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('RH_BasicOption')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('RH_Demographic')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('RH_Diagnosis')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID

        insert into dbo.RH_FIM_RPG(LinkID, FIM_Motor, FIM_Cognitive, RG, RPG, Weight, ShortStay, LongStay)
        select @OrigAbstID, FIM_Motor, FIM_Cognitive, RG, RPG, Weight, ShortStay, LongStay
        from dbo.RH_FIM_RPG
        where LinkID = @ID

        set @sql = dbo.GetCorrectionForMerge('RH_FIM_Score')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('RH_FollowUpAssess')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('RH_Health')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('RH_Intervention')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('RH_Project')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('RH_Provider')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('RH_Rehabilitation')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('RH_ServiceInterupt')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('RH_UDAbstracting')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID

	    insert into dbo.RH_UpdateHistory(AbstractID, HospitalID, Coder, updated, UpdateType) 
	    select @OrigAbstID, HospitalID, Coder, updated, UpdateType 
        from RH_UpdateHistory where AbstractID = @ID

	    exec U_AB_Main @ID, @CType
	    exec U_AB_Main @OrigAbstID, @CType

	    insert into MRG_SubmitCorrect values ( @OrigAbstID, @OrigChart, @ID, @NewChart, @CType ) 
        fetch from cur_rehab into @ID
    end
    close cur_rehab
    deallocate cur_rehab
    drop table #AllAssessment
end
--CCRS does not have correction.
--else if @CareType = 'L'
--begin
--	set @CType = 4
--    select AbstractID into #AllAssessmentCCRS from CRS_Demographic where LinkID = @AbstractID and IsSubmited = 1 and IsDeleted = 2
--
--    declare cur_ccrs cursor for
--        select AbstractID from #AllAssessmentCCRS
--    open cur_ccrs
--    fetch from cur_ccrs into @ID
--    while(@@fetch_status = 0)
--    begin
--	    --Copy the Abstract to a new record and set it up for insertion
--        set @sql = dbo.GetCorrectionForMerge('CRS_Demographic')
--	    select @OrigChart = (select ChartNumber from CRS_Demographic where AbstractID = @ID) 
--	    select @OrigAbstID = (select isnull(max(AbstractID), 0) from CRS_Demographic) + 1
--        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
--	    --update the original for deletion			
--	    update CRS_Demographic set IsSubmited = 2, CIHIDateSent = '', BatchYear = null, BatchPeriod = null 
--        where AbstractID = @ID
--
--        set @sql = dbo.GetCorrectionForMerge('CRS_Admission')
--        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
--        set @sql = dbo.GetCorrectionForMerge('CRS_Ancillary')
--        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
--        set @sql = dbo.GetCorrectionForMerge('CRS_AssessFull1')
--        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
--        set @sql = dbo.GetCorrectionForMerge('CRS_AssessFull2')
--        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
--        set @sql = dbo.GetCorrectionForMerge('CRS_AssessShare1')
--        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
--        set @sql = dbo.GetCorrectionForMerge('CRS_AssessShare2')
--        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
--        set @sql = dbo.GetCorrectionForMerge('CRS_AssessShare3')
--        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
--        set @sql = dbo.GetCorrectionForMerge('CRS_AssessShare4')
--        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
--        set @sql = dbo.GetCorrectionForMerge('CRS_AssessShare5')
--        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
--        set @sql = dbo.GetCorrectionForMerge('CRS_BasicOption')
--        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
--        set @sql = dbo.GetCorrectionForMerge('CRS_Diagnosis')
--        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
--        set @sql = dbo.GetCorrectionForMerge('CRS_Hobic')
--        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
--        set @sql = dbo.GetCorrectionForMerge('CRS_Medication')
--        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
--        set @sql = dbo.GetCorrectionForMerge('CRS_Project')
--        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
--        set @sql = dbo.GetCorrectionForMerge('CRS_RAPS')
--        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
--        set @sql = dbo.GetCorrectionForMerge('CRS_RAPS2')
--        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
--        set @sql = dbo.GetCorrectionForMerge('CRS_RUGS')
--        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
--        set @sql = dbo.GetCorrectionForMerge('CRS_Signature')
--        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
--        set @sql = dbo.GetCorrectionForMerge('CRS_UDAbstracting')
--        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
--
--	    insert into dbo.CRS_UpdateHistory(AbstractID, HospitalID, Coder, updated, UpdateType) 
--	    select @OrigAbstID, HospitalID, Coder, updated, UpdateType 
--        from CRS_UpdateHistory where AbstractID = @ID
--
--	    exec U_AB_Main @ID, @CType
--	    exec U_AB_Main @OrigAbstID, @CType
--
--	    insert into MRG_SubmitCorrect values ( @OrigAbstID, @OrigChart, @ID, @NewChart, @CType ) 
--        fetch from cur_ccrs into @ID
--    end
--    close cur_ccrs
--    deallocate cur_ccrs
--    drop table #AllAssessmentCCRS
--end
else if @CareType = 'M'
begin
	set @CType = 7
    select aa.AbstractID into #AllAssessmentOMHRS from OMHRS_SecAA aa inner join OMHRS_RecInfo i on aa.AbstractID = i.AbstractID
    where LinkID = @AbstractID and IsSubmited = 1 and IsDeleted = 2

    declare cur_ccrs cursor for
        select AbstractID from #AllAssessmentOMHRS
    open cur_ccrs
    fetch from cur_ccrs into @ID
    while(@@fetch_status = 0)
    begin
	    --Copy the Abstract to a new record and set it up for insertion
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecAA')
	    select @OrigChart = (select ChartNumber from OMHRS_SecAA where AbstractID = @ID) 
	    select @OrigAbstID = (select isnull(max(AbstractID), 0) from OMHRS_SecAA) + 1
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
	    --update the original for deletion			
        exec @X1 = [dbo].[P_UpdateOMHRS_X1] --PR - 04465
	    update OMHRS_SecAA set x2 = 200301, X1 = @x1 where AbstractID = @ID
	    update OMHRS_SecAA set x2 = 200303 where AbstractID = @OrigAbstID

        set @sql = dbo.GetCorrectionForMerge('OMHRS_RecInfo')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
	    --update the original for deletion	
	    update OMHRS_RecInfo 
        set IsSubmited = 2, IsCorrected = 1, CIHIDateSent = '', BatchYear = null, BatchPeriod = null 
        where AbstractID = @ID

        set @sql = dbo.GetCorrectionForMerge('OMHRS_Ancillary')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_BasicOption')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_CIHIErrors')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_DSM_Diag')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_Medication')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        exec dbo.P_UpdateOMHRS_X1_ForCorrection @ID --PR - 04465
        set @sql = dbo.GetCorrectionForMerge('OMHRS_MHAPS')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_Project')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_Provider')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecA')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecB')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecBB')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecC')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecCC')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecD')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecDD')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecE')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecF')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecG')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecH')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecI')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecJ')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecK')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecL')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecM')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecN')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecO')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecP')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecQ')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecR')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_SecS')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_Serv_Interrupt')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID
        set @sql = dbo.GetCorrectionForMerge('OMHRS_UserDefined')
        exec sp_executesql @sql, N'@NewID int, @OldID int', @OrigAbstID, @ID

	    insert into dbo.OMHRS_UpdateHistory(AbstractID, HospitalID, Coder, updated, UpdateType) 
	    select @OrigAbstID, HospitalID, Coder, updated, UpdateType 
        from OMHRS_UpdateHistory where AbstractID = @ID

	    exec U_AB_Main @ID, @CType
	    exec U_AB_Main @OrigAbstID, @CType

	    insert into MRG_SubmitCorrect values ( @OrigAbstID, @OrigChart, @ID, @NewChart, @CType ) 
        fetch from cur_ccrs into @ID
    end
    close cur_ccrs
    deallocate cur_ccrs
    drop table #AllAssessmentOMHRS
end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is called when a Chart is Changed or Merged to set up the Abstracts for Corrections
CREATE PROCEDURE [P_UpdateAbstractForCorrection_Undo]
    @AbstractID	int,
    @CareType 	varchar(1)
AS

declare @CType int

--AMCARE ICD 10
if @CareType = 'B' 
begin
	update AB_Abstract set IsCorrected = 1, CIHIReturnStatus = 1,
        IsCorrectLevel1 = 1, CIHIReturnStatusLevel1 = 1
    where AbstractID = @AbstractID
    	exec U_AB_Main @AbstractID, 5
end

-- INPATIENT/SDS ICD 10
else if @CareType in ('A', 'D') 
begin
	set @CType = case when @CareType = 'A' then 1 when @CareType = 'D' then 2 end

	update AB_Abstract set IsDeleted = 2, IsCorrected = 1 where AbstractID = @AbstractID
	exec U_AB_Main @AbstractID, @CType
end
--PR - 04020
else if @CareType in ('R') 
begin
	set @CType = 3

	update RH_ClientInfo set IsDeleted = 2, IsCorrected = 1 where AbstractID = @AbstractID
	exec U_AB_Main @AbstractID, @CType
end
else if @CareType in ('L') 
begin
	set @CType = 4

	update dbo.CRS_Demographic set IsDeleted = 2 where AbstractID = @AbstractID
	exec U_AB_Main @AbstractID, @CType
end
else if @CareType in ('M') 
begin
	set @CType = 7

	update dbo.OMHRS_RecInfo set IsDeleted = 2, IsCorrected = 1 where AbstractID = @AbstractID
	exec U_AB_Main @AbstractID, @CType
end


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is called when a Chart is Um-Merged to undo the set up the Abstracts for Corrections
CREATE PROCEDURE [P_UpdateAbstractForCorrection_UndoAuto]
    @ChartOrig 	varchar(50),
    @ChartNew 	varchar(50)
AS
declare  @AID_O as int
declare  @AID_N as int
declare  @CType int
declare  @AppID int 

declare cur cursor local fast_forward for 
	select AbstID_Orig, AbstID_New, CareType from MRG_SubmitCorrect where Chart_Orig = @ChartOrig and Chart_New = @ChartNew
open cur
while (1=1) begin
	fetch next from cur into @AID_O , @AID_N, @CType
    	if (@@fetch_status <> 0) break
    if @CType in (1, 2, 5)
    begin
	    --Don't do this if the correction was already sent
	    if exists(select AbstractID from AB_Abstract where AbstractID = @AID_O) 
	    begin
		    select @CType = CareType from AB_Abstract where AbstractID = @AID_O
		    select @AppID = AppID from AB_Main where AbstractID = @AID_O and AppID in (200, 201, 202, 401)

		    update AB_Abstract set 
			    --IsCorrected = z.IsCorrected, --Iscorrection should be always 2 in deletion.
			    CIHIReturnStatus = z.CIHIReturnStatus, 
			    IsSubmited = z.IsSubmited, 
			    CIHIDateSent = z.CIHIDateSent, 
			    BatchYear = z.BatchYear, 
			    BatchPeriod = z.BatchPeriod, 
			    BatchNumber = z.BatchNumber, 
			    AbstractNumber = z.AbstractNumber,  
                IsSubmitLevel1 = z.IsSubmitLevel1,  --NP - 00125
                IsCorrectLevel1 = z.IsCorrectLevel1, --NP - 00125
                IsValidLevel1 = z.IsValidLevel1,  --NP - 00125
                CIHIReturnStatusLevel1 = z.CIHIReturnStatusLevel1, --NP - 00125
                CIHIDateSentLevel1 = z.CIHIDateSentLevel1 --NP - 00125
		    from 
			    (select IsCorrected, 
				    CIHIReturnStatus, 
				    IsSubmited, 
				    CIHIDateSent, 
				    BatchYear, 
				    BatchPeriod, 
				    BatchNumber, 
                    AbstractNumber, 
                    IsSubmitLevel1, IsCorrectLevel1, IsValidLevel1, CIHIReturnStatusLevel1, CIHIDateSentLevel1
                    from AB_Abstract where AbstractID = @AID_O
			    ) as z
		    where AbstractID = @AID_N

		    exec D_AB_Abstract @AID_O, @AppID
		    --exec U_AB_Main @AID_O, @CType
		    exec U_AB_Main @AID_N, @CType
	    end
    end
    --PR - 04020
    else if @CType = 3
    begin
	    --Don't do this if the correction was already sent
	    if exists(select AbstractID from RH_ClientInfo where AbstractID = @AID_O) 
	    begin
		    select @AppID = AppID from AB_Main where AbstractID = @AID_O and AppID in (250, 251, 252, 253)

		    update RH_ClientInfo set 
			    IsSubmited = z.IsSubmited, 
			    CIHIDateSent = z.CIHIDateSent, 
			    BatchYear = z.BatchYear, 
			    BatchPeriod = z.BatchPeriod, 
			    AbstractNumber = z.AbstractNumber
		    from 
			    (select IsCorrected, 
				    IsSubmited, 
				    CIHIDateSent, 
				    BatchYear, 
				    BatchPeriod, 
				    AbstractNumber from RH_ClientInfo where AbstractID = @AID_O
			    ) as z
		    where AbstractID = @AID_N

		    exec D_RH_ClientInfo @AID_O
		    --exec U_AB_Main @AID_O, @CType
		    exec U_AB_Main @AID_N, @CType
	    end
    end
--    else if @CType = 4
--    begin
--	    --Don't do this if the correction was already sent
--	    if exists(select AbstractID from CRS_Demographic where AbstractID = @AID_O) 
--	    begin
--		    select @AppID = AppID from AB_Main where AbstractID = @AID_O and AppID between 470 and 479
--
--		    update CRS_Demographic set 
--			    IsSubmited = z.IsSubmited, 
--			    CIHIDateSent = z.CIHIDateSent, 
--			    BatchYear = z.BatchYear, 
--			    BatchPeriod = z.BatchPeriod
--		    from 
--			    (select 
--				    IsSubmited, 
--				    CIHIDateSent, 
--				    BatchYear, 
--				    BatchPeriod from CRS_Demographic where AbstractID = @AID_O
--			    ) as z
--		    where AbstractID = @AID_N
--
--		    exec D_CRS_Demographic @AID_O, @AppID
----		    exec U_AB_Main @AID_O, @CType
--		    exec U_AB_Main @AID_N, @CType
--	    end
--    end
    else if @CType = 7
    begin
	    --Don't do this if the correction was already sent
	    if exists(select AbstractID from OMHRS_RecInfo where AbstractID = @AID_O) 
	    begin
		    select @AppID = AppID from AB_Main where AbstractID = @AID_O and AppID between 650 and 655

		    update OMHRS_RecInfo set 
                IsSubmited = z.IsSubmited, 
			    CIHIDateSent = z.CIHIDateSent, 
			    BatchYear = z.BatchYear, 
			    BatchPeriod = z.BatchPeriod
		    from 
			    (select 
                    IsSubmited, 
				    CIHIDateSent, 
				    BatchYear, 
				    BatchPeriod from OMHRS_RecInfo where AbstractID = @AID_O
			    ) as z
		    where AbstractID = @AID_N

            update OMHRS_SecAA 
            set X1 = z.X1
		    from 
			    (select X1 from OMHRS_SecAA where AbstractID = @AID_O) as z
		    where AbstractID = @AID_N   --PR - 04465 Restore original X1.

		    exec D_OMHRS_SecAA @AID_O
		    --exec U_AB_Main @AID_O, @CType
		    exec U_AB_Main @AID_N, @CType
	    end
    end
end

delete MRG_SubmitCorrect where Chart_Orig = @ChartOrig and Chart_New = @ChartNew
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [P_UpdateAbstractNumber]
   (@AbstractID                    [int],
    @AdmitDate                     [datetime],
    @DischDate                     [datetime])
AS 
--PR-01550
declare @CA as int
select @CA = isnull(CIHI_AbstractID, 0) from AB_Abstract where AbstractID = @AbstractID

--AB Must always have a unique ID across all batches
if exists (select Code from H_HospitalProfile where ProvinceNumber = 8) and @CA <= 0
	update AB_Abstract set CIHI_AbstractID = @AbstractID where AbstractID = @AbstractID

else if not exists (select Code from H_HospitalProfile where ProvinceNumber = 8) and @CA <= 0
begin
	declare @VDate as datetime
	declare @BDate as varchar(10)
	declare @BYear as int 
	declare @BPerd as int 

	set @VDate = GetDate() 
	if isdate(@DischDate) = 1 set @VDate = @DischDate
	if isdate(@AdmitDate) = 1 set @VDate = @AdmitDate

	set @BDate = convert(nvarchar(10), @VDate, 111)
	set @BYear = convert(int, left(@BDate, 4))
	set @BPerd = convert(int, substring(@BDate, 6, 2))

	if @bPerd >= 4 
		set @BPerd = @BPerd - 3
	else 
		set @BPerd = @BPerd + 9
	
	set @CA = (select max(isnull(CIHI_AbstractID, 0)) 
			from AB_Abstract 
            		where CareType = 5 
			and BatchYear = @BYear 
                	and BatchPeriod = @BPerd 
			and AbstractNumber < 9000000)

	if @CA is null set @CA = 0
	set @CA = @CA + 1
	update AB_Abstract set CIHI_AbstractID = @CA where AbstractID = @AbstractID
end




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

-- This updates the Abstract with a Volume Number
CREATE PROCEDURE [P_UpdateAbstractVolume]
	@VolumeID AS INTEGER,
    @UniversalID as integer = 0,
	@AID as Integer = 0	
AS

--     10756 - Changed to also use the Visit History
--     @AbstractID AS INTEGER

    declare @CT as int 
    declare @EN as varchar(100)
    declare @CN as varchar(100)
    declare @AD as datetime
    declare @AT as datetime
    declare @Inst as int
    declare @Count int

    declare @AbstractID as integer

    if @AID = 0
    Begin
    --9753
        select 	
            @AbstractID = AbstractID,    --PR - 03001
            @CT = AppType, 
    		@EN = EncounterNumber, 
    		@CN = ChartNumber, 
            @AD = AdmitDate, 
    		@AT = AdmitTime, 
    		@Inst = InstitutionNumber 
        from AB_Main where [UniversalID] = @UniversalID
        --PR - 03001
	    --set @AbstractID = (select AbstractID from AB_Main where [UniversalID] = @UniversalID) --and AppType in (1, 2, 5))
    End
    else
    Begin
	    set @AbstractID = @AID
        --PR - 03001
	    --set @UniversalID = (select UniversalID from AB_Main where [AbstractID] = @AbstractID and AppType in (1, 2, 5))
        select 	
            @UniversalID = UniversalID,    
            @CT = AppType, 
    		@EN = EncounterNumber, 
    		@CN = ChartNumber, 
            @AD = AdmitDate, 
    		@AT = AdmitTime, 
    		@Inst = InstitutionNumber 
        from AB_Main where [AbstractID] = @AbstractID and AppType in (1, 2, 5)
    End

    update [AB_Main] set [VolumeID] = @VolumeID where [UniversalID] = @UniversalID
    if  @CT in (1, 2, 5)
        update [AB_Abstract] set [VolumeID] = @VolumeID where [AbstractID] = @AbstractID
    --PR-01560
    --PR - 01838 I don't know the reason for it.
    --update [Def_SlipMain] set [DefVolumeID] = @VolumeID where DefMainStatus <> 8 and DefAbstractID = @UniversalID
    update [Def_SlipMain] set [DefVolumeID] = @VolumeID where DefMainStatus <> 8 and DefAbstractID = @UniversalID and isnull(DefAbstractID, 0) <> 0


/*Tvail for speed increase    if @CT = 5
    begin
        update [AB_Main] set [VolumeID] = @VolumeID  where [EncounterNumber] = @EN and ChartNumber = @CN and [AdmitDate] = @AD and [AdmitTime] = @AT and [AppType] = 5
        update [AB_Abstract] set [VolumeID] = @VolumeID  where [EncounterNumber] = @EN and ChartNumber = @CN and [AdmitDate] = @AD and [AdmitTime] = @AT and [CareType] = 5
    end
*/
    --PR - 03001
    if @CT = 5 and isnull(@EN, '') <> ''
    begin
    	select Abstractid, VolumeID, EncounterNumber, AdmitTime, Caretype into #QTemp 
        from ab_abstract
    	where chartnumber = @CN and InstitutionNumber = @Inst and admitdate = @AD
            and AbstractID <> @AbstractID
        set @Count = @@rowcount
        delete from #QTemp where CareType <> 5 or isnull(EncounterNumber, '') <> @EN or isnull(AdmitTime, '1950/01/01') <> @AT
        set @Count = @Count - @@rowcount
        if @Count > 0
        begin
            create index idx_QTEmp_AbstractID on #QTemp(AbstractID)
            update [AB_Main] set [VolumeID] = @VolumeID 
            from AB_Main m
                inner join #QTemp z on m.AbstractID = z.AbstractID and m.AppType = 5
            where isnull(m.VolumeID, 0) <> @VolumeID

            update [AB_Abstract] set [VolumeID] = @VolumeID  
            from AB_Abstract m
                inner join #QTemp z on m.AbstractID = z.AbstractID 
            where isnull(m.VolumeID, 0) <> @VolumeID

        end
--         update [AB_Main] set [VolumeID] = @VolumeID where [EncounterNumber] = @EN and ChartNumber = @CN and [AdmitDate] = @AD and [AdmitTime] = @AT and [AppType] = 5
--         update [AB_Abstract] set [VolumeID] = @VolumeID  where abstractid in ( select abstractid from #QTemp
-- 		   where [EncounterNumber] = @EN and [AdmitTime] = @AT and [CareType] = 5 and VolumeID <> @VolumeID)
    end

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE   PROCEDURE [P_UpdateBillingNum]
	(@BillNo BIGINT OUTPUT,
	 @HospID int = 0)
AS 

-- If the Start Number is Greater than the Max, use it instead.
if @HospID = 0
begin
	SET @BillNo = (SELECT TOP 1 CAST(ISNULL(StartBillingNumber, 0) AS BIGINT) FROM H_HospitalProfile) + 1 
	UPDATE [H_HospitalProfile] SET [StartBillingNumber] = @BillNo
end

else
begin
	SET @BillNo = (SELECT CAST(ISNULL(StartBillingNumber, 0) AS BIGINT) FROM H_HospitalProfile where Code = @HospID) + 1 
	UPDATE [H_HospitalProfile] SET [StartBillingNumber] = @BillNo where Code = @HospID
end

RETURN 0





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE  PROCEDURE [P_UpdateBillingSequence]
	(@BillNo INT OUTPUT,
	 @HospID int)
AS 

-- Get the Max Chart Number. 
-- If the Start Number is Greater than the Max, use it instead.
if @HospID = 0
	SET @BillNo = (SELECT TOP 1 CAST(ISNULL(StartBillingSequence, 0) AS INT) FROM H_HospitalProfile) + 1 
else
	SET @BillNo = (SELECT CAST(ISNULL(StartBillingSequence, 0) AS INT) FROM H_HospitalProfile where Code = @HospID) + 1 

-- Reset if Bill Number is over 1000
IF @BillNo = 1000 SET @BillNo = 1

if @HospID = 0
	UPDATE [H_HospitalProfile] SET [StartBillingSequence] = @BillNo
else
	UPDATE [H_HospitalProfile] SET [StartBillingSequence] = @BillNo where Code = @HospID

RETURN 0




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE      PROCEDURE [P_UpdateChartNum]
	(@Chart varchar(10) output, 
	 @HospID int = 0)
as 

declare @ChA as varchar(2) 	-- Stores Alpha value (if there is one)
declare @ChN as bigint		-- Stores value in Profile
declare @CChN as bigint 	-- Stores value in CPI

declare @HID as int
set @HID = @HospID
if @HospID = 0 select top 1 @HID = isnull(Code, 0) from H_HospitalProfile 

--CHECK and SEE if THE CHART IS SHARED and set UP IN THE REGION PROFILE INSTEAD OF Hospital
if exists (select * from H_RegionProfile where isnull(AutoGenChartNum, 0) = 1)
and exists (select * from H_HospitalProfile where Code = @HID and isnull(AutoGenChartNum, 0) <> 1)
begin
	--Numeric Chart
	select isnull(StartChartNumber, 0) from H_RegionProfile where isnumeric(left(StartChartNumber, 2)) = 1
    	if @@RowCount = 1 
    	begin
		set @ChA = ''
		set @ChN = (select cast(isnull(StartChartNumber, 0) as bigint) from H_RegionProfile) + 1 
    		set @CChN = (select max(cast(isnull(ChartNumber, 0) as bigint)) + 1 from CM_CPI where isnumeric(ChartNumber) = 1 and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end))
    	end
    
    	--Two Digit Alpha Chart
    	select StartChartNumber from H_RegionProfile where isnumeric(left(StartChartNumber, 2)) = 0 and isnumeric(substring(StartChartNumber, 2, 1)) = 0 
    	if @@RowCount = 1 
    	begin
    		set @ChA = (select left(StartChartNumber, 2) from H_RegionProfile)
		set @ChN = (select cast(isnull(substring(StartChartNumber, 3, LEN(StartChartNumber) - 2), 0) as bigint) from H_RegionProfile) + 1 
    		set @CChN = (select max(cast(isnull(substring(ChartNumber, 3, LEN(ChartNumber) - 2), 0) as bigint)) + 1 from CM_CPI where left(ChartNumber, 2) = @ChA and isnumeric(substring(ChartNumber, 3, LEN(ChartNumber) - 2)) = 1 and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end))
    	end
    
    	--One Digit Alpha Chart
    	select StartChartNumber from H_RegionProfile where isnumeric(left(StartChartNumber, 1)) = 0 and isnumeric(substring(StartChartNumber, 2, 1)) = 1 
    	if @@RowCount = 1  
    	begin
    		set @ChA = (select left(StartChartNumber, 1) from H_RegionProfile )
		set @ChN = (select cast(isnull(substring(StartChartNumber, 2, LEN(StartChartNumber) - 1), 0) as bigint) from H_RegionProfile ) + 1 
    		set @CChN = (select max(cast(isnull(substring(ChartNumber, 2, LEN(ChartNumber) - 1), 0) as bigint)) + 1 from CM_CPI where left(ChartNumber, 1) = @ChA and isnumeric(substring(ChartNumber, 2, LEN(ChartNumber) - 1)) = 1 and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end))
    	end

	-- If the Start Number is Greater than the Max, use it instead.
	if isnull(@CChN, -1)  > isnull(@ChN, -1) set @ChN = @CChN
	if isnull(@ChN, -1) < 0 set @ChN = 1
	
	set @Chart = @ChA + cast(@ChN as varchar(10))		
	update [H_RegionProfile] set [StartChartNumber] = @Chart 
end
else
begin
	--Numeric Chart
    	select isnull(StartChartNumber, 0) from H_HospitalProfile where isnumeric(left(StartChartNumber, 2)) = 1 and Code = @HID
    	if @@RowCount = 1 
    	begin
		set @ChA = ''
		set @ChN = (select cast(isnull(StartChartNumber, 0) as bigint) from H_HospitalProfile where Code = @HID) + 1 
    		set @CChN = (select max(cast(isnull(ChartNumber, 0) as bigint)) + 1 from CM_CPI where isnumeric(ChartNumber) = 1 and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end))    		
    	end
    
    	--Two Digit Alpha Chart
    	select StartChartNumber from H_HospitalProfile where isnumeric(left(StartChartNumber, 2)) = 0 and isnumeric(substring(StartChartNumber, 2, 1)) = 0 and Code = @HID
    	if @@RowCount = 1 
    	begin
    		set @ChA = (select left(StartChartNumber, 2) from H_HospitalProfile where Code = @HID)
		set @ChN = (select cast(isnull(substring(StartChartNumber, 3, LEN(StartChartNumber) - 2), 0) as bigint) from H_HospitalProfile where Code = @HID) + 1 
    		set @CChN = (select max(cast(isnull(substring(ChartNumber, 3, LEN(ChartNumber) - 2), 0) as bigint)) + 1 from CM_CPI where left(ChartNumber, 2) = @ChA and isnumeric(substring(ChartNumber, 3, LEN(ChartNumber) - 2)) = 1 and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end))    		
	end
    
    	--One Digit Alpha Chart
    	select StartChartNumber from H_HospitalProfile where isnumeric(left(StartChartNumber, 1)) = 0 and isnumeric(substring(StartChartNumber, 2, 1)) = 1 and Code = @HID
    	if @@RowCount = 1  
    	begin
    		set @ChA = (select left(StartChartNumber, 1) from H_HospitalProfile where Code = @HID)
		set @ChN = (select cast(isnull(substring(StartChartNumber, 2, LEN(StartChartNumber) - 1), 0) as bigint) from H_HospitalProfile where Code = @HID) + 1 
    		set @CChN = (select max(cast(isnull(substring(ChartNumber, 2, LEN(ChartNumber) - 1), 0) as bigint)) + 1 from CM_CPI where left(ChartNumber, 1) = @ChA and isnumeric(substring(ChartNumber, 2, LEN(ChartNumber) - 1)) = 1 and (isnull(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else isnull(HospitalID, 0) end))
    	end

	-- If the Start Number is Greater than the Max, use it instead.
	if isnull(@CChN, -1)  > isnull(@ChN, -1) set @ChN = @CChN
	if isnull(@ChN, -1) < 0 set @ChN = 1
    
    	set @Chart = @ChA + cast(@ChN as varchar(10))		
    	update [H_HospitalProfile] set [StartChartNumber] = @Chart where Code = @HID
end
return 0



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- This updates the CIHI Return status to be used by Amcare Submissions & Corrections.  
CREATE   PROCEDURE [P_UpdateCIHIReturnStatus]
    @AbstractID 	int,
    @CIHIReturnStatus 	int 
AS   
-- If a 1 is passed that means that it's not been accepted by CIHI and the period is still open.   
-- So all we have to do is re-submit. Otherwise this will be a correction.  
if (@CIHIReturnStatus = 1)   
    update AB_Abstract set 	
	IsSubmited = 2,
      	IsCorrected = 1,
	CIHIReturnStatus = @CIHIReturnStatus,
	CIHIDateSent = NULL,
	--PR - 05486
	BatchYear = (case when CareType <> 5 then NULL else BatchYear end),
	BatchPeriod = (case when CareType <> 5 then 0 else BatchPeriod end),
	BatchNumber = (case when CareType <> 5 then Null else BatchNumber end),
	AbstractNumber = (case when CareType <> 5 then NULL else AbstractNumber end)
	--BatchYear = (case when CareType <> 5 or isnull( IsSubmitLevel1, 0) in (0, 2) then NULL else BatchYear end),
	--BatchPeriod = (case when CareType <> 5 or isnull( IsSubmitLevel1, 0) in (0, 2) then 0 else BatchPeriod end),
	--BatchNumber = (case when CareType <> 5 or isnull( IsSubmitLevel1, 0) in (0, 2) then Null else BatchNumber end),
	--AbstractNumber = (case when CareType <> 5 or isnull( IsSubmitLevel1, 0) in (0, 2) then NULL else AbstractNumber end)
    where AbstractID = @AbstractID and isnull( IsSubmitLevel1, 0) in (0, 2)
else 
    update AB_Abstract set 	
	IsSubmited = 1,
	IsCorrected = 2,
	CIHIReturnStatus = @CIHIReturnStatus   
    where AbstractID = @AbstractID  

--NP - 00125 Introduce NACRS Level 1
--if (@CIHIReturnStatus = 1)  
--begin 
--    if @SubmissionLevel = 3
--        update AB_Abstract    
--    	set CIHIDateSent = NULL,
--      	    IsSubmited = 2,
--	        IsCorrected = 1,
--      	    CIHIReturnStatus = @CIHIReturnStatus,
--        where AbstractID = @AbstractID  
--    else if @SubmissionLevel = 1
--        update AB_Abstract    
--  	    set CIHIDateSent = NULL,
--            IsSubmitLevel1 = 2,
--            IsCorrectLevel1 = 1,
--            CIHIReturnStatusLevel1 = @CIHIReturnStatus 
--        where AbstractID = @AbstractID  
--    else --for both level 3 and 1
--        update AB_Abstract    
--  	    set CIHIDateSent = NULL,
--		    BatchYear = NULL,
--		    BatchPeriod = 0,
--		    BatchNumber = NULL,
--		    AbstractNumber = NULL,
--      	    IsSubmited = 2,
--	        IsCorrected = 1,
--      	    CIHIReturnStatus = @CIHIReturnStatus,
--            IsSubmitLevel1 = 2,   
--            IsCorrectLevel1 = 1,   
--            CIHIReturnStatusLevel1 = @CIHIReturnStatus
--        where AbstractID = @AbstractID  
--end
--else 
--    update AB_Abstract   
--    set 	--IsSubmited = 1,
--      		IsCorrected = (case when IsSubmited = 1 then 2 else IsCorrected end),
--      		CIHIReturnStatus = (case when IsSubmited = 1 then @CIHIReturnStatus else CIHIReturnStatus end),   
--            IsCorrectLevel1 = (case when IsSubmitLevel1 = 1 then 2 else IsCorrectLevel1 end),
--            CIHIReturnStatusLevel1 = (case when IsSubmitLevel1 = 1 then @CIHIReturnStatus else CIHIReturnStatusLevel1 end)
--    where AbstractID = @AbstractID  
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- This updates the CIHI Return status to be used by Amcare Submissions & Corrections for Level 1.  
CREATE    PROCEDURE [P_UpdateCIHIReturnStatus_Level1] --NP - 00125
    @AbstractID 	int,
    @CIHIReturnStatus 	int 
AS   
-- If a 1 is passed that means that it's not been accepted by CIHI and the period is still open.   
-- So all we have to do is re-submit. Otherwise this will be a correction.  
if (@CIHIReturnStatus = 1)   
    update AB_Abstract set 	
	IsSubmitLevel1 = 2,
	IsCorrectLevel1 = 1,
	CIHIReturnStatusLevel1 = @CIHIReturnStatus,
	CIHIDateSentLevel1 = NULL,
	--PR - 05486
	BatchYear = (case when CareType <> 5 then NULL else BatchYear end),
	BatchPeriod = (case when CareType <> 5 then 0 else BatchPeriod end),
	BatchNumber = (case when CareType <> 5 then Null else BatchNumber end),
	AbstractNumber = (case when CareType <> 5 then NULL else AbstractNumber end)
	--BatchYear = (case when CareType <> 5 or isnull( IsSubmited, 0) in (0, 2) then NULL else BatchYear end),
	--BatchPeriod = (case when CareType <> 5 or isnull( IsSubmited, 0) in (0, 2) then 0 else BatchPeriod end),
	--BatchNumber = (case when CareType <> 5 or isnull( IsSubmited, 0) in (0, 2) then Null else BatchNumber end),
	--AbstractNumber = (case when CareType <> 5 or isnull( IsSubmited, 0) in (0, 2) then NULL else AbstractNumber end)
    where AbstractID = @AbstractID  
else 
    update AB_Abstract set 	
	IsSubmitLevel1 = 1,
	IsCorrectLevel1 = 2,
	CIHIReturnStatusLevel1 = @CIHIReturnStatus   
    where AbstractID = @AbstractID  


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is called by the Amcare Submission to clear a previous submit.
CREATE PROCEDURE [P_UpdateClearAmcareSubmit]
    @InstNumber   int
  , @BatYear      int
  , @BatPeriod    int
  , @CIHIDateSent datetime
  , @HospID 	  int = 0
  , @LevelCode    int = 3   --NP - 00125
AS 
If isnull(@LevelCode, 3) not in (0, 1, 2)
    UPDATE AB_Abstract
    SET IsSubmited = 2
      , IsCorrected = 1
      , CIHIDateSent = NULL
      , CIHIReturnStatus = 1
    WHERE InstitutionNumber = @InstNumber 
    AND BatchYear = @BatYear 
    AND BatchPeriod = @BatPeriod 
    AND convert(varchar(20), CIHIDateSent, 100) = convert(varchar(20), @CIHIDateSent, 100)
    AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
else If @LevelCode in (1, 2) --NP - 00125
    UPDATE AB_Abstract
    SET IsSubmitLevel1 = 2
      , IsCorrectLevel1 = 1
      , CIHIDateSentLevel1 = NULL
      , CIHIReturnStatusLevel1 = 1
    from AB_Abstract
        inner join LU_MISCode on MISCode = LU_MISCode.Code
    WHERE InstitutionNumber = @InstNumber 
    AND BatchYear = @BatYear 
    AND BatchPeriod = @BatPeriod 
    AND convert(varchar(20), CIHIDateSentLevel1, 100) = convert(varchar(20), @CIHIDateSent, 100)
    and LU_MISCode.AmcareGroup = 'ED'
    AND (ISNULL(AB_Abstract.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(AB_Abstract.HospitalID, 0) end)
else If @LevelCode = 0 --2.x-1683 -   Clear Submission - Care Type 'B-C-Lite'
    UPDATE AB_Abstract
    SET IsSubmitLevel1 = 2
      , IsCorrectLevel1 = 1
      , CIHIDateSentLevel1 = NULL
      , CIHIReturnStatusLevel1 = 1
    from AB_Abstract
        inner join LU_MISCode on MISCode = LU_MISCode.Code
    WHERE InstitutionNumber = @InstNumber 
    AND BatchYear = @BatYear 
    AND BatchPeriod = @BatPeriod 
    AND convert(varchar(20), CIHIDateSentLevel1, 100) = convert(varchar(20), @CIHIDateSent, 100)
    and [ClinicLite] = 1
    AND (ISNULL(AB_Abstract.HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(AB_Abstract.HospitalID, 0) end)

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE        PROCEDURE [P_UpdateClinicEncNum]
	(@EncNo BigInt output,
	 @HospID as int = 0)
AS 

if @HospID = 0
begin
	SET @EncNo = (SELECT TOP 1 ClinicEncNumber FROM H_HospitalProfile) + 1
	UPDATE [H_HospitalProfile] SET [ClinicEncNumber] = @EncNo 
end
else
begin	
	SET @EncNo = (SELECT ClinicEncNumber FROM H_HospitalProfile WHERE Code = @HospID) + 1
	UPDATE [H_HospitalProfile] SET [ClinicEncNumber] = @EncNo WHERE Code = @HospID
end	

RETURN 0




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- This is called by the Submit for Clinic Billing when the record has been save to a file.
CREATE    PROCEDURE [P_UpdateClinicSubmitted]
	(@ProvdNum 	[int])
AS 
	--Do All Un-Submitted Records
	IF @ProvdNum = 0 
		UPDATE [CR_Demographic] 
		SET [IsSubmited] = 1, [IsValidated] = 4, [IsCompleted] = 4, [BillDate] = GetDate()
		WHERE IsDeleted = 2 AND IsSubmited <> 1
	ELSE
		UPDATE [CR_Demographic]
		SET [IsSubmited] = 1, [IsValidated] = 4, [IsCompleted] = 4, [BillDate] = GetDate()
		FROM dbo.CR_Demographic INNER JOIN dbo.CR_Visit ON dbo.CR_Demographic.AbstractID = dbo.CR_Visit.AbstractID
		WHERE IsDeleted = 2 AND IsSubmited <> 1 AND ProviderNumber = @ProvdNum



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This is called by the Batch Verify if a record is clean, but not flaged for Verified & Complete. (Usually from Conversions).
CREATE    PROCEDURE [P_UpdateCompleteVerifyAbstract]
	(@AbstractID	[int],
	 @AbstStatus	[int])
AS 
UPDATE [AB_Abstract] SET [IsValidated] = @AbstStatus, [IsCompleted] = @AbstStatus WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is called by the Batch Verify if a record is clean, but not flaged for Verified & Complete. (Usually from Conversions).
CREATE PROCEDURE [P_UpdateCompleteVerifyAbstractLevel1] --NP-00125
	(@AbstractID	[int],
	 @AbstStatus	[int],
	 @UpdateComplete [int])
AS 

if @UpdateComplete = 0
	update [AB_Abstract] set [IsValidLevel1] = @AbstStatus where [AbstractID] = @AbstractID
else
	update [AB_Abstract] set [IsValidLevel1] = @AbstStatus, [IsCompleteLevel1] = @AbstStatus where [AbstractID] = @AbstractID
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE    PROCEDURE [P_UpdateCompleteVerifyCCRS]
	(@AbstractID	[int],
	 @AbstStatus	[int])
AS 
update [CRS_Demographic] set [IsValidated] = @AbstStatus, [IsCompleted] = @AbstStatus where ([AbstractID] = @AbstractID)


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

-- This is called by the Batch Verify if a record is clean, but not flaged for Verified & Complete. (Usually from Conversions).
create    PROCEDURE [P_UpdateCompleteVerifyCJRR]
	(@RecordID		[int],
	 @AbstStatus	[int])
AS 
update [CJRR_Abstract] set [IsValidated] = @AbstStatus, [IsCompleted] = @AbstStatus where ([RecordID] = @RecordID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- This is called by the Batch Verify for Clinic Billing if a record is clean, but not flaged for Verified & Complete. (Usually from Conversions).
CREATE    PROCEDURE [P_UpdateCompleteVerifyClinic]
	(@AbstractID	[int],
	 @AbstStatus	[int])
AS 
UPDATE [CR_Demographic] SET [IsValidated] = @AbstStatus, [IsCompleted] = @AbstStatus WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE    PROCEDURE [P_UpdateCompleteVerifyOMHRS]
	(@AbstractID	[int],
	 @AbstStatus	[int])
AS 
update [OMHRS_RecInfo] set [IsValidated] = @AbstStatus, [IsCompleted] = @AbstStatus where ([AbstractID] = @AbstractID)


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This is called by the Batch Verify if a record is clean, but not flaged for Verified & Complete. (Usually from Conversions).
CREATE    PROCEDURE [P_UpdateCompleteVerifyRehab]
	(@AbstractID	[int],
	 @AbstStatus	[int])
AS 
UPDATE [RH_ClientInfo] SET [IsValidated] = @AbstStatus, [IsCompleted] = @AbstStatus WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_UpdateCPIDeathDate]
	(@ChartNumber AS VarChar(10),
	@DeathDate AS Datetime,
	@DischargeDate AS DateTime,
	@HospID as int = 0)
AS 

declare @ret as int --PR-01823

--10858
--if  (select top 1 DischargeDate from dbo.AB_Abstract where (ChartNumber = @ChartNumber) order by DischargeDate desc) = @DischargeDate
if  (select top 1 Convert(NVarChar(10), DischargeDate, 111) from dbo.AB_Main where (ChartNumber = @ChartNumber) order by DischargeDate desc) = Convert(NVarChar(10),  @DischargeDate, 111) 
begin
	if @HospID = 0
	begin
		if @DeathDate is null
		begin
			--1270 -   Death Indicator in CPI not updating 
			update CM_CPI set DeathDate = null, DeathIndicator = 0 where ChartNumber = @ChartNumber and DeathIndicator = 1
			update AB_Main set DeathIndicator = 0 where ChartNumber = @ChartNumber and AppID = 0 and DeathIndicator = 1   --PR - 05124
		end
		else
		begin
			update CM_CPI set DeathDate = @DeathDate, DeathIndicator = 1 where ChartNumber = @ChartNumber
			update AB_Main set DeathIndicator = 1 where ChartNumber = @ChartNumber and AppID = 0    --PR - 05124
		end
	end
	else
	begin
		set @ret = (select count(*) from CM_CPI WHERE ChartNumber = @ChartNumber AND ISNULL(HospitalID, 0) = @HospID) 
		if @ret <> 0 
		begin
			if @DeathDate is null
			begin
				--1270 -   Death Indicator in CPI not updating 			
				update CM_CPI set DeathDate = null, DeathIndicator = 0 where ChartNumber = @ChartNumber and DeathIndicator = 1 and ISNULL(HospitalID, 0) = @HospID
				update AB_Main set DeathIndicator = 0 where ChartNumber = @ChartNumber and AppID = 0 and DeathIndicator = 1 and ISNULL(HospitalID, 0) = @HospID   --PR - 05124
			end
			else
			begin
				update CM_CPI set DeathDate = @DeathDate, DeathIndicator = 1 where ChartNumber = @ChartNumber and ISNULL(HospitalID, 0) = @HospID
				update AB_Main set DeathIndicator = 1 where ChartNumber = @ChartNumber and AppID = 0 and ISNULL(HospitalID, 0) = @HospID   --PR - 05124
			end
		end
		else
		begin
			if @DeathDate is null
			begin
				--1270 -   Death Indicator in CPI not updating 			
				update CM_CPI set DeathDate = null, DeathIndicator = 0 where ChartNumber = @ChartNumber and DeathIndicator = 1
				update AB_Main set DeathIndicator = 0 where ChartNumber = @ChartNumber and AppID = 0 and DeathIndicator = 1 --PR - 05124
			end
			else
			begin
				update CM_CPI set DeathDate = @DeathDate, DeathIndicator = 1 where ChartNumber = @ChartNumber
				update AB_Main set DeathIndicator = 1 where ChartNumber = @ChartNumber and AppID = 0 --PR - 05124
			end
		end
	end
end


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [P_UpdateCustomVerifyAbstract]
	(@AbstractID	[int],
	 @AbstStatus	[int],
     @CareType      varchar(50))
AS 
    if @CareType in ('A', 'B', 'D')
        UPDATE [AB_Abstract] SET IsCustomValidated = @AbstStatus WHERE ([AbstractID] = @AbstractID)
    else --    if @CareType in ('A', 'B', 'D')
        UPDATE [dbo].[CJRR_Abstract] SET IsCustomValidated = @AbstStatus WHERE ([RecordID] = @AbstractID)


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO






-- This is called by the Deficiency Letters to update the status to show that a Letter has been sent.
CREATE     PROCEDURE [P_UpdateDeficiencyLetter]
	(@DefID	[int],
	 @Provider	[int],
	 @Coder 	[int],
	 @Level	[int])
AS 
-- Update the Deficiency.
--EN-00183
UPDATE Def_SlipMain SET DefMainStatus = @Level WHERE DefID = @DefID --DefeciencyID = @DefID

-- Insert a new Provider Log entry.
INSERT INTO [dbo].[REC_Notes] 
	([LogID], [AppID], [RecordID], [LogNote], [LogDate], [LogTime], [LogCoder]) 
	SELECT ISNULL(MAX(LogID), 0) + 1,  1104, @Provider, 'Letter ' + CONVERT(varchar(10), @Level - 1) + ' Sent', GetDate(), GetDate(), @Coder FROM REC_Notes





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE         PROCEDURE [P_UpdateInstitutionEncNum]
	(@Code [int], @EncNo BigInt output)
AS 

declare @AEncNo as BigInt 

set @EncNo = (select cast(isnull(StartEncounterNumber, 0) as bigint) from H_InstitutionProfile where ([Code] = @Code)) + 1 
set @AEncNo = (select cast(max(isnull(EncounterNumber, 0)) as bigint ) + 1 from ab_abstract where isnumeric( encounternumber ) = 1 and institutionnumber = @Code)

-- If the Start Number is Greater than the Max, use it instead.
if isnull(@AEncNo, -1)  > isnull(@EncNo, -1) set @EncNo = @AEncNo
if isnull(@EncNo, -1) < 0 set @EncNo = 1

update [H_InstitutionProfile] set [StartEncounterNumber] = @EncNo where [Code] = @Code

return 0



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec [dbo].[P_UpdateOMHRS_X1]
CREATE PROCEDURE [P_UpdateOMHRS_X1]
as 

declare @X1 int
declare @AX1 as Int 
declare @MX1 as Int 
declare @ABS as int

select @AX1 = cast(max(isnull(X1, 0)) as int ) + 1, @ABS = max(AbstractID) + 1 from OMHRS_SecAA

--set @AX1 = (select cast(max(isnull(X1, 0)) as int ) + 1 from OMHRS_SecAA)
set @MX1 = (select cast(max(isnull(X1, 0)) as int ) + 1 from OMHRS_Medication)
set @X1 = (select cast(isnull(StartOMHRS_X1, 0) as int) + 1 from H_RegionProfile)

-- If the Start Number is Greater than the Max, use it instead.

if isnull(@ABS, -1)  > isnull(@X1, -1) set @X1 = @ABS
if isnull(@AX1, -1)  > isnull(@X1, -1) set @X1 = @AX1
if isnull(@MX1, -1)  > isnull(@X1, -1) set @X1 = @MX1
if isnull(@X1, -1) < 0 set @X1 = 1
if @X1 = 0 set @X1 = 1

--PR - 03364 Ticket PR - 02960 ask to use facility ID for the X1 in OMHRS facility files.
--  This cause the OMHRS submission X1 duplicate issue.
declare @FacilityID bigint
set @FacilityID = isnull((select max(FacilityFileID) from H_Institutionprofile where FacilityFileID is not null), 0)

if @X1 = @FacilityID 
    set @X1 = @X1 + 1
-------------    
--PR - 05159 
update [H_RegionProfile] set [StartOMHRS_X1] = @X1 where isnull([StartOMHRS_X1], 0) < @X1
--update [H_RegionProfile] set [StartOMHRS_X1] = @X1 
if @@rowcount = 0   -- Another call update X1 just ahead this call
begin
    begin transaction X1
    update [H_RegionProfile] set [StartOMHRS_X1] = isnull([StartOMHRS_X1], 0) + 1    
    set @X1 = (select StartOMHRS_X1 from H_RegionProfile)
    commit transaction X1
end

return @X1
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create procedure [P_UpdateOMHRS_X1_ForCorrection]
    @ID int
as
    --PR - 04465
declare @x1 int
declare @occ int

declare cur_x1_corr cursor for
    select Occurrence from dbo.OMHRS_Medication where AbstractID = @ID order by Occurrence
open cur_x1_corr
fetch next from cur_x1_corr into @occ
while (@@fetch_status = 0)
begin
    exec @X1 = [dbo].[P_UpdateOMHRS_X1] 
    update dbo.OMHRS_Medication set X1 = @x1 where AbstractId = @ID and Occurrence = @occ
    fetch next from cur_x1_corr into @occ
end
close cur_x1_corr
deallocate cur_x1_corr
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- This updates the Last Date Password was changed
CREATE    PROCEDURE [P_UpdatePasswordChangeDates]
	@UserID as Integer,
	@LastPasswordDate AS DateTime,
	@NewPasswordDate AS DateTime
AS 

	UPDATE [U_Users] SET [PasswordChanged] = @LastPasswordDate, [ChangePasswordDate] = @NewPasswordDate WHERE [Code] = @UserID




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- This is called by the Deficiency Letters to update the status to show that a Letter has been sent.
CREATE PROCEDURE [P_UpdateProviderDeficiencyLetter]
	(@Provider	[int],
	 @Coder 	[int],
	 @Level	[int])
AS 
-- Update the Deficiency.
Update LU_Provider 
set ProvdrCurLetter = @Level, ProvdrLastUpdateDate = getdate()
where Code = @Provider

-- Update the Deficiency.
-- PR - 01841
-- UPDATE Def_SlipMain 
-- SET DefMainStatus = @Level 
-- WHERE DefDrNumber = @Provider and DefMainStatus not in (8, 11)

-- declare @MaxLevel int
-- set @MaxLevel = isnull((select top 1 ProvdrMaxLetter from LU_Provider where code = @Provider), 0)
-- 
-- UPDATE Def_SlipMain 
-- SET DefMainStatus = NewLevel 
-- from Def_SlipMain s
--     inner join
--     (select DefeciencyID, isnull(min(code), 0) as NewLevel 
--      from Def_SlipMain sm 
--         inner join dbo.DefLU_ChartStatus s on sm.DefDays >= NumberDays
--      WHERE sm.DefDrNumber = @Provider and sm.DefMainStatus not in (8, 11) 
--         and Code <= @MaxLevel and Code between 2 and 6 and isnull(DefDays , 0) > 0
--      group by DefeciencyID) m on s.DefeciencyID = m.DefeciencyID
-- where isnull(s.DefMainStatus, 0) <> NewLevel

-- Insert a new Provider Log entry.
INSERT INTO [dbo].[REC_Notes] 
	([LogID], [AppID], [RecordID], [LogNote], [LogDate], [LogTime], [LogCoder]) 
	SELECT ISNULL(MAX(LogID), 0) + 1,  1104, @Provider, 'Letter ' + CONVERT(varchar(10), @Level) + ' Sent', GetDate(), GetDate(), @Coder FROM REC_Notes

exec P_ResetProviderCurrentLevel @Provider



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

-- This updates the User's Fields Sort Order
CREATE    PROCEDURE [P_UpdateSortOrder]
	@AppID as Integer,
	@UserID as Integer,
	@FieldID as Integer,
	@GroupID as integer,
	@SortOrder as Integer
AS 
	update [U_UsersFields] 
	set 
		SortOrder = @SortOrder, 
		GroupID = @GroupID 
	where AppID = @AppID 
	and UserID = @UserID 
	and FieldID = @FieldID
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE    PROCEDURE [P_UpdateTransNum]
	(@TransNo BIGINT OUTPUT,
	 @HospID int = 0)
AS 
-- Get the Max Chart Number. 
declare @HID as int
set @HID = @HospID
if @HospID = 0 select top 1 @HID = isnull(Code, 0) from H_HospitalProfile 

if exists (select * from H_HospitalProfile where Code = @HID and isnull(StartTransNumber, 0) = 0)
begin
	set @TransNo = (select max(cast(isnull(TranscriptionID, 0) as bigint)) + 1 from TR_Main where isnumeric(isnull(TranscriptionID, ' ')) = 1)
	
	if isnumeric(@TransNo) <> 1 set @TransNo = 0
	-- If the Start Number is Greater than the Max, use it instead.
	if (select cast(isnull(StartTransNumber, 0) as bigint) from H_RegionProfile ) >= @TransNo
		set @TransNo = (select cast(isnull(StartTransNumber, 0) as bigint) from H_RegionlProfile ) + 1 
	
	update [H_RegionProfile] set [StartTransNumber] = @TransNo 
end

else
begin
	SET @TransNo = (SELECT MAX(CAST(ISNULL(TranscriptionID, 0) AS BIGINT)) + 1 FROM TR_Main WHERE ISNUMERIC(ISNULL(TranscriptionID, ' ')) = 1)
	
	IF ISNUMERIC(@TransNo) <> 1 SET @TransNo = 0
	-- If the Start Number is Greater than the Max, use it instead.
	IF (SELECT CAST(ISNULL(StartTransNumber, 0) AS BIGINT) FROM H_HospitalProfile WHERE Code = @HID) >= @TransNo
		SET @TransNo = (SELECT CAST(ISNULL(StartTransNumber, 0) AS BIGINT) FROM H_HospitalProfile WHERE Code = @HID) + 1 
	
	UPDATE [H_HospitalProfile] SET [StartTransNumber] = @TransNo WHERE Code = @HID
end

return 0


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO





-- This updates the User's Password
CREATE    PROCEDURE [P_UpdateUserPassword]
	@Password AS VarChar(15),
	@UserID as Integer
AS 
	Set @Password = replace(isnull(char(ASCII(SUBSTRING(reverse(@Password), 1, 1)) - 10), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 2, 1)) - 11), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 3, 1)) - 12), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 4, 1)) - 13), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 5, 1)) - 14), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 6, 1)) - 15), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 7, 1)) - 16), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 8, 1)) - 17), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 9, 1)) - 18), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 10, 1)) - 19), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 11, 1)) - 20), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 12, 1)) - 21), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 13, 1)) - 22), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 14, 1)) - 23), '') +
	isnull(char(ASCII(SUBSTRING(reverse(@Password), 15, 1)) - 24), ''), '               ', '')

	UPDATE [U_Users] SET [UserPassword] = @Password WHERE [Code] = @UserID

	exec I_U_Users_password @UserID, @Password	--2.x-0205


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [P_UpdateVolumeDigitalIndicator](
    @VolumeID int, @HospitalID int, @UniversalID int = 0)
as
--TS-222
    declare @MDAS int
    declare @TotalCount int, @MDASCount int, @DigitalIndicator int
    
    --TS-771
    if isnull(@VolumeID, 0) = 0 and @UniversalID > 0
        set @VolumeID = (select top 1 volumeID from ab_main where UniversalID = @UniversalID)
   
    if @VolumeID > 0 
    begin
        set @MDAS = (select top 1 ascii(substring(cdkey, 24, 1)) from h_hospitalprofile where isnull(@HospitalID, 0) in (0, code))
        
        if (@MDAS % 3 = 0 or @MDAS % 2 = 0) 
        begin    
            select @TotalCount = count(*), @MDASCount = sum(case when [HasDAS] > 0 then 1 else 0 end) from AB_Main where VolumeID = @VolumeID and AppID > 0
            if @MDASCount > 0 
            begin
                if @TotalCount = @MDASCount    
                    set @DigitalIndicator = 1
                else 
                    set @DigitalIndicator = 2
            end
            else
                set @DigitalIndicator = 0    
            
            update CM_CPI_Volume 
	        set DigitalIndicator = @DigitalIndicator    
	        where VolumeID = @VolumeID and isnull(DigitalIndicator, 0) <> @DigitalIndicator
        end
    end
    return isnull(@DigitalIndicator, 0)
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE   PROCEDURE [P_WinRecsLogout]
	@Userid as int
AS

	delete M_NCoder where Userid = @Userid
	--9741
	--delete M_CurrentLogIn where UserName in (select UserName from U_Users where Code = @UserID) --NP-00025
	delete M_CurrentLogIn where Code = @UserID --NP-00025


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- Sets the Deleted Flag to No (Recover the Abstract)
CREATE  PROCEDURE [R_AB_Abstract] 
    @AbstractID int
AS 
UPDATE AB_Abstract 
SET IsDeleted = 2 
WHERE AbstractID = @AbstractID

-- This will update Amcare records that are return type 2 (Delete). 
-- There is no way to know if changes were made before the delete 
-- so the assumption will be that there were and it wil be sent to 
-- CIHI as such. Better safe than sorry.
UPDATE AB_Abstract 
SET CIHIReturnStatus = (case IsSubmited when 1 then 4 else 1 end)
  , IsCorrected      = (case IsSubmited when 1 then 2 else 1 end)
  , CIHIReturnStatusLevel1 = (case IsSubmitLevel1 when 1 then 4 else 1 end) --NP - 00125
  , IsCorrectLevel1      = (case IsSubmitLevel1 when 1 then 2 else 1 end)   --NP - 00125
FROM AB_Abstract 
WHERE AbstractID = @AbstractID 
AND CareType = 5
-- AND CIHIReturnStatus = 2 




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


-- Sets the Deleted Flag to NO
CREATE PROCEDURE [R_AB_Main] (@UniversalID [int])
AS 

UPDATE [AB_Main] SET [IsDeleted] = 2 WHERE ([UniversalID] = @UniversalID)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [R_Calculate_CodingDuration]
    @StartDate datetime,
    @EndDate datetime,
    @Institution varchar(1000) = '',
    @IsVisitDate varchar(1) = 'Y'    --Y - Visit Date  others - Save Date
as
--set @StartDate = '2021/08/01'
--set @EndDate = '2021/08/31'
--set @Institution = '51234,51235'
set nocount on

create table #ID (AbstractID int primary key)
set @StartDate = cast(convert(varchar(50), @StartDate, 111) + ' 00:00' as datetime)
set @EndDate = cast(convert(varchar(50), @EndDate, 111) + ' 23:59' as datetime)

if @IsVisitDate = 'Y'
begin
    if isnull(@Institution, '') = ''
        insert into #ID 
        select AbstractID 
        from AB_Abstract with (nolock)
        where (AdmitDate between @StartDate and @EndDate and CareType = 5)
            or (DischargeDate between @StartDate and @EndDate and CareType <> 5)
    else
        insert into #ID 
        select AbstractID 
        from AB_Abstract ab with (nolock)
            inner join H_InstitutionProfile h with (nolock) on ab.InstitutionNumber = h.code 
            inner join [dbo].[SplitByDelimiter](@Institution, ',') s on h.DisplayCode = s.[value]
        where (AdmitDate between @StartDate and @EndDate and CareType = 5)
            or (DischargeDate between @StartDate and @EndDate and CareType <> 5)
end
else
begin
    if isnull(@Institution, '') = ''
        insert into #ID 
        select distinct AbstractID 
        from AB_UpdateHistory h with (nolock)
        where h.Updated between @StartDate and @EndDate and Coder not in (55555, 66666, 77777, 88888, 99999) and UpdateType = 'Saved'
    else
        insert into #ID 
        select distinct ab.AbstractID 
        from AB_Abstract ab with (nolock)
            inner join AB_UpdateHistory t with (nolock) on ab.AbstractID = t.AbstractID
            inner join H_InstitutionProfile h with (nolock) on ab.InstitutionNumber = h.code 
            inner join [dbo].[SplitByDelimiter](@Institution, ',') s on h.DisplayCode = s.[value]
        where t.Updated between @StartDate and @EndDate and Coder not in (55555, 66666, 77777, 88888, 99999) and UpdateType = 'Saved'
end

--select a.AbstractID, min(h.Updated) as minDate into #ID_MinDate
--from #ID a
--    inner join AB_UpdateHistory h with (nolock) on a.AbstractID = h.AbstractID
--where UpdateType = 'Saved'
--group by a.AbstractID

--create index idx_ID_MinDate_AbstractID on #ID_MinDate(AbstractID)

--select m.AbstractID, m.minDate into #ID_CreateByCoder
--from AB_UpdateHistory h with (nolock) 
--    inner join #ID_MinDate m on h.AbstractID = m.AbstractID
--where h.Updated = m.minDate and h.Updated = 'Saved' and h.Coder not in (55555, 66666, 77777, 88888, 99999)

--create index idx_ID_CreateByCoder_AbstractID on #ID_CreateByCoder(AbstractID)

select a.AbstractID, s.Coder, s.Updated, max(v.Updated) maxViewDate
    into #ID_MaxViewDate
from #ID a
    inner join AB_UpdateHistory s with (nolock) on a.AbstractID = s.AbstractID and s.UpdateType = 'Saved' and s.Coder not in (55555, 66666, 77777, 88888, 99999)
    left join AB_UpdateHistory v with (nolock) on a.AbstractID = v.AbstractID and s.Coder = v.Coder and v.UpdateType = 'Viewed' and v.Updated < s.Updated
group by a.AbstractID, s.Coder, s.Updated

create index idx_ID_MaxViewDate_AbstractID on #ID_MaxViewDate(AbstractID)

update v
set maxViewDate = convert(varchar(50), ab.InputDate, 111) + ' ' + convert(varchar(50), ab.InputTime, 114)
from #ID_MaxViewDate v
    inner join AB_Abstract ab with (nolock) on v.AbstractID = ab.AbstractID
where v.maxViewDate is null

select AbstractID, Coder, maxViewDate, max(Updated) as maxSaveDate
    into #ID_SaveDate
from #ID_MaxViewDate
group by AbstractID, Coder, maxViewDate

create index idx_ID_SaveDate_AbstractID on #ID_SaveDate(AbstractID)

select AbstractID, max(Updated) as maxSaveDate
    into #ID_MaxSaveDate
from #ID_MaxViewDate
group by AbstractID

create index idx_ID_MaxSaveDate_AbstractID on #ID_MaxSaveDate(AbstractID)

select z.AbstractID, max(DiagnosisOccurrence) as MaxDiagnosisOccurrence
    into #ID_DiagnosisOccurrence
from #ID_MaxViewDate z 
    inner join AB_Diagnosis d with (nolock) on z.AbstractID = d.AbstractID
group by z.AbstractID

create index idx_ID_DiagnosisOccurrence_AbstractID on #ID_DiagnosisOccurrence(AbstractID)

select z.AbstractID, max(IntervOccurrence) as MaxInterventionOccurrence
    into #ID_InterventionOccurrence
from #ID_MaxViewDate z 
    inner join AB_Intervention d with (nolock) on z.AbstractID = d.AbstractID
group by z.AbstractID

create index idx_ID_InterventionOccurrence_AbstractID on #ID_InterventionOccurrence(AbstractID)
    
select 
    AdmissionDate = AdmitDate,
    CareType = LU_CareType.DisplayCode,     CareTypeDescription = LU_CareType.UserDescription,
    ChartNumber,
    EncounterNumber,
    CoderNumber = u.DisplayCode,            CoderNumberDescription = u.UserDescription,
    DateSentCIHI = ab.CIHIDateSent,
    DischargeDate,
    IsAbstractCorrected = LU_CIHICorrect.DisplayCode,   IsAbstractCorrectedDescription = LU_CIHICorrect.UserDescription, 
    IsAbstractSubmitted = LU_IsSubmit.DisplayCode,      IsAbstractSubmittedDescription = LU_IsSubmit.UserDescription, 
    IsAbstractValidated = LU_IsValid.DisplayCode,       IsAbstractValidatedDescription = LU_IsValid.UserDescription, 
    LOSDays,
    AcuteLOS,
    ALCLOS,
    m.AmCareGroup,
    MISCode = m.DisplayCode,  MISCodeDescription = m.UserDescription,
    Diagnosis = diag.DisplayCode, DiagnosisDescription = diag.UserDescription,
    md.MaxDiagnosisOccurrence,
    Intervention = isnull(c.IntervCode, n.InterventionCode),
    InterventionDescription = (select top 1 UserDescription from ICD_ProcFile10 with (nolock) where code = isnull(c.IntervCode, n.InterventionCode)),
    mp.MaxInterventionOccurrence,
--From CMG table
    CMG,    CMGDescription = tGrouper_CMG_CMG.cmg_long_e_desc,
    CMG_RIW,
    CMG_ELOS,
    InpatientRIWAtypicalCode,
--From CACS table for SDS DAD and SDS Amcare
    CACS = n.CACSCell,  CACSDescription = tGrouper_CACS_CACS.cacs_long_e_desc,
    ACW,
    UpdateStartTime = s.maxViewDate,
    UpdateEndTime = s.maxSaveDate,
    UpdateDuration = isnull(nullif(datediff(minute,  s.maxViewDate, s.maxSaveDate), 0), 1),
    FirstCompleteDate = (case when ab.FinishDate is not null then cast(convert(varchar(20), ab.FinishDate, 111) + ' ' + isnull(convert(varchar(20), getdate(), 114), '') as datetime) end),
    LastSaveDate = x.maxSaveDate,
    zzAbstractLink = ab.AbstractID
from AB_Abstract ab with (nolock) 
    inner join #ID_SaveDate s on ab.AbstractID = s.AbstractID 
    inner join #ID_MaxSaveDate x on ab.AbstractID = x.AbstractID
    left join #ID_DiagnosisOccurrence md on ab.AbstractID = md.AbstractID 
    left join #ID_InterventionOccurrence mp on ab.AbstractID = mp.AbstractID 
    inner join H_InstitutionProfile h with (nolock) on ab.InstitutionNumber = h.Code 
    left join AB_CMG c with (nolock) on ab.AbstractID = c.AbstractID and isnull(ab.BatchYear, datepart(year, dateadd(month, -3, dischargedate))) = c.CMG_Year and c.OccurrenceNumber = 1
    left join AB_CACS n with (nolock) on ab.AbstractID = n.AbstractID and isnull(ab.BatchYear, (case when caretype = 5 then datepart(year, dateadd(month, -3, admitdate))
                                                                                                       else datepart(year, dateadd(month, -3, isnull(dischargedate, admitdate)))
                                                                                                   end)
                                                                                ) = n.CACS_Year and n.OccurrenceNumber = 1
    left join LU_CareType with (nolock) on ab.CareType = LU_CareType.Code 
    left join [dbo].[tGrouper_CACS_CACS] with (nolock) on n.CACS_Year = tGrouper_CACS_CACS.methodology_year and n.CACSCell = tGrouper_CACS_CACS.cacs_code
    left join [dbo].[tGrouper_CMG_CMG] with (nolock) on c.CMG_Year = tGrouper_CMG_CMG.methodology_year and c.CMG = tGrouper_CMG_CMG.cmg_code
    left join AB_Diagnosis d with (nolock) on ab.AbstractID = d.AbstractID and d.DiagnosisOccurrence = 1
    left join ICD_DiagFile10 diag with (nolock) on d.DiagnosisCode = diag.code 
    left join LU_MISCode m with (nolock) on ab.MISCode = m.code
    left join U_Users u with (nolock) on s.Coder = u.code
    left join LU_YesNoNumeric LU_IsSubmit with (nolock) on ab.IsSubmited = LU_IsSubmit.code
    left join LU_CIHICorrect with (nolock) on ab.IsCorrected = LU_CIHICorrect.code
    left join LU_AbstractStatus LU_IsValid with (nolock) on ab.IsValidated = LU_IsValid.code

order by ab.CareType, ab.InstitutionNumber, ab.AdmitDate, ab.ChartNumber, s.maxSaveDate

drop table #ID
drop table #ID_MaxViewDate
drop table #ID_SaveDate
drop table #ID_MaxSaveDate
drop table #ID_DiagnosisOccurrence
drop table #ID_InterventionOccurrence

set nocount off
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Sets the Deleted Flag to NO
CREATE PROCEDURE [R_CC_RecordInfo] (@RecordID [int])
AS 

UPDATE [CC_RecordInfo] SET [IsDeleted] = 2 WHERE ([AbstractID] = @RecordID)






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [R_Check_RecordLock]
    @Key varchar(1000) = ''
as
set nocount on
--EN - 00643
--declare @Key varchar(1000)
--set @key = '12|2014/01/01|2014/02/15|Y'
--declare @AppID int
declare @InstitutionNumber int
declare @DateFrom datetime
declare @DateTo datetime
declare @IsCJRR varchar(10)
declare @i int
--declare @Records table(
--    InstitutionNumber varchar(20),
--    ChartNumber varchar(10),
--    AdmitDate datetime,
--    Discharge datetime,
--    VisitDate datetime,
--    CoderNumber varchar(20)
--    CoderName varchar(500))
--@Key: InstitutionNumber, DateFrom, DateTo, IsCJRR    
If @Key is null set @Key = ''
if len(@Key) > 0
begin
    set @i = charindex('|', @Key, 1)
    --select @i
    if @i > 0 
    begin
        set @InstitutionNumber = cast(substring(@Key, 1, @i - 1) as int)
        set @DateFrom = cast(substring(@Key, @i + 1, 10) as datetime)
        set @DateTo = cast(substring(@Key, @i + 12, 10) as datetime)
        set @IsCJRR = substring(@Key, @i + 23, 10)
    end         
end

--if @InstitutionNumber > 0
--    set @AppID = (case (select top 1 AssociationID from H_InstitutionProfile where code = @InstitutionNumber)
--                    when 1 then 201
--                    when 2 then 202
--                    when 3 then 250
--                    when 4 then 470
--                    when 5 then 401
--                    when 7 then 650 end)

--insert into @Records(InstitutionNumber, ChartNumber, AdmitDate, DischargeDate, VisitDate, CoderNumber, CoderName)
select [Institution Number] = h.DisplayCode, 
    m.ChartNumber, m.AdmitDate, m.DischargeDate, m.VisitDate, 
    [Coder Number] = U.DisplayCode, 
    [Coder Name] = u.UserDescription
from dbo.W_RecordLock l
    inner join AB_Main m on l.AppID = l.AppID and l.RecordID = m.AbstractID
    inner join h_institutionProfile h on InstitutionNumber = h.code
    inner join U_users u on l.UserID = u.code
where @Key = '' or 
    (m.InstitutionNumber = @InstitutionNumber and m.VisitDate between @DateFrom and @DateTo and
        ((@IsCJRR = 'Y' and l.AppID in (40000, 40001)) or (@IsCJRR <> 'Y' and l.AppID not in (40000, 40001))))
    
set nocount off
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

-- Sets the Deleted Flag to NO
create PROCEDURE [R_CJRR_Abstract] (@RecordID [int])
AS 

update [CJRR_Abstract] set [IsDeleted] = 2 where ([RecordID] = @RecordID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- Sets the Deleted Flag to NO
CREATE PROCEDURE [R_CM_CPI] (@PatientID [int])
AS 

UPDATE [CM_CPI] SET [IsDeleted] = 2 WHERE ([PatientID] = @PatientID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [R_ControlFile]
	@Key as VarChar(50), 
	@Username as varchar(50) = '',
	@AppID as varchar(100) = '',
	@AppName as varchar(200) = ''
AS

	
--Ticket 13136. I don't know why we use "AppID > 9". I change it to "AppID >= 0". Hong

--EN - 00548
if @Key is null set @Key = ''
if @Username is null set @Username = ''
if @AppID is null set @AppID = ''
if @AppName is null set @AppName = ''
if isnumeric(@AppID) = 0 and @AppID <> '' set @AppID = '-1'
if cast(@AppID as int) < 0 set @AppID = ''
if @Key = '' and @Username = '' set @Key = '99'

set nocount on
create table #DataType(
    DataTypeDesc varchar(100) COLLATE Latin1_General_CI_AS NULL,
    Code int
)
insert into #DataType values('NUMERIC', 0)
insert into #DataType values('ALPHA ONLY', 1)
insert into #DataType values('ALPHA_NUM', 2)
insert into #DataType values('MONEY', 3)
insert into #DataType values('OCCURRENCE', 4)
insert into #DataType values('PRINTER_LIST', 5)
insert into #DataType values('WEEKDAY', 6)
insert into #DataType values('PASSWORD_MASK', 7)
insert into #DataType values('DECIMAL', 8)
insert into #DataType values('UPPER_CASE', 9)
insert into #DataType values('ZERO_FILL', 10)
insert into #DataType values('STANDARD_DATE', 11)
insert into #DataType values('CCR_DATE', 12)
insert into #DataType values('FUTURE_DATE', 13)
insert into #DataType values('SHORT_TIME', 15)
insert into #DataType values('LONG_TIME', 16)
insert into #DataType values('CCR_TIME', 17)
insert into #DataType values('FILE_FILE', 18)
insert into #DataType values('FILE_PATH', 19)
insert into #DataType values('CHRT_NUM', 20)
insert into #DataType values('BATCH_YEARS', 23)
insert into #DataType values('VOLUME_NUM', 25)
insert into #DataType values('NOTE_FLD', 97)
insert into #DataType values('NOTE_SHORT', 98)
insert into #DataType values('NOTE_LONG', 99)
insert into #DataType values('CPI Link', 101)
insert into #DataType values('ABSTRACT Link', 102)
insert into #DataType values('CCM Link', 103) 
    
	SELECT fieldid, 
	    cast(userid as varchar(20)) as Coder, 
	    UserName = (select top 1 UserDescription from u_users where (DisplayCode = @Key and @Key <> '') or (UserName = @UserName and @UserName <> '')),
	    cast(AppID as varchar(50)) as Application, 
	    Header_CIHI_English as Field_Name, Header_User, 
	    SortOrder, 
	    cast(FieldEnabled as VarChar(3)) as Enabled, 
	    Cast(FieldVisible as VarChar(3)) as Visible, 
	    cast(DefaultValue as VarChar(50)) as DefaultValue, 
	    Lookuptable,
	    FieldSize,
	    DataType = isnull(DataTypeDesc, 'Lookup'),
	    MandatoryStatus = (case MandatoryStatus when 1 then 'HOSPITAL WARNING'
	                                            when 2 then 'CIHI MANDATORY'
	                                            when 3 then 'SUBMIT MANDATORY'
	                                            when 4 then 'SYSTEM MANDATORY'
	                                            when 5 then 'PROVINCE MANDATORY'
	                                            when 6 then 'HOSPITAL ERROR'
	                                            when 7 then 'HOSPITAL REQUIRE'
	                                            when 8 then 'GENERAL MANDATORY'
	                                            else 'Not Mandatory'
	                        end)
	Into #DataDictionary
	FROM dbo.U_UsersFields left join #DataType on dbo.U_UsersFields.DataType = #DataType.Code
	WHERE (DataType <> 100000)  
	    and AppID = (case when @AppID = '' then AppID else cast(@AppID as int) end)
        and userid in (select top 1 (case when isnull(RoleID, 0) = 0 then code else RoleID end) from u_users 
        where (DisplayCode = @Key and @Key <> '') or (UserName = @UserName and @UserName <> ''))
--Ticket 13207 to disable this line
--    	AND (AppID >= 0) and appid < 655 

--Ticket 11926. Change To DisplayCode (AppID > 9) and appid < 500 and userid in (select code from u_users where cihivalue = @Key)
	
-- 	Update #DataDictionary set Application = 'Chart_Locator' where Application in ('10', '11')
-- 	Update #DataDictionary set Application = 'Chart_Deficiency' where Application = '15'
-- 	Update #DataDictionary set Application = 'Release Of Information ROI' where Application = '30'
-- 	Update #DataDictionary set Application = 'CCR_ICD9' where Application = '100'
-- 	Update #DataDictionary set Application = 'Inpatient_ICD9' where Application = '101'
-- 	Update #DataDictionary set Application = 'SDS_ICD9' where Application = '102'
-- 	Update #DataDictionary set Application = 'CCR_ICD10' where Application = '200'
-- 	Update #DataDictionary set Application = 'Inpatient_ICD10' where Application = '201'
-- 	Update #DataDictionary set Application = 'SDS_ICD10' where Application = '202'
-- 	Update #DataDictionary set Application = 'Amcare_ICD9' where Application = '301'
-- 	Update #DataDictionary set Application = 'Amcare_ICD10' where Application = '401'
-- 	Update #DataDictionary set Application = 'Amcare_ICD9' where Application = '301'
-- 	Update #DataDictionary set Application = 'Rehab Admission' where Application = '250'
-- 	Update #DataDictionary set Application = 'Rehab Discharge' where Application = '251'
-- 	Update #DataDictionary set Application = 'Rehab Followup' where Application = '252'
-- 	Update #DataDictionary set Application = 'Transcription' where Application = '20'
-- 	Update #DataDictionary set Application = 'Clinic' where Application = '451'

    Update #DataDictionary set Application = 'Visit History' where Application = '3' --Non Abstract 

    Update #DataDictionary
    set Application = u.ModuleName
    from #DataDictionary z
        inner join dbo.U_AppIDs u on z.Application = cast(u.AppID as varchar(50))

    --EN - 00548            
    if @AppID = '' and @AppName <> ''
        Delete from #DataDictionary where Application <> @AppName
 	
 	Update #DataDictionary set Application = 'Rehab Internal Assessment' where Application = '253'
 	Update #DataDictionary set Application = 'DAS' where Application = '41'

    -- eREGN_PROF = 1003
    -- eHOSP_PROF = 1000
    -- eINST_PROF = 1001
 	Update #DataDictionary set Application = 'Hospital Profile' where Application = '1000'
 	Update #DataDictionary set Application = 'Institution Profile' where Application = '1001'
 	Update #DataDictionary set Application = 'Region Profile' where Application = '1003'

	Update #DataDictionary set Enabled = 'Yes' where Enabled = '1'
	Update #DataDictionary set Enabled = 'No' where Enabled = '2'
	Update #DataDictionary set Visible = 'Yes' where Visible = '1'
	Update #DataDictionary set Visible = 'No' where Visible = '2'
	Update #DataDictionary set DefaultValue = '' where DefaultValue is null
	Update #DataDictionary set Header_User = '' where Field_Name = Header_User
	Update #DataDictionary set Coder = DisplayCode from U_Users where coder = code

	Declare @Lookup as VarChar(100)
	Declare @SQL as NVarChar(2000)
	Declare @LUCodefile as int
	set @LUCodefile = 0
	Declare cur_Defaults cursor for     
	SELECT distinct Lookuptable from #DataDictionary
	where defaultvalue <> '' and lookuptable is not null
	Open cur_Defaults  
	fetch next from cur_Defaults    
	into @Lookup
	while @@fetch_status = 0    
	begin    
	
		If isnumeric(@Lookup) = 1 and @LUCodeFile = 0
		Begin
			Set @SQL = 'Update #DataDictionary set Defaultvalue = DisplayCode
				from LU_Codefile where defaultvalue <> '''' 
                    and (case when isnumeric(defaultvalue) = 1 then defaultvalue 
                          else (select top 1 code from lu_codefile where displaycode = defaultvalue and lookupid = lookuptable)
                    end) = code 
                    and isnumeric(lookuptable) = ''1'''
			exec sp_executesql @sql
			Set @LUCodeFile = 1
		End
		Else If (@LUCodeFile = 0 and isnumeric(@Lookup) = 0 and @Lookup <> '') or (@Lookup <> '' and isnumeric(@Lookup) = 0)
		Begin
			Set @SQL = 'Update #DataDictionary set Defaultvalue = DisplayCode
				from ' + @Lookup + ' where defaultvalue <> '''' 
                and (case when isnumeric(defaultvalue) = 1 then defaultvalue 
                          else (select top 1 code from ' + @Lookup + ' where displaycode = defaultvalue)
                    end) = code 
                and lookuptable = ''' + @Lookup + ''''
			exec sp_executesql @sql
			Set @LUCodeFile = 1
		End
	
		fetch next from cur_Defaults    
		into @Lookup
	end    
	Close cur_Defaults    
	Deallocate cur_Defaults  

    delete from #DataDictionary	where isnumeric(Application) = 1

set nocount off
	select Coder = UserName, Application, FieldID, Field_Name, Header_User, SortOrder, Enabled, Visible, 
	    DefaultValue, FieldSize, DataType, MandatoryStatus
	from #DataDictionary 
	Order by coder, Application, SortOrder
	
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- Sets the Deleted Flag to NO
CREATE PROCEDURE [R_CR_Demographic] (@RecordID [int])
AS 

UPDATE [CR_Demographic] SET [IsDeleted] = 2 WHERE ([AbstractID] = @RecordID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Sets the Deleted Flag to No (Recover the Abstract)
CREATE PROCEDURE [R_CRS_Demographic] (@AbstractID [int])
AS 
 
UPDATE [CRS_Demographic] 
SET [IsDeleted] = 2, 
    IsCorrected = 1,
    Y3 = 15769 
WHERE ([AbstractID] = @AbstractID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






CREATE   PROCEDURE [R_DataDictionary]
AS
SELECT cast(AppID as varchar(50)) as Application, Header_CIHI_English as Field_Name, cast(DataType as VarChar(50)) as Data_Type, FieldSize  as Size, SortOrder, Fieldid
Into #DataDictionary
FROM dbo.U_UsersFields WHERE (UserID = 1) AND (DataType <> 100000) and appid < 700

Update #DataDictionary set Data_Type = 'Alpha-Numeric' where data_type in ('2', '6', '7', '19', '20')
Update #DataDictionary set Data_Type = 'Comment' where data_type in ('98')
Update #DataDictionary set Data_Type = 'Currency' where data_type = '3'
Update #DataDictionary set Data_Type = 'Numeric' where data_type in ('0', '4', '8', '10')
Update #DataDictionary set Data_Type = 'Alpha' where data_type in ('1', '5', '9')
Update #DataDictionary set Data_Type = 'Date-Time' where data_type in ('11', '12', '15', '16', '17')
Update #DataDictionary set Data_Type = 'Lookup' where data_type in ('42', '21', '22', '23', '25', '30', '35', '36', '37', '38', '39', '40', '41', '
42', '43', '44', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '70', '99', '100', '101', '102','26')
Update #DataDictionary set Data_Type = 'Currency' where data_type = '3'
--Do these two updates last
Update #DataDictionary set Data_Type = 'HEADER', Size = 0 where fieldid between 200 and 399
Update #DataDictionary set Application = left(ModuleName, 50)
FROM         dbo.U_AppIDs RIGHT OUTER JOIN
                      dbo.#DataDictionary ON dbo.U_AppIDs.AppID = dbo.#DataDictionary.Application

select Application, Field_Name, Data_Type, Size, SortOrder from #DataDictionary Order by Application, Field_Name





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


Create PROCEDURE [R_DataDictionary_French]
AS
SELECT cast(AppID as varchar(50)) as Application, Header_CIHI_French as Field_Name, cast(DataType as VarChar(50)) as Data_Type, FieldSize  as Size, SortOrder, Fieldid
Into #DataDictionary
FROM dbo.U_UsersFields WHERE (UserID = 1) AND (DataType <> 100000) and appid < 500

Update #DataDictionary set Data_Type = 'Alpha-Numérique' where data_type in ('2', '6', '7', '19', '20')
Update #DataDictionary set Data_Type = 'Commentaire' where data_type in ('98')
Update #DataDictionary set Data_Type = 'Devise' where data_type = '3'
Update #DataDictionary set Data_Type = 'Numérique' where data_type in ('0', '4', '8', '10')
Update #DataDictionary set Data_Type = 'Alpha' where data_type in ('1', '5', '9')
Update #DataDictionary set Data_Type = 'Date-Temps' where data_type in ('11', '12', '15', '16', '17')
Update #DataDictionary set Data_Type = 'Lookup' where data_type in ('42', '21', '22', '23', '25', '30', '35', '36', '37', '38', '39', '40', '41', '
42', '43', '44', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '70', '99', '100', '101', '102','26')
Update #DataDictionary set Data_Type = 'Devise' where data_type = '3'
--Do these two updates last
Update #DataDictionary set Data_Type = 'EN-TÊTE', Size = 0 where fieldid between 200 and 399
Update #DataDictionary set Application = left(ModuleName, 50)
FROM         dbo.U_AppIDs RIGHT OUTER JOIN
                      dbo.#DataDictionary ON dbo.U_AppIDs.AppID = dbo.#DataDictionary.Application

select Application, Field_Name, Data_Type, Size, SortOrder from #DataDictionary Order by Application, Field_Name


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO







CREATE   PROCEDURE [R_DefSlip]
	@SlipID as int
AS
SELECT     dbo.AB_Abstract.AdmitDate, dbo.AB_Abstract.AdmitTime, dbo.Def_SlipMain.DefBirthDate AS BirthDate, dbo.Def_SlipMain.DefPatientID AS ChartNumber,
                       Lookup1.DisplayCode AS ColourCode, Lookup1.UserDescription AS ColourCodeDesc, Lookup2.DisplayCode AS CompletedBy, 
                      Lookup2.UserDescription AS CompletedByDesc, Lookup3.DisplayCode AS DeficiencyCode, Lookup3.UserDescription AS DeficiencyCodeDesc, 
                      Lookup4.DisplayCode AS DeficiencyCodeType, Lookup4.UserDescription AS DeficiencyCodeTypeDesc, dbo.Def_SlipMain.DefDays AS DeficiencyDays, 
                      dbo.Def_Activity.DefDays AS DeficiencyDetailDays, dbo.Def_Activity.DefEndDate AS DeficiencyDetailEndDate, 
                      dbo.Def_Activity.DefStartDate AS DeficiencyDetailStartDate, dbo.Def_SlipMain.DefEndDate AS DeficiencyEndDate, 
                      dbo.Def_Activity.JobNumber AS DeficiencyJobNumber,
                      dbo.Def_Activity.DefOccurrence AS DeficiencyOccurrence, dbo.Def_SlipMain.DefStartDate AS DeficiencyStartDate, 
                      dbo.Def_Activity.DefNote AS DetailComments, dbo.Def_Activity.DefeciencyID AS DetailReferenceIDNumber, Lookup5.DisplayCode AS DetailStatus, 
                      Lookup5.UserDescription AS DetailStatusDesc, dbo.AB_Abstract.DischargeDate, dbo.AB_Abstract.DischargeTime, dbo.AB_Abstract.EncounterNumber, 
                      dbo.AB_Abstract.EncounterSequence, dbo.Def_SlipMain.DefMainNote AS HeaderNotes, dbo.Def_SlipMain.DefeciencyID AS HeaderReferenceIDNumber, 
                      Lookup6.DisplayCode AS HeaderStatus, Lookup6.UserDescription AS HeaderStatusDesc, dbo.Def_SlipMain.DefHoldDays AS HoldDays, 
                      dbo.Def_SlipMain.DefHoldEndDate AS HoldEndDate, dbo.Def_SlipMain.DefHoldStartDate AS HoldStartDate, 
                      Lookup7.DisplayCode AS InstitutionNumber, Lookup7.UserDescription AS InstitutionNumberDesc, dbo.Def_SlipMain.DefManualDays AS ManualDays, 
                      Lookup8.DisplayCode AS MessageBox, Lookup8.UserDescription AS MessageBoxDesc, dbo.Def_SlipMain.DefPatFirstName AS PatientFirstName, 
                      dbo.Def_SlipMain.DefPatLastName AS PatientLastName, Lookup9.DisplayCode AS ProviderNumber, 
                      Lookup9.UserDescription AS ProviderNumberDesc, dbo.Def_SlipMain.DefDrStatus AS ProviderStatus, Lookup10.DisplayCode AS Resident, 
                      Lookup10.UserDescription AS ResidentDesc, Lookup11.DisplayCode AS SiteNumber, Lookup11.UserDescription AS SiteNumberDesc, 
                      Lookup11.DefaultDescription AS SiteNumberDesc_D, dbo.Def_SlipMain.DefSuspensionDays AS SuspensionDays, 
                      dbo.Def_SlipMain.DefVacationDays AS VacationDays, dbo.CM_CPI_Volume.VolumeNumber
FROM         dbo.Def_SlipMain LEFT OUTER JOIN
                      dbo.AB_Main ON dbo.Def_SlipMain.DefAbstractID = dbo.AB_Main.UniversalID LEFT OUTER JOIN
                      dbo.AB_Abstract ON dbo.AB_Main.AbstractID = dbo.AB_Abstract.AbstractID LEFT OUTER JOIN
                      dbo.CM_CPI_Volume ON dbo.Def_SlipMain.DefVolumeID = dbo.CM_CPI_Volume.VolumeID LEFT OUTER JOIN
                      dbo.Def_Activity ON dbo.Def_SlipMain.DefeciencyID = dbo.Def_Activity.HeaderDefID LEFT OUTER JOIN
                      dbo.U_Users Lookup2 ON dbo.Def_Activity.DefCompletedBy = Lookup2.Code LEFT OUTER JOIN
                      dbo.DefLU_DeficiencyCode Lookup3 ON dbo.Def_Activity.DefCode = Lookup3.Code LEFT OUTER JOIN
                      dbo.DefLU_DeficiencyType Lookup4 ON dbo.Def_Activity.DefCodeType = Lookup4.Code LEFT OUTER JOIN
                      dbo.DefLU_ChartStatus Lookup5 ON dbo.Def_Activity.DefStatus = Lookup5.Code LEFT OUTER JOIN
                      dbo.DefLU_Messages Lookup8 ON dbo.Def_Activity.DefMessage = Lookup8.Code LEFT OUTER JOIN
                      dbo.DefLU_Resident Lookup10 ON dbo.Def_Activity.DefResident = Lookup10.Code LEFT OUTER JOIN
                      dbo.DefLU_DocColourCode Lookup1 ON dbo.Def_SlipMain.DefColour = Lookup1.Code LEFT OUTER JOIN
                      dbo.DefLU_ChartStatus Lookup6 ON dbo.Def_SlipMain.DefMainStatus = Lookup6.Code LEFT OUTER JOIN
                      dbo.H_InstitutionProfile Lookup7 ON dbo.Def_SlipMain.DefInstNumber = Lookup7.Code LEFT OUTER JOIN
                      dbo.LU_Provider Lookup9 ON dbo.Def_SlipMain.DefDrNumber = Lookup9.Code LEFT OUTER JOIN
                      dbo.LU_Site Lookup11 ON dbo.Def_SlipMain.DefSiteNumber = Lookup11.Code
WHERE     (dbo.Def_SlipMain.DefeciencyID = @SlipID)






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [R_HSMR_Report]
	@YearFrom int,	@YearTo int, @PeriodFrom int, @PeriodTo int, 
	@InstitutionNumber varchar(12),	@Option varchar(100) = '',
	@Option2 varchar(50) = ''
as
	declare @Group1 varchar(50)
	declare @sql varchar(3000)	
	declare @StartDate varchar(20), @EndDate varchar(20)

	--declare @Option2 varchar(50)
	--declare @i int
	--set @i = charindex('|', @Option) 
	--if @i > 0
	--begin
	--	set @Option2 = isnull(substring(@Option, @i + 1, 50), '')
	--	set @Option = isnull(substring(@Option, 0, @i -1), '')
	--end
	--else
	--	set @Option2 = ''
		
	if @YearFrom < @YearTo
	begin
		set @Group1 = 'BatchYear'
		set @StartDate = cast(@YearFrom as varchar(10)) + '/04/01'
		set @EndDate = cast(@YearTo + 1 as varchar(10)) + '/03/31'
	end
	else
	begin
		set @Group1 = 'BatchPeriod'
		set @StartDate = cast(@YearFrom as varchar(10)) + '/04/01'
		set @EndDate = cast(@YearFrom + 1 as varchar(10)) + '/03/31'
	end

	set @sql = 'select 
		Group1 = ' + (case when @YearFrom < @YearTo then 'BatchYear'
						   else (case when @PeriodFrom = 1 then '(BatchPeriod - 1) / 3 + 1' else 'BatchPeriod' end) end) + ',
		Group2 = ' + (case when isnull(@Option, '') = '' then '''''' else @Option end) + ',
		BatchYear,
        BatchPeriod = ' + (case when @PeriodFrom = 1 then '(BatchPeriod - 1) / 3 + 1' else 'BatchPeriod' end) + ',
        InstitutionNumber,
        InstitutionNumberDesc,
		AgeNumber,
		AgeGroup,
		Gender,
		LOSDays,
		LOSGroup,
		AdmissionCategory,
		DiagnosisGroup,
		CharlsonIndex,
		Transfers = Transferred,
		Death = (case when DeathFlag in (''Y'', ''1'') then 1 else 0 end),
		ExpectedDeath = ExpectedDeath' + (case when len(@Option2) > 0 then '_' + @Option2 else '' end) + '
		from dbo.HSMR_Main
		where InstitutionNumber = ''' + @InstitutionNumber + ''' and 
			DischargeDate between ''' + @StartDate + ''' and ''' + @EndDate + ''' 
			and	IsNeonate = ''N'' and Gender in (''M'', ''F'') and AdmissionCategory in (''U'', ''L'')
			and AgeNumber < = 120 and LOSDays <= 365
			and PostalCode not in (''US'', ''OC'', ''AL'', ''AK'', ''AZ'', ''AR'', ''CA'', ''CO'', 
				''CT'', ''DE'', ''DC'', ''FL'', ''GA'', ''HI'', ''ID'', ''IL'', 
				''IN'', ''IA'', ''KS'', ''KY'', ''LA'', ''ME'', ''MD'', 
				''MA'', ''MI'', ''MN'', ''MS'', ''MO'', ''MT'', ''NE'', ''NV'', 
				''NH'', ''NJ'', ''NM'', ''NY'', ''NC'', ''ND'', ''OH'', ''OK'', 
				''OR'', ''PA'', ''RI'', ''SC'', ''SD'', ''TN'', ''TX'', ''UT'', 
				''VT'', ''VA'', ''WA'', ''WV'', ''WI'', ''WY'') and isnumeric(PostalCode) = 0
			and DiagFlagCaseMark = ''Y'' 
			and DiagnosisCode_01 not in (''G9381'', ''Z515'') ' +
			(case when @Option2 = 'ICU' then ' and ICU = ''Y'' '
				  when @Option2 = 'Medical' then ' and MedicalSurgicalProgram = ''M'' '	
				  when @Option2 = 'Surgical' then ' and MedicalSurgicalProgram = ''S'' '	
				  when @Option2 = 'NoTransfer' then ' and Transferred = ''N'' '	
				  else ''
			 end)

	--print @sql
	exec (@sql)
			
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--PR - 00521 some lookup tables have link
--Add a new column: AssociationLink
CREATE PROCEDURE [R_LookupDetail]
	@LUTable as VarChar(50) = ''
AS 

	Declare @SQL as nVarChar(2000)
	Declare @DataType as VarChar(3)
	If isnumeric(@LUTable) = 1
		Select @SQL = 'SELECT dbo.LU_CodeFile.DisplayCode, dbo.LU_CodeFile.UserDescription, dbo.LU_CodeFile.DefaultDescription, dbo.LU_CodeFile.CIHIValue, 
						CAST(dbo.LU_CodeFile.ValidFrom AS datetime) AS ValidFrom, CAST(dbo.LU_CodeFile.ValidTo AS datetime) AS ValidTo, dbo.LU_CodeFile.InterfaceIn, 
						dbo.H_HospitalProfile.UserDescription AS HospitalLink, dbo.LU_CodeFile.LUText AS LookupText,
                        '''' as AssociationLink
						FROM  dbo.LU_CodeFile LEFT OUTER JOIN
						dbo.H_HospitalProfile ON dbo.LU_CodeFile.HospitalID = dbo.H_HospitalProfile.Code where lookupid = ' + @LUTable
	Else
	Begin
		Set @SQL = 'select @DataType = datatype from u_usersfields where appid = 1100 and userid = 1 and lookuptable = ''' +  @LUTable + ''''
		exec sp_executesql @sql, N'@DataType VarChar(3) output', @DataType output

--Ticket PR-00589
		if not exists (select column_name from information_Schema.columns where table_name = @LUTable and column_name = 'defaultdescription')
			Select @SQL = 'SELECT dbo.' + @LUTable + '.DisplayCode, dbo.' + @LUTable + '.UserDescription, '''' as DefaultDescription, '''' as CIHIValue, 
			dbo.' + @LUTable + '.ValidFrom, dbo.' + @LUTable + '.ValidTo, dbo.' + @LUTable + '.InterfaceIn, dbo.H_HospitalProfile.UserDescription AS HospitalLink, 
			dbo.' + @LUTable + '.LUText AS Lookuptext, '''' as AssociationLink FROM dbo.' + @LUTable + ' LEFT OUTER JOIN
			dbo.H_HospitalProfile ON dbo.' + @LUTable + '.HospitalID = dbo.H_HospitalProfile.Code'
		else if not exists (select column_name from information_Schema.columns where table_name = @LUTable and column_name = 'cihivalue')
			Select @SQL = 'SELECT dbo.' + @LUTable + '.DisplayCode, dbo.' + @LUTable + '.UserDescription, dbo.' + @LUTable + '.DefaultDescription, '''' as CIHIValue, 
			dbo.' + @LUTable + '.ValidFrom, dbo.' + @LUTable + '.ValidTo, dbo.' + @LUTable + '.InterfaceIn, dbo.H_HospitalProfile.UserDescription AS HospitalLink, 
			dbo.' + @LUTable + '.LUText AS Lookuptext, '''' as AssociationLink FROM dbo.' + @LUTable + ' LEFT OUTER JOIN
			dbo.H_HospitalProfile ON dbo.' + @LUTable + '.HospitalID = dbo.H_HospitalProfile.Code'
		Else If @DataType in ('44', '43')
			Select @SQL = 'SELECT dbo.' + @LUTable + '.DisplayCode, dbo.' + @LUTable + '.UserDescription, dbo.' + @LUTable + '.UserDescription as DefaultDescription, dbo.' + @LUTable + '.CIHIValue, 
			dbo.' + @LUTable + '.ValidFrom, dbo.' + @LUTable + '.ValidTo, dbo.' + @LUTable + '.InterfaceIn, dbo.H_HospitalProfile.UserDescription AS HospitalLink, 
			dbo.' + @LUTable + '.LUText AS Lookuptext, '''' as AssociationLink FROM dbo.' + @LUTable + ' LEFT OUTER JOIN
			dbo.H_HospitalProfile ON dbo.' + @LUTable + '.HospitalID = dbo.H_HospitalProfile.Code'
		Else If @LUTable in ('DefLU_ChartStatus')
			Select @SQL = 'SELECT dbo.' + @LUTable + '.DisplayCode, dbo.' + @LUTable + '.UserDescription, dbo.' + @LUTable + '.UserDescription as DefaultDescription, dbo.' + @LUTable + '.CIHIValue, 
			dbo.' + @LUTable + '.ValidFrom, dbo.' + @LUTable + '.ValidTo, dbo.' + @LUTable + '.InterfaceIn, dbo.H_HospitalProfile.UserDescription AS HospitalLink, 
			dbo.' + @LUTable + '.LUText AS Lookuptext, '''' as AssociationLink FROM dbo.' + @LUTable + ' LEFT OUTER JOIN
			dbo.H_HospitalProfile ON dbo.' + @LUTable + '.HospitalID = dbo.H_HospitalProfile.Code'
--PR-00521
		Else If @LUTable like 'LU_Ancillary%'
			Select @SQL = 'SELECT dbo.' + @LUTable + '.DisplayCode, dbo.' + @LUTable + '.UserDescription, dbo.' + @LUTable + '.UserDescription as DefaultDescription, dbo.' + @LUTable + '.CIHIValue, 
			dbo.' + @LUTable + '.ValidFrom, dbo.' + @LUTable + '.ValidTo, dbo.' + @LUTable + '.InterfaceIn, dbo.H_HospitalProfile.UserDescription AS HospitalLink, 
			dbo.' + @LUTable + '.LUText AS Lookuptext, 
            (select top 1 DisplayCode from LU_CareType where LU_CareType.code = ' + @LUTable + '. AssociationID ) as AssociationLink FROM dbo.' + @LUTable + ' LEFT OUTER JOIN
			dbo.H_HospitalProfile ON dbo.' + @LUTable + '.HospitalID = dbo.H_HospitalProfile.Code'
--PR-00521
		Else If @LUTable like 'LU_BasicOption%'
			Select @SQL = 'SELECT dbo.' + @LUTable + '.DisplayCode, dbo.' + @LUTable + '.UserDescription, dbo.' + @LUTable + '.UserDescription as DefaultDescription, dbo.' + @LUTable + '.CIHIValue, 
			dbo.' + @LUTable + '.ValidFrom, dbo.' + @LUTable + '.ValidTo, dbo.' + @LUTable + '.InterfaceIn, dbo.H_HospitalProfile.UserDescription AS HospitalLink, 
			dbo.' + @LUTable + '.LUText AS Lookuptext, 
            (select top 1 DisplayCode from H_InstitutionProfile where H_InstitutionProfile.code = ' + @LUTable + '. AssociationID ) as AssociationLink FROM dbo.' + @LUTable + ' LEFT OUTER JOIN
			dbo.H_HospitalProfile ON dbo.' + @LUTable + '.HospitalID = dbo.H_HospitalProfile.Code'
--PR-00521
		Else If @LUTable like 'LU_ProjectQuestion%'
			Select @SQL = 'SELECT dbo.' + @LUTable + '.DisplayCode, dbo.' + @LUTable + '.UserDescription, dbo.' + @LUTable + '.UserDescription as DefaultDescription, dbo.' + @LUTable + '.CIHIValue, 
			dbo.' + @LUTable + '.ValidFrom, dbo.' + @LUTable + '.ValidTo, dbo.' + @LUTable + '.InterfaceIn, dbo.H_HospitalProfile.UserDescription AS HospitalLink, 
			dbo.' + @LUTable + '.LUText AS Lookuptext, 
            (select top 1 DisplayCode from LU_Project where LU_Project.code = ' + @LUTable + '. AssociationID ) as AssociationLink FROM dbo.' + @LUTable + ' LEFT OUTER JOIN
			dbo.H_HospitalProfile ON dbo.' + @LUTable + '.HospitalID = dbo.H_HospitalProfile.Code'

		Else
			Select @SQL = 'SELECT dbo.' + @LUTable + '.DisplayCode, dbo.' + @LUTable + '.UserDescription, dbo.' + @LUTable + '.DefaultDescription, dbo.' + @LUTable + '.CIHIValue, 
			dbo.' + @LUTable + '.ValidFrom, dbo.' + @LUTable + '.ValidTo, dbo.' + @LUTable + '.InterfaceIn, dbo.H_HospitalProfile.UserDescription AS HospitalLink, 
			dbo.' + @LUTable + '.LUText AS Lookuptext, '''' as AssociationLink FROM dbo.' + @LUTable + ' LEFT OUTER JOIN
			dbo.H_HospitalProfile ON dbo.' + @LUTable + '.HospitalID = dbo.H_HospitalProfile.Code'
	End

	Exec(@SQL)

	Return 0

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ED - 01518
-- @Module: DAD, NACRS, Rehab, OMHRS, CCRS, CCM, CPI, Volumne, ROI,
CREATE  Procedure [R_LookupDetailByApplication]
    @RoleID int = null, @Module varchar(250) = null
as

set nocount on
declare @sql varchar(4000), @AppID int, @len int
declare @table varchar(100)
--declare @roleID int

if isnull(@RoleID, 0) < 1 set @RoleID = 1
--set @roleID = (select top 1 roleId from u_users where code = @RoleID)
--if isnull(@roleID, 0) = 0 set @RoleID = @RoleID
if not exists (select top 1 roleid from u_usersfields where userid = @roleid)
    set @RoleID = 1

Create table #AppIDs(
    AppID int,
    AppDesc varchar(250) COLLATE Latin1_General_CI_AS NULL
)

insert into #AppIDs(AppID, AppDesc) values(0, 'Central Patient Index')
insert into #AppIDs(AppID, AppDesc) values(1, 'CPI Volume')
insert into #AppIDs(AppID, AppDesc) values(3, 'Non Abstracted')
insert into #AppIDs(AppID, AppDesc) values(10, 'Chart Pull List')
insert into #AppIDs(AppID, AppDesc) values(11, 'Chart Locator')
insert into #AppIDs(AppID, AppDesc) values(15, 'Chart Deficiency')
insert into #AppIDs(AppID, AppDesc) values(20, 'Transcription')
insert into #AppIDs(AppID, AppDesc) values(30, 'Release of Information')
insert into #AppIDs(AppID, AppDesc) values(101, 'Abscare Inpatient ICD 9/CM')
insert into #AppIDs(AppID, AppDesc) values(102, 'Same Day Surgery ICD 9/CM')
insert into #AppIDs(AppID, AppDesc) values(201, 'Abscare Inpatient ICD 10')
insert into #AppIDs(AppID, AppDesc) values(202, 'Same Day Surgery ICD 10')
insert into #AppIDs(AppID, AppDesc) values(250, 'Rehab')
insert into #AppIDs(AppID, AppDesc) values(301, 'Ambulatory Care ICD 9/CM')
insert into #AppIDs(AppID, AppDesc) values(401, 'Ambulatory Care ICD 10')
insert into #AppIDs(AppID, AppDesc) values(470, 'MDS 2.0')
insert into #AppIDs(AppID, AppDesc) values(500, 'Scheduler')
insert into #AppIDs(AppID, AppDesc) values(550, 'Care Map')
insert into #AppIDs(AppID, AppDesc) values(600, 'Report Generator')
insert into #AppIDs(AppID, AppDesc) values(650, 'OMHRS')
insert into #AppIDs(AppID, AppDesc) values(675, 'CCM')
insert into #AppIDs(AppID, AppDesc) values(40000, 'CJRR Knee')
insert into #AppIDs(AppID, AppDesc) values(40001, 'CJRR Hip')

insert into #AppIDs(AppID, AppDesc) values(1000, 'Hospital Profile')
insert into #AppIDs(AppID, AppDesc) values(1001, 'Institution Profile')
insert into #AppIDs(AppID, AppDesc) values(1002, 'User Profile')
insert into #AppIDs(AppID, AppDesc) values(1003, 'Regional Profile')

if isnull(@Module, '') <> ''
    delete from #AppIDs where AppDesc <> @Module

-- select * from #AppIDs

create table #TempUserFields(
    FieldID int,
    AppID   int,
    FieldSize int,
    LookUpTable varchar(250) COLLATE Latin1_General_CI_AS NULL,
    FieldDesc varchar(4000) COLLATE Latin1_General_CI_AS NULL
)
insert into  #TempUserFields(FieldID, AppID, FieldSize, LookUpTable)
select distinct FieldID, 
AppID = (case when AppID between 250 and 253 then 250
              when AppID between 470 and 479 then 470
              when AppID between 650 and 659 then 650
              when AppID between 675 and 679 then 675
              else appid end), 
FieldSize, LookUpTable
from u_usersfields
where UserID = @roleID and isnull(LookupTable, '') <> ''
    and (case when AppID between 250 and 253 then 250
              when AppID between 470 and 479 then 470
              when AppID between 650 and 659 then 650
              when AppID between 675 and 679 then 675
              else appid end) in (select appid from #AppIDs)
    and LookUpTable not in ('LU_AppIDs', 'LU_Provider', 'LU_IntervAttExtent', 
        'LU_IntervAttLocation', 'LU_IntervAttStatus', '4', 'LU_CareType', 
        'LU_AbstractStatus', 'LU_CIHICorrect', 'LU_DeleteStatus')
    and ((LookUpTable = 'H_HospitalProfile' and AppID = 1000) or 
         (LookUpTable = 'H_InstitutionProfile' and AppID = 1001) or
         (LookUpTable = 'H_RegionProfile' and AppID = 1003) or
         (LookUpTable = 'U_Users' and AppID = 1002) or  
         LookUpTable not in ('H_HospitalProfile', 'H_InstitutionProfile', 'H_RegionProfile',  'U_Users'))


Update #TempUserFields
set LookUpTable = 'LU_ProviderService'
where LookUpTable = 'LLU_ProviderServices'

Update #TempUserFields
set LookUpTable = 'LU_ProviderSpecialty'
where LookUpTable = 'LLU_ProviderSpecialty'
 
Update #TempUserFields
set FieldDesc = Header_User
from #TempUserFields z
    inner join u_usersfields uf on z.fieldID = uf.fieldid and uf.UserID = @RoleID
            and (uf.AppID  = z.AppID
            or (z.AppID = 250 and uf.AppID between 250 and 253)
            or (z.AppID = 470 and uf.AppID between 470 and 479)
            or (z.AppID = 650 and uf.AppID between 650 and 659)
            or (z.AppID = 675 and uf.AppID between 675 and 679))
where isnull(Header_User, '') <> ''

--merge multi field with same lookuptable into one record
declare @old_appid int, @old_lookUptable varchar(100), @old_len int
declare @new_fielddesc varchar(4000), @fielddesc varchar(4000)

--select z.AppID, z.FieldSize, z.LookUpTable, z.FieldDesc
--from #TempUserFields z
--    inner join (select AppID, FieldSize, LookUpTable from #TempUserFields group by AppID, FieldSize, LookUpTable having count(*) > 1) d
--        on z.AppID = d.AppID and z.LookUpTable = d.LookUpTable and z.FieldSize = d.FieldSize
--order by z.AppID, z.LookUpTable, z.FieldSize

declare z_dupLookUpTable cursor READ_ONLY for
    select z.AppID, z.FieldSize, z.LookUpTable, z.FieldDesc
    from #TempUserFields z
        inner join (select AppID, FieldSize, LookUpTable from #TempUserFields group by AppID, FieldSize, LookUpTable having count(*) > 1) d
            on z.AppID = d.AppID and z.LookUpTable = d.LookUpTable and z.FieldSize = d.FieldSize
    order by z.AppID, z.LookUpTable, z.FieldSize

open z_duplookuptable
set @old_appid = -1
set @old_lookuptable = ''
set @old_len = -1
fetch next from z_duplookuptable into @appid, @len, @table, @fielddesc
while(@@fetch_status = 0)
begin
    if @appid <> @old_appid or @old_lookuptable <> @table or @len <> @old_len
    begin
        if @old_appid <> -1 and @old_lookuptable <> '' and @old_len <> -1
        begin
            delete from #TempUserFields where appid = @old_appid and lookuptable = @old_lookuptable and FieldSize = @old_len
            --print @new_fielddesc
            insert into  #TempUserFields(Appid, FieldSize, LookUpTable, FieldDesc)
            values(@old_Appid, @old_len, @old_lookupTable, @new_fielddesc)
        end
        set @old_appid = @appid
        set @old_lookuptable = @table
        set @old_len = @len
        set @new_fielddesc = @fielddesc
    end
    else
        set @new_fielddesc = @new_fielddesc + ', ' + @fielddesc

    fetch next from z_duplookuptable into @appid, @len, @table, @fielddesc
end
close z_duplookuptable
deallocate z_duplookuptable
if(@old_appid > 0)
begin
    delete from #TempUserFields where appid = @old_appid and lookuptable = @old_lookuptable and FieldSize = @old_len
    insert into  #TempUserFields(Appid, FieldSize, LookUpTable, FieldDesc)
    values(@old_Appid, @old_len, @old_lookupTable, @new_fielddesc)
end

--End merge
create table #TempLookUps(
    LookUpTable varchar(250) COLLATE Latin1_General_CI_AS NULL,
    DisplayCode varchar(50) COLLATE Latin1_General_CI_AS NULL,
    UserDescription varchar(500) COLLATE Latin1_General_CI_AS NULL,
    CIHIValue  varchar(50) COLLATE Latin1_General_CI_AS NULL,
    ValidFrom  datetime,
    ValidTo    datetime,
    InterfaceIn varchar(50) COLLATE Latin1_General_CI_AS NULL,
    AssociationDesc varchar(500) COLLATE Latin1_General_CI_AS NULL,
    AssociationID int,
	HospitalID int
)

insert into #TempLookUps(LookUpTable, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo, InterfaceIn, AssociationID, HospitalID)
select distinct z.LookUpTable, c.DisplayCode, c.UserDescription, c.CIHIValue, c.ValidFrom, c.ValidTo, c.InterfaceIn, 0, c.HospitalID
from #TempUserFields z 
    inner join lu_codefile c on z.lookuptable = cast(c.lookupid as varchar(10))


declare z_lookups cursor for
    select distinct lookuptable from #TempUserFields where isnumeric(lookuptable) = 0
open z_lookups
fetch next from z_lookups into @table
while(@@fetch_status = 0)
begin
    set @sql = 'select ''' + @table + ''', DisplayCode, UserDescription, CIHIValue = ' + 
        (case when @table like 'LoanLU%' or @table like 'DefLU%' or @table like 'LU_ROI%' or @table like 'LU_UserDefined%' then '''''' else 'CIHIValue' end) +  
        ', ValidFrom, ValidTo, InterfaceIn = ' + (case when @table in ('LU_OhipFeeCodes', 'LU_ROI_TaxType') then 'null' else 'InterfaceIn' end) + ', AssociationID = ' + 
        (case when @Table like 'LU_BasicOption%' or @Table like 'LU_Ancillary%' or @table like 'LU_ProjectQuestion%' then 'AssociationID'
              else 'null' end) +  
        ', HospitalID from ' + @table
    --print @sql
    insert into #TempLookUps(LookUpTable, DisplayCode, UserDescription, CIHIValue, ValidFrom, ValidTo, InterfaceIn, AssociationID, HospitalID)
    exec (@sql)
    fetch next from z_lookups into @table
end
close z_lookups
deallocate z_lookups

Update #TempLookUps
set AssociationDesc = h.DisplayCode
from #TempLookUps z
    inner join H_InstitutionProfile h on z.AssociationID = h.code
where LookUpTable like 'LU_BasicOption%' 

Update #TempLookUps
set AssociationDesc = (select top 1 DisplayCode from lu_caretype h where h.code = AssociationID)
where LookUpTable like 'LU_Ancillary%' 

Update #TempLookUps
set AssociationDesc = (select top 1 DisplayCode from lu_project h where h.code = AssociationID)
where LookUpTable like 'LU_ProjectQuestion%' 

select 
    Module = a.AppDesc,
    z.FieldDesc,  
    z.FieldSize,
    LookUpTable = (case when uf.Header_User is null 
                        then (case when z.LookUptable like 'lu_basicoption%' or z.LookUptable like 'lu_projectquestion%' then z.FieldDesc 
                                   when z.LookUptable = 'lu_yesNoSystem' then 'Yes/No(1/0)'
                                   when z.LookUptable = 'LU_YesBlank' then 'Yes/No(1/blank)'
                                   when z.LookUptable = 'LU_YesBlankAlpha' then 'Yes/No(Y/blank)'
                                   when z.LookUptable = 'LU_YesNoAlpha' then 'Yes/No(Y/N)'
                                   when z.LookUptable = 'LU_YesNoNumeric' then 'Yes/No(1/2)'
                                   when z.LookUptable = 'LU_AbstractStatus' then 'Abstract Status'
                                   when z.LookUptable = 'LU_CIHICorrect' then 'CIHI Correction Flag'
                                   when z.LookUptable = 'LU_DeleteStatus' then 'Deletion Flag'
                                   when z.LookUptable = 'LU_InjuryActivity' then 'Injury Activity'
                                   when z.LookUptable = 'LoanLU_Type' then 'Transaction Type'
                                   when z.LookUptable = 'LU_OhipFeeCodes' then 'Ohip Fee Codes'
                                   when z.LookUptable = 'LU_FamilyPhysician' then 'Family Physician'
                                   when z.LookUptable = 'LU_CC_Morphology_O2' then 'Morphology Code - O2'
                                   when z.LookUptable = 'LU_CC_Morphology_O3' then 'Morphology Code - O3'
                                   when z.LookUptable = 'LU_CC_Topography' then 'Topography Code'
                                   when z.LookUptable = 'LoanLU_PullFormat' then 'Pull List ID Format'
                                   when z.LookUptable = 'LU_FieldState' then 'Field State'
                                   when z.LookUptable = 'LU_UseMentalHealth' then 'Data Collect'
                                   when z.LookUptable = 'LU_Permission' then 'Permission'
                                   when z.LookUptable = 'LU_FontSize' then 'Font Size'
                                   when z.LookUptable = 'LU_SystemLanguage' then 'System Language'
                                   when z.LookUptable = 'LU_PermitAccess' then 'Permission Access'
                                   when z.LookUptable = 'LU_PermitAccess_MDAS' then 'MDAS Permission Access'
                                   when z.LookUptable = 'LU_Permission_MDAS' then 'MDAS Permission'

                                   when z.LookUptable = '1' then 'Yes(1 only)'
                                   when z.LookUptable = '6' then 'Date Format'
                                   when z.LookUptable = '7' then 'Amcare Type'
                                   when z.LookUptable = '74' then 'Sensitivity Level'
                                   when z.LookUptable = '81' then 'Report Audit Level'
                                   when z.LookUptable = '82' then 'WinRecs ~ 3-M CodeFinder Phase'
                                   when z.LookUptable = '83' then 'Volume List Sort Field'
                                   when z.LookUptable = '500' then 'Record type'
                                   when z.LookUptable = '566' then 'Self-Injury - Attempts'
                                   when z.LookUptable = '567' then 'Self-Injury - Intent'
                                   when z.LookUptable = '568' then 'Self-Injury - Considered'
                                   when z.LookUptable = '569' then 'Self-Injury - Others concerned'
                                   when z.LookUptable = '571' then 'Cognitive Decline'
                                   when z.LookUptable = '1001' then 'Staging Version'
                                   when z.LookUptable = '1002' then 'Laterality'
                                   when z.LookUptable = '1003' then 'CC/Visit Program Code'
                                   when z.LookUptable = '1005' then 'Morphology Code Version'
                                   when z.LookUptable = '1006' then 'HCP Status'
                                   when z.LookUptable = '25027' then 'Yes/No(1/0)'
                                   when z.LookUptable = '25032' then 'Serivce Interuption Reason/Diagnostic Condition Code'
                                   when z.LookUptable = '45108' then 'Pharmacy'
                                   when z.LookUptable = '45111' then 'Payment Program'
                                   when z.LookUptable = '45112' then 'Payee'
                                   when z.LookUptable = '45113' then 'Billing Action'
                                   when z.LookUptable = '45117' then 'Billing Item Tax Type'
                                   when z.LookUptable = '47001' then 'Reason For Assessment'
                                   when z.LookUptable = '47002' then 'Facility/level of care'
                                   when z.LookUptable = '47004' then 'Education (highest completed)'
                                   when z.LookUptable = '47008' then 'Route of Administration'
                                   when z.LookUptable = '47009' then 'Frequency'
                                   when z.LookUptable = '47010' then 'Language'
                                   when z.LookUptable = '47015' then 'Cognitive skills/daily decision making'
                                   when z.LookUptable = '47016' then 'Indicators of Delirium/Periodic Disordered Thinking/Awareness'
                                   when z.LookUptable = '47017' then 'Change in cognitive status'
                                   when z.LookUptable = '47018' then 'Hearing'
                                   when z.LookUptable = '47019' then 'Making self understood'
                                   when z.LookUptable = '47020' then 'Speech clarity'
                                   when z.LookUptable = '47021' then 'Ability to understand others'
                                   when z.LookUptable = '47022' then 'Change in communication/hearing'
                                   when z.LookUptable = '47023' then 'Vision'
                                   when z.LookUptable = '47024' then 'Indicators of Depression, Anxiety, Sad Mood'
                                   when z.LookUptable = '47025' then 'Mood persistence'
                                   when z.LookUptable = '47026' then 'Change in mood'
                                   when z.LookUptable = '47027' then 'Behavioural Symptoms Frequency'
                                   when z.LookUptable = '47028' then 'Behavioural Symptoms Alterability'
                                   when z.LookUptable = '47029' then 'Change in behavioural symptoms'
                                   when z.LookUptable = '47032' then 'Bathing Self-Performance'
                                   when z.LookUptable = '47033' then 'Test for Balance'
                                   when z.LookUptable = '47034' then 'Functional Limitation in Range of Motion'
                                   when z.LookUptable = '47035' then 'Functional Limitation in Range of Motion (Voluntary Movement)'
                                   when z.LookUptable = '47036' then 'Change in ADL function'
                                   when z.LookUptable = '47037' then 'Continence in Last 14 Days'
                                   when z.LookUptable = '47038' then 'Change in urinary continence'
                                   when z.LookUptable = '47040' then 'Parenteral or enteral intake-Proportion of total calories'
                                   when z.LookUptable = '47041' then 'Pain symptoms intensity'
                                   when z.LookUptable = '47043' then 'Average time involved in activities'
                                   when z.LookUptable = '47044' then 'Prefers Change in Daily Routine'
                                   when z.LookUptable = '47045' then 'Devices and Restraints'
                                   when z.LookUptable = '47046' then 'Stay projected to be of short duration'
                                   when z.LookUptable = '47047' then 'Overall change in care needs'
                                   when z.LookUptable = '47048' then 'Participation in Assessment'
                                   when z.LookUptable = '47060' then 'ADL Self-Performance'
                                   when z.LookUptable = '47061' then 'ADL Support Provided'
                                   when z.LookUptable = '47069' then 'Pain symptoms frequency'
                                   when z.LookUptable = '47076' then 'Data Record Type'
                                   when z.LookUptable = '47077' then 'Gender'
                                   when z.LookUptable = '47079' then 'Marital Status'
                                   when z.LookUptable = '47080' then 'Yes/No/Unknown(0/1/9)'
                                   when z.LookUptable = '47081' then 'Pain Site'
                                   when z.LookUptable = '47082' then 'Batch Period'
                                   when z.LookUptable = '47084' then 'Past Roles'
                                   when z.LookUptable = '47085' then 'Stage of pressure ulcer'
                                   when z.LookUptable = '47086' then 'Stage of stasis ulcer'    --(CIHI 47085 and 47086 are same)
                                   when z.LookUptable = '47087' then 'Memory'
                                   when z.LookUptable = '47088' then 'Parenteral or enteral intake-Average fluid intake per day'
                                   when z.LookUptable = '50003' then 'Status'
                                   when z.LookUptable = '51011' then 'Method/Basis of Diagnosis'
                                   else '' end)
                        else uf.Header_User end),
    l.DisplayCode,
    l.UserDescription,
    l.CIHIValue,
    l.ValidFrom,
    l.ValidTo,
    l.InterfaceIn,
    AssociationDescription = l.AssociationDesc,
	h.DisplayCode AS HospitalLink,	--0287
	h.UserDescription AS HospitalLinkDesc	--0287
--into zzTempUserField
from #TempUserFields z
    inner join #AppIDs a on z.AppID = a.AppID
    inner join #TempLookUps l on z.LookUpTable = l.LookUpTable 
    left  join U_usersFields uf on z.LookUpTable = uf.LookUptable and uf.AppID = 1100 and uf.userID = @roleID
    left  join H_InstitutionProfile p on l.AssociationID = p.code
    left  join H_HospitalProfile h on l.HospitalID = h.code
where (isnull(l.AssociationID, 0) = 0 or z.LookUpTable like 'LU_ProjectQuestion%' 
    or (z.LookUpTable like 'LU_Ancillary%' and l.AssociationID = 
            (case when z.AppID in (101, 201)       then 1   --Inpatient
                  when z.AppID in (102, 202)       then 2   --S.D.S.
                  when z.AppID between 250 and 253 then 3   --Rehabilitation
                  when z.AppID between 470 and 479 then 4   --Long Term Care (CCRS)
                  when z.AppID in (301, 401)       then 5   --Ambulatory Care
                  --when z.AppID = 500               then 6 --Clinic
                  when z.AppID between 650 and 659 then 7   --Mental Health
                  when z.AppID between 765 and 769 then 8   --Cancer Care
                  when z.AppID = 3                 then 9   --Non Abstract
                  else 0 end )) 
    or (z.LookUpTable like 'LU_BasicOption%' and z.AppID = 
            (case when len(h.CIHIValue) = 4 and p.AssociationID = 1 then 101
                  when len(h.CIHIValue) = 5 and p.AssociationID = 1 then 201
                  when len(h.CIHIValue) = 4 and p.AssociationID = 2 then 102
                  when len(h.CIHIValue) = 5 and p.AssociationID = 2 then 202
                  when len(h.CIHIValue) = 4 and p.AssociationID = 5 then 301
                  when len(h.CIHIValue) = 5 and p.AssociationID = 5 then 401
                  when p.AssociationID = 3                          then 250
                  when p.AssociationID = 4                          then 470
                  --when h.AssociationID = 6                          then 500
                  when p.AssociationID = 7                          then 650
                  when p.AssociationID = 8                          then 765
                  when p.AssociationID = 9                          then 3
                  else 0 end)))
--and l.HospitalID > 0
order by a.AppDesc, z.FieldDesc, uf.Header_User, l.DisplayCode
set nocount off
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


-- Sets the Deleted Flag to NO
CREATE PROCEDURE [R_OMHRS_SecAA] (@RecordID [int])
AS 
update [OMHRS_SecAA] set [X2] = 200301 
where ([AbstractID] = @RecordID)
and AbstractID in (select AbstractID from OMHRS_RecInfo where AbstractID = @RecordID and isnull(IsCorrected, 1) <> 2)

update [OMHRS_SecAA] set [X2] = 200302
where ([AbstractID] = @RecordID)
and AbstractID in (select AbstractID from OMHRS_RecInfo where AbstractID = @RecordID and isnull(IsCorrected, 1) = 2)

update [OMHRS_RecInfo] set [IsDeleted] = 2 where ([AbstractID] = @RecordID)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [R_RehabSubmissionLog]
	@InstitutionNumber varchar(12), @SubmissionDate datetime = null, @InstitutionCode int = 0
as

set nocount on
Create table #RehabSubmission(
	ExecutionID	int,
	ExecutionDate datetime,
	CoderNumber varchar(20) COLLATE Latin1_General_CI_AS NULL,
	CoderNumberDesc varchar(200) COLLATE Latin1_General_CI_AS NULL,
	InstitutionNumber varchar(20) COLLATE Latin1_General_CI_AS NULL,
	InstitutionNumberDesc varchar(200) COLLATE Latin1_General_CI_AS NULL,
	NameOfFile varchar(250),
	BatchYear int,
	BatchPeriod varchar(20) COLLATE Latin1_General_CI_AS NULL,
	BatchPeriodDesc varchar(200) COLLATE Latin1_General_CI_AS NULL,
	Deletion int,
	DeletionSuccess varchar(20),
	Admission int,
	AdmissionSuccess varchar(20),
	Discharge int,
	DischargeSuccess varchar(20),
	FollowUp int,
	FollowUpSuccess varchar(20)
)

if isnull(@InstitutionNumber, '') = '' and @InstitutionCode > 0
	set @InstitutionNumber = (select top 1 CIHIValue from H_InstitutionProfile where code = @InstitutionCode)
	
select p.* 
	into #Deletion 
from dbo.SU_ExecProperties p
where InstNoCIHI = @InstitutionNumber and 
	p.GroupID in (select distinct GroupID from dbo.SU_StructureList s where SU_Type = 6) and
	(@SubmissionDate is null or convert(varchar(20), @SubmissionDate, 111) = convert(varchar(20), ExecutionDate, 111))
	
select p.* into #Admission 
from dbo.SU_ExecProperties p
where InstNoCIHI = @InstitutionNumber and 
	p.GroupID in (select distinct GroupID from dbo.SU_StructureList s where SU_Type = 7) and
	(@SubmissionDate is null or convert(varchar(20), @SubmissionDate, 111) = convert(varchar(20), ExecutionDate, 111))

select p.* into #Discharge 
from dbo.SU_ExecProperties p
where InstNoCIHI = @InstitutionNumber and 
	p.GroupID in (select distinct GroupID from dbo.SU_StructureList s where SU_Type = 8) and
	(@SubmissionDate is null or convert(varchar(20), @SubmissionDate, 111) = convert(varchar(20), ExecutionDate, 111))

select  p.* into #FollowUp 
from dbo.SU_ExecProperties p
where InstNoCIHI = @InstitutionNumber and 
	p.GroupID in (select distinct GroupID from dbo.SU_StructureList s where SU_Type = 9) and
	(@SubmissionDate is null or convert(varchar(20), @SubmissionDate, 111) = convert(varchar(20), ExecutionDate, 111))

insert into #RehabSubmission(ExecutionID, ExecutionDate, CoderNumber, CoderNumberDesc, InstitutionNumber, 
	InstitutionNumberDesc, NameOfFile, BatchYear, BatchPeriod, BatchPeriodDesc, Deletion, DeletionSuccess)
select z.ExecutionID, z.ExecutionDate, CoderNumber = u.DisplayCode, CoderNumberDesc = u.UserDescription, 
	InstitutionNumber = z.InstNoCIHI, InstitutionNumberDesc = h.UserDescription, z.NameOfFile, 
	z.BatchYear, BatchPeriod = b.DisplayCode, BatchPeriodDesc = b.UserDescription,
	Deletion = z.RecordCount, DeletionSuccess = (case when z.TerminateSuccess = 1 then 'Yes' else 'No' end)
from #Deletion z
	left join dbo.U_Users u on z.CoderNumber = u.code	
	left join dbo.lu_codefile b on z.BatchPeriod = b.code
	inner join dbo.H_InstitutionProfile h on z.InstNoCode = h.code

Update #RehabSubmission
set Admission = z.RecordCount,
	AdmissionSuccess = (case when z.TerminateSuccess = 1 then 'Yes' else 'No' end)
from #RehabSubmission R
	inner join 
	(select ExecutionID = (select max(d.ExecutionID) from #Deletion d where d.ExecutionID < a.ExecutionID and 
			d.BatchYear = a.BatchYear and d.BatchPeriod = a.BatchPeriod), 
		RecordCount, TerminateSuccess
	from #Admission a) z on r.ExecutionID = z.ExecutionID
		
Update #RehabSubmission
set Discharge = z.RecordCount,
	DischargeSuccess = (case when z.TerminateSuccess = 1 then 'Yes' else 'No' end)
from #RehabSubmission R
	inner join 
	(select ExecutionID = (select max(d.ExecutionID) from #Deletion d where d.ExecutionID < a.ExecutionID and 
			d.BatchYear = a.BatchYear and d.BatchPeriod = a.BatchPeriod), 
		RecordCount, TerminateSuccess
	from #Discharge a) z on r.ExecutionID = z.ExecutionID
	
Update #RehabSubmission
set FollowUp = z.RecordCount,
	FollowUpSuccess = (case when z.TerminateSuccess = 1 then 'Yes' else 'No' end)
from #RehabSubmission R
	inner join 
	(select ExecutionID = (select max(d.ExecutionID) from #Deletion d where d.ExecutionID < a.ExecutionID and 
			d.BatchYear = a.BatchYear and d.BatchPeriod = a.BatchPeriod), 
		RecordCount, TerminateSuccess
	from #FollowUp a) z on r.ExecutionID = z.ExecutionID
		
	
select 
	ExecutionDate,
	CoderNumber,
	CoderNumberDesc,
	InstitutionNumber,
	InstitutionNumberDesc,
	NameOfFile,
	BatchYear,
	BatchPeriod,
	BatchPeriodDesc,
	Deletion,
	DeletionSuccess,
	Admission,
	AdmissionSuccess = isnull(AdmissionSuccess, 'No'),
	Discharge,
	DischargeSuccess = isnull(DischargeSuccess, 'No'),
	FollowUp,
	FollowUpSuccess = isnull(FollowUpSuccess, 'No')
from #RehabSubmission order by ExecutionID desc

set nocount off
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- Sets the Deleted Flag to NO
CREATE PROCEDURE [R_RH_ClientInfo] (@RecordID [int])
AS 

UPDATE [RH_ClientInfo] SET [IsDeleted] = 2 WHERE ([AbstractID] = @RecordID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO






CREATE PROCEDURE [R_ROI_Invoice]
	@ROIID as int
AS
SELECT     dbo.LU_ROI_Requesters.UserDescription AS RequesterName, dbo.LU_ROI_Requesters.Address, dbo.LU_ROI_Requesters.PostalCode, 
                      dbo.LU_ROI_Requesters.BillingAddress, dbo.LU_ROI_Requesters.BillingPostalCode, dbo.ROI_Main.RequestComments, dbo.ROI_SentItems.Quantity, 
                      dbo.ROI_Main.InvoiceNumber, dbo.ROI_Main.InvoiceDate, dbo.ROI_Main.InvoiceTotal, dbo.LU_ROI_RequestTypes.DisplayCode AS Linecode, 
                      dbo.LU_ROI_RequestTypes.UserDescription AS LineDescription, dbo.LU_ROI_TaxType.DisplayCode AS TaxType, 
                      dbo.ROI_SentItems.Price AS PricePer, dbo.ROI_SentItems.Amount AS LineTotal, dbo.ROI_SentItems.SentDate, dbo.LU_ROI_Requesters.Phone, 
                      dbo.LU_ROI_Requesters.Fax, dbo.LU_ROI_Contacts.UserDescription AS Contact, dbo.LU_ROI_Contacts.Phone AS ContactPhone, 
                      dbo.LU_ROI_Contacts.PhoneExt AS ContactFax, dbo.ROI_Main.AmountPaid, dbo.ROI_Main.AmountOwed, dbo.ROI_Main.GSTNumber, 
                      dbo.ROI_Main.DueDate
FROM         dbo.LU_ROI_RequestTypes RIGHT OUTER JOIN
                      dbo.ROI_SentItems ON dbo.LU_ROI_RequestTypes.Code = dbo.ROI_SentItems.ItemCode LEFT OUTER JOIN
                      dbo.LU_ROI_TaxType ON dbo.ROI_SentItems.TaxCode = dbo.LU_ROI_TaxType.Code RIGHT OUTER JOIN
                      dbo.ROI_Main ON dbo.ROI_SentItems.ROIID = dbo.ROI_Main.ROIID LEFT OUTER JOIN
                      dbo.LU_ROI_Contacts ON dbo.ROI_Main.ContactID = dbo.LU_ROI_Contacts.Code LEFT OUTER JOIN
                      dbo.LU_ROI_Requesters ON dbo.ROI_Main.RequesterID = dbo.LU_ROI_Requesters.Code
WHERE     (dbo.ROI_Main.ROIID = @ROIID)





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





-- Sets the Deleted Flag to NO
CREATE PROCEDURE [R_ROI_Main] (@ROIID [int])
AS 

UPDATE [ROI_Main] SET [IsDeleted] = 2 WHERE ([ROIID] = @ROIID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [R_SP_MacKenzie_Project340]
    @AbstractID int
as
set nocount on

--select AbstractID, InstitutionTo, DispositionCode, ResponsiblePayment, PostalCode into #ab_abstract from ab_abstract where AbstractID = @AbstractID
--select DiagnosisCode, DiagnosisType into #ab_diagnosis from ab_diagnosis where AbstractID = @AbstractID and diagnosiscode > 0
--select projectnumber into #ab_project from ab_project where AbstractID = @AbstractID and projectnumber > 0

select 
    InstitutionTo, 
    DischargeDisposition, 
    PostalCode, 
    ResponsiblityForPayment,
    I340, X340,
    P340, P998, P640,
    zzAbstractLink

from
(SELECT 
    InstitutionTo = isnull(LU_Institution_10.DisplayCode, ''), 
    DischargeDisposition = isnull(LU_DispositionCode_I.DisplayCode, ''), 
    ResponsiblityForPayment = isnull(LU_RespPayment.DisplayCode, ''),
    --InstitutionTo = isnull((select LU_Institution_10.DisplayCode from LU_Institution_10 where ab_abstract.InstitutionTo = LU_Institution_10.Code), ''), 
    --DischargeDisposition = isnull((select LU_DispositionCode_I.DisplayCode from LU_DispositionCode_I where ab_abstract.DispositionCode= LU_DispositionCode_I.Code), ''), 
    --ResponsiblityForPayment = isnull((select LU_RespPayment.DisplayCode from LU_RespPayment where ab_abstract.ResponsiblePayment = LU_RespPayment.Code), ''),
    PostalCode = isnull(PostalCode, ''), 
    zzAbstractLink = AbstractID
FROM  ab_abstract
    left join LU_Institution_10 on InstitutionTo = LU_Institution_10.Code
    left join LU_DispositionCode_I on DispositionCode= LU_DispositionCode_I.Code
    left join LU_RespPayment on ab_abstract.ResponsiblePayment = LU_RespPayment.Code
where abstractid = @AbstractID
) a,
(select sum((case when LU_DiagnosisType.CIHIValue in ('M','1','W','X','Y') and ICD_DiagFile10.CIHIValue not in ('I608','I636','G454') 
                and (left(ICD_DiagFile10.CIHIValue, 3) in ('I60', 'I61', 'I63','I64') or ICD_DiagFile10.CIHIValue in ('I676','H340','H341','G08','G450','G451','G452','G453','G458','G459')) 
             then 1 else 0 end)) as I340,
    sum((case when isnull(LU_DiagnosisType.CIHIValue, '') not in ('M','1','W','X','Y')  
                and (left(ICD_DiagFile10.CIHIValue, 3) in ('I60', 'I61', 'I63','I64') or ICD_DiagFile10.CIHIValue in ('I676','H340','H341','G08','G450','G451','G452','G453','G458','G459')) 
             then 1 else 0 end)) as X340,
    sum((case when ICD_DiagFile10.CIHIValue like 'I62%' then 1 else 0 end)) as I62
from AB_Diagnosis 
    inner join ICD_DiagFile10 on DiagnosisCode = ICD_DiagFile10.Code
    left join LU_DiagnosisType on DiagnosisType = LU_DiagnosisType.Code
where abstractid = @AbstractID
) d,
(select 
    sum((case when CIHIValue = '340' then 1 else 0 end)) P340,
    sum((case when CIHIValue = '998' then 1 else 0 end)) P998,
    sum((case when CIHIValue = '640' then 1 else 0 end)) P640
from ab_project
    inner join LU_Project on ProjectNumber = code
where abstractid = @AbstractID
) p

--(SELECT 
--    InstitutionTo = isnull(LU_Institution_10.DisplayCode, ''), 
--    DischargeDisposition = isnull(LU_DispositionCode_I.DisplayCode, ''), 
--    PostalCode = isnull(PostalCode, ''), 
--    ResponsiblityForPayment = isnull(LU_RespPayment.DisplayCode, ''),
--    zzAbstractLink = AbstractID
--FROM  #ab_abstract ab_abstract
--    left join LU_Institution_10 on InstitutionTo = LU_Institution_10.Code
--    left join LU_DispositionCode_I on DispositionCode= LU_DispositionCode_I.Code
--    left join LU_RespPayment on ab_abstract.ResponsiblePayment = LU_RespPayment.Code
--) a,
--(select sum((case when LU_DiagnosisType.CIHIValue in ('M','1','W','X','Y') and ICD_DiagFile10.CIHIValue not in ('I608','I636','G454') 
--                and (left(ICD_DiagFile10.CIHIValue, 3) in ('I60', 'I61', 'I63','I64') or ICD_DiagFile10.CIHIValue in ('I676','H340','H341','G08','G450','G451','G452','G453','G458','G459')) 
--             then 1 else 0 end)) as I340,
--    sum((case when isnull(LU_DiagnosisType.CIHIValue, '') not in ('M','1','W','X','Y')  
--                and (left(ICD_DiagFile10.CIHIValue, 3) in ('I60', 'I61', 'I63','I64') or ICD_DiagFile10.CIHIValue in ('I676','H340','H341','G08','G450','G451','G452','G453','G458','G459')) 
--             then 1 else 0 end)) as X340,
--    sum((case when ICD_DiagFile10.CIHIValue like 'I62%' then 1 else 0 end)) as I62
--from #ab_diagnosis AB_Diagnosis 
--    inner join ICD_DiagFile10 on DiagnosisCode = ICD_DiagFile10.Code
--    left join LU_DiagnosisType on DiagnosisType = LU_DiagnosisType.Code
--) d,
--(select 
--    sum((case when CIHIValue = '340' then 1 else 0 end)) P340,
--    sum((case when CIHIValue = '998' then 1 else 0 end)) P998,
--    sum((case when CIHIValue = '640' then 1 else 0 end)) P640
--from #ab_project
--    inner join LU_Project on ProjectNumber = code) p
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- Sets the Deleted Flag to NO
CREATE PROCEDURE [R_Transcription] (@RecordID [int])
AS 

UPDATE [TR_Main] SET [IsDeleted] = 2 WHERE ([TranscriptionID] = @RecordID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [Rpt_InpatientSummary]
	@AbstractID as int
AS
SELECT     dbo.AB_Abstract.ICDType, dbo.AB_Abstract.AbstractID, dbo.AB_Abstract.EncounterNumber, dbo.AB_Abstract.EncounterSequence, 
                      dbo.AB_Abstract.ChartNumber, dbo.H_InstitutionProfile.DisplayCode AS InstitutionNumber, 
                      dbo.H_InstitutionProfile.UserDescription AS InstitutionDescription, dbo.U_Users.DisplayCode AS CoderNumber, 
                      dbo.U_Users.UserDescription AS CoderDescription, dbo.AB_Abstract.FirstName, dbo.AB_Abstract.MiddleName, dbo.AB_Abstract.LastName, 
                      dbo.LU_Gender_I.DisplayCode AS Gender, dbo.LU_Gender_I.UserDescription AS GenderDescription, dbo.AB_Abstract.BirthDate, 
                      dbo.AB_Abstract.AdmitDate, dbo.AB_Abstract.AdmitTime, dbo.AB_Abstract.DischargeDate, dbo.AB_Abstract.DischargeTime, 
                      dbo.LU_AdmitCategory.DisplayCode AS AdmitCode, dbo.LU_AdmitCategory.UserDescription AS AdmitDescription, 
                      dbo.LU_DispositionCode_I.DisplayCode AS ExitCode, dbo.LU_DispositionCode_I.UserDescription AS ExitDescription, 
                      dbo.AB_Abstract.AgeNumber AS Age, dbo.AB_Diagnosis.DiagnosisOccurrence, dbo.ICD_DiagFile10.DisplayCode AS DiagnosisCode, 
                      dbo.ICD_DiagFile10.UserDescription AS DiagnosisDescription, dbo.LU_DiagnosisType.DisplayCode AS DiagnosisType, 
                      dbo.LU_DiagnosisType.UserDescription AS DiagnosisTypeDescription, dbo.AB_Intervention.IntervOccurrence, 
                      dbo.ICD_ProcFile10.DisplayCode AS InterventionCode, dbo.ICD_ProcFile10.UserDescription AS InterventionDescription
FROM         dbo.AB_Intervention LEFT OUTER JOIN
                      dbo.ICD_ProcFile10 ON dbo.AB_Intervention.IntervCode = dbo.ICD_ProcFile10.Code RIGHT OUTER JOIN
                      dbo.AB_Abstract ON dbo.AB_Intervention.AbstractID = dbo.AB_Abstract.AbstractID LEFT OUTER JOIN
                      dbo.LU_DiagnosisType RIGHT OUTER JOIN
                      dbo.AB_Diagnosis ON dbo.LU_DiagnosisType.Code = dbo.AB_Diagnosis.DiagnosisType LEFT OUTER JOIN
                      dbo.ICD_DiagFile10 ON dbo.AB_Diagnosis.DiagnosisCode = dbo.ICD_DiagFile10.Code ON 
                      dbo.AB_Abstract.AbstractID = dbo.AB_Diagnosis.AbstractID LEFT OUTER JOIN
                      dbo.LU_DispositionCode_I ON dbo.AB_Abstract.ExitCode = dbo.LU_DispositionCode_I.Code LEFT OUTER JOIN
                      dbo.LU_AdmitCategory ON dbo.AB_Abstract.EntryCode = dbo.LU_AdmitCategory.Code LEFT OUTER JOIN
                      dbo.LU_Gender_I ON dbo.AB_Abstract.Gender = dbo.LU_Gender_I.Code LEFT OUTER JOIN
                      dbo.U_Users ON dbo.AB_Abstract.CoderNumber = dbo.U_Users.Code LEFT OUTER JOIN
                      dbo.H_InstitutionProfile ON dbo.AB_Abstract.InstitutionNumber = dbo.H_InstitutionProfile.Code
WHERE     (dbo.AB_Abstract.AbstractID = @AbstractID)
ORDER BY dbo.AB_Diagnosis.DiagnosisOccurrence, dbo.AB_Intervention.IntervOccurrence

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [SU_CCR_Initialize]
    @SU_Type     int,
    @date_fr     datetime,
    @date_to     datetime,
    @InstCode    int,
    @FiscalYr    int,
    @FiscalQt    int,
    @RecCount    int output,
    @RecWidth    int output,
    @ExecutionID int output,
    @NameOfFile  varchar(50) output,
    @CoderNumber int = 999999,
    @Resubmit    int
as

declare @AppID    int
declare @GroupID  int
declare @DateSent datetime
declare @SU_Const varchar(20)
-- PR - 01564
declare @medcount int

declare @BatchPeriod int

set @BatchPeriod = (case @FiscalQt when 1 then 15401  -- Quarter 1
                                   when 2 then 15402  -- Quarter 2
                                   when 3 then 15403  -- Quarter 3
                                   when 4 then 15404  -- Quarter 4
                                   when 6 then 15406  -- Q6 submission  ED - 02155
                                   else @FiscalQt
                    end) 

if @FiscalQt = @FiscalQt    --ED - 02155 Q6
begin
    set @FiscalYr = datepart(year, @date_to) - (case when datepart(month, @date_to) > 3 then 0 else 1 end)
end

-- eSU_CRS_ASSESS_QURT = 10	
-- eSU_CRS_ASSESS_FULL = 11	
-- eSU_CRS_ASSESS_DSCH = 12	
-- eSU_CRS_ASSESS_ADMT = 13	
-- eSU_CRS_ASSESS_RNTR = 14	
-- eSU_CRS_ASSESS_MAST = 15	
-- eSU_CRS_ASSESS_MEDI = 16	
-- eSU_CRS_ASSESS_DEMO = 17	
-- eSU_CRS_ASSESS_UPDATE = 20  --Add 2010
-- eSU_CRS_ASSESS_PROJECT = 21 --Add 2010

select @SU_Const = su_const from SU_StructureType where su_id = @SU_Type

set @AppID = 
    case @SU_Type
        when 10 then 472
        when 11 then 473
        when 12 then 474
        when 13 then 470
        when 14 then 475
        when 15 then 470
        when 16 then 473
        when 17 then 471
        when 20 then 476
        when 21 then 470	--ED - 02385 477
    end

--EN - 00651
declare @RehabSubDate datetime
declare @SubFiscalYear int
select top 1 @RehabSubDate = RehabSubDate from H_InstitutionProfile where Code = @InstCode

set @DateSent = GetDate()
if @RehabSubDate is null
    set @SubFiscalYear = @FiscalYr
else 
begin
    set @SubFiscalYear = datepart(year, @DateSent) - (case when datepart(month, @DateSent) in (1, 2, 3) then 1 else 0 end)
    if @RehabSubDate >= @DateSent 
    begin
        if @FiscalYr < @SubFiscalYear and @DateSent >= cast(cast(datepart(year, @RehabSubDate) as varchar(10)) + '/04/01' as datetime)
            set @SubFiscalYear = @SubFiscalYear - 1
        else if @FiscalYr > @SubFiscalYear
            set @SubFiscalYear = @FiscalYr
    end    
    else if @RehabSubDate < @DateSent 
    begin
        set @SubFiscalYear = datepart(year, @RehabSubDate) - (case when datepart(month, @RehabSubDate) in (1, 2, 3) then 1 else 0 end)
        if @FiscalYr > @SubFiscalYear
            set @SubFiscalYear = @FiscalYr

    end    
end
--EN - 00651
--set @GroupID = dbo.SUF_GET_GroupID( @SU_type, @AppID, @FiscalYr, 0, 0 )
set @GroupID = dbo.SUF_GET_GroupID( @SU_type, @AppID, @SubFiscalYear, 0, 0 )

print 'GroupID = ' + str(@GroupID)

declare @Records table ( AbstractID int, OrderBy int identity(1,1) )

set @DateSent = GetDate()

insert SU_ExecProperties 
       ( ExecutionDate, GroupID,  AppID,  CoderNumber,  DateStart, DateEnd,  InstNoCode, BatchYear, BatchPeriod, ICDType, SubFiscalYear ) 
values ( @DateSent,     @GroupID, @AppID, @CoderNumber, @date_fr,  @date_to, @InstCode,  @FiscalYr, @BatchPeriod, 'T', @SubFiscalYear) --@FiscalQt, 'T' )

set @ExecutionID = @@identity


------------------------------------------------------------------------------------
-- GET A LIST OF ABSTRACTID'S THAT WILL BE USED TO CREAT THE SUBMISSION FILE
--
-- NOTE: Send AppID = -1 for master list of record keys
-- 
if @Resubmit = 0 
    insert @Records ( AbstractID ) 
    select AbstractID 
    from dbo.SU_SELECT_CCRS( @SU_Const, @InstCode, @date_fr, @date_to, @BatchPeriod )
    where (@date_fr < '2012/04/01' and IsSubmited != 1 and IsDeleted = 2) --or @SU_Type in (16, 21))
        or (@date_fr >= '2012/04/01' and ((IsSubmited != 1 and IsDeleted = 2) or IsCorrected = 2))
    order by (case when IsDeleted in (1, 3) then 0 - AbstractID else 0 end), patient_id, event_date, assessment 
    --order by (case when IsDeleted in (1, 3) then 0 - AbstractID else AbstractID end), event_date, assessment 
    --ED - 02710  
else
    --ED - 02783
    insert @Records ( AbstractID ) 
    select AbstractID 
    from dbo.SU_SELECT_CCRS( @SU_Const, @InstCode, @date_fr, @date_to, @BatchPeriod )
    where (@date_fr < '2012/04/01' and IsSubmited = 1 and IsDeleted = 2) --or @SU_Type in (16, 21)) --PR - 06932
        or (@date_fr >= '2012/04/01' and ((IsDeleted = 2) or IsCorrected = 2))
    order by (case when IsDeleted in (1, 3) then 0 - AbstractID else 0 end), patient_id, event_date, assessment 
    --order by (case when IsDeleted in (1, 3) then 0 - AbstractID else AbstractID end), event_date, assessment 
    --ED - 02710  

insert SU_RecordSelect ( 
    ExecutionID  , 
    AbstractID   ,     OrderBy      , 
    IsSubmited   , 
    IsValidated  , 
    IsCompleted  , 
    IsDeleted    , 
    CIHIDateSent , 
    BatchYear    ,
    BatchPeriod  )
select 
    @ExecutionID  , 
    r.AbstractID  , 
    r.OrderBy     ,
	1             ,
	a.IsValidated ,
	a.IsCompleted ,
	a.IsDeleted   ,
	@DateSent     ,
	@FiscalYr     ,
    @BatchPeriod    --@FiscalQt
from @Records r 
join dbo.CRS_Demographic a on r.AbstractID = a.AbstractID 
order by OrderBy

-- set the total number of records: 
set @RecCount = @@rowcount

-- PR - 01564
-- eSU_CRS_ASSESS_MAST = 15	
-- eSU_CRS_ASSESS_MEDI = 16	
if @SU_Type = 15
begin
    set @medcount = (select count(*)
        from @Records r 
            join dbo.CRS_Demographic a on r.AbstractID = a.AbstractID 
            join dbo.CRS_Medication m on a.abstractid = m.abstractid
        where a.Z1 in (15353, 15354))
    set @RecCount = @RecCount + isnull(@medcount, 0)
end
if @SU_Type = 16
begin
    set @medcount = (select count(*)
        from @Records r 
            join dbo.CRS_Demographic a on r.AbstractID = a.AbstractID 
            join dbo.CRS_Medication m on a.abstractid = m.abstractid
        where a.Z1 in (15353, 15354)and occurrence > 1)
    set @RecCount = @RecCount + isnull(@medcount, 0)
end

delete from @Records

DBCC DBREINDEX (SU_RecordSelect)

select @RecWidth = sum(TextLength) 
from SU_StructureFile 
where GroupID = @GroupID


set @NameOfFile = dbo.SU_FILENAME_CCRS( @ExecutionID, @SU_Const )

-----------------------------------------------------------------------------------
-- UPDATE THE EXECUTION PROPERTIES TABLE WITH THE VARIOUS VALUES
update SU_ExecProperties
set RecordCount = @RecCount,
    RecordWidth = @RecWidth,
    NameOfFile  = @NameOfFile,
    InstNoCIHI  = (select CIHIValue from H_InstitutionProfile where Code = @InstCode)
where ExecutionID = @ExecutionID

EXIT_PROCEDURE_NORMAL:
    return 0
ERROR___INVALID_SUBMISSION_NUMBER:
    return 1

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [SU_CCRS_ControlRecord]
    @ExecutionID int,
    @ControlRecord varchar(100) output
as


declare 
    @tt       char(2), -- Data record type 
    @dddddddd char(8), -- Date of submission 
    @pp       char(2), -- Province/territory code 
    @fffff    char(5), -- Facility number 
    @yyyy     char(4), -- Fiscal year for this submission 
    @q        char(1), -- Fiscal quarter for this submission 
    @cccccc   char(6), -- Number of data records in transmission
    @vvv   char(3)  -- Version Number
declare @Inst int   --ED - 02710
declare @SubFiscalYear int --EN - 00651
    
set @tt = '00'
set @pp = 
    case (select top 1 ProvinceNumber from H_HospitalProfile)
        when 13 then 'AB' -- Alberta                  
        when 14 then 'BC' -- British Columbia         
        when 11 then 'MB' -- Manitoba                 
        when  8 then 'NB' -- New Brunswick            
        when  5 then 'NL' -- Newfoundland and Labrador
        when  7 then 'NS' -- Nova Scotia              
        when  2 then 'NT' -- North West Territories   
        when  3 then 'NU' -- Nunavut                  
        when 10 then 'ON' -- Ontario                  
        when  6 then 'PE' -- Prince Edward Island     
        when  9 then 'QC' -- Quebec                   
        when 12 then 'SK' -- Saskatchewan             
        when  4 then 'YT' -- Yukon                    
    end

select 
  @dddddddd = convert( varchar(8), ExecutionDate, 112 )
, @fffff    = InstNoCIHI
, @yyyy     = convert( char(4), BatchYear)
, @q        = (case BatchPeriod when 15401 then '1' 
                                when 15402 then '2'
                                when 15403 then '3'
                                when 15404 then '4'
                                when 15406 then '6' --ED - 02155
                                else str(BatchPeriod, 1) 
               end)
, @cccccc   = replace(str(RecordCount, 6), ' ', '0')
, @Inst     = InstNoCode
, @SubFiscalYear = isnull(SubFiscalYear, BatchYear)
from SU_ExecProperties 
where ExecutionID = @ExecutionID
----EN - 00651
--if cast(@yyyy as int) < 2012 
--begin
--    set @ControlRecord = '00ddddddddppfffffyyyyqcccccc'
--    set @ControlRecord = 
--        replace(
--        replace(
--        replace(
--        replace(
--        replace(
--        replace(
--        replace(
--            @ControlRecord 
--        , 'tt'      , isnull( @tt      , 'tt'       ) )
--        , 'dddddddd', isnull( @dddddddd, 'dddddddd' ) )
--        , 'pp'      , isnull( @pp      , 'pp'       ) )
--        , 'fffff'   , isnull( @fffff   , 'fffff'    ) )
--        , 'yyyy'    , isnull( @yyyy    , 'yyyy'     ) )
--        , 'q'       , isnull( @q       , 'q'        ) )
--        , 'cccccc'  , isnull( @cccccc  , 'cccccc'   ) )
--end
--else
--begin
    --ED - 02710
    set @tt = 'CR'
    set @fffff = (select (case when len(isnull(MDS20_SubmissionOrgID, '')) < 5 then CIHIValue else MDS20_SubmissionOrgID end) from H_InstitutionProfile where code = @Inst)
    
    set @ControlRecord = 'ttMDS_2_0-vvv   M0004ddddddddfffffyyyyqcccccc'
    --EN - 00651
    --if cast(@yyyy as int) = 2012 
    --    set @vvv = '1.0   '
    --if @SubFiscalYear <= 2013 
    --    set @vvv = '2.0   '
    --if @SubFiscalYear <= 2014 and getdate() < '2015/06/02'
    --    set @vvv = '3.0   '
    --if @SubFiscalYear <= 2015 and getdate() < '2016/06/01'
    --    set @vvv = '4.0'
    if @SubFiscalYear <= 2019 and getdate() < '2020/06/01'
        set @vvv = '5.0'
    else
        set @vvv = '5.1'    --2.x-1869 change from 5.0 to 5.1

    set @ControlRecord = 
        replace(
        replace(
        replace(
        replace(
        replace(
        replace(
        replace(
        replace(
            @ControlRecord 
        , 'tt'      , isnull( @tt      , 'tt'       ) )
        , 'dddddddd', isnull( @dddddddd, 'dddddddd' ) )
        , 'pp'      , isnull( @pp      , 'pp'       ) )
        , 'fffff'   , isnull( @fffff   , 'fffff'    ) )
        , 'yyyy'    , isnull( @yyyy    , 'yyyy'     ) )
        , 'q'       , isnull( @q       , 'q'        ) )
        , 'cccccc'  , isnull( @cccccc  , 'cccccc'   ) )
        , 'vvv'     , isnull( @vvv     , 'vvv'   ) )
--end
return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [SU_CCRS_MED_CheckSequence]
    @AbstractID [int],
	@Occurrence int,
	@Seq varchar(2)  output,
	@RecordType varchar(1) output
as    
    --ED - 02710
    declare @IsDeleted int
    declare @i int
    
    select top 1 @Seq = substring(SubmitedRecord, 96, 2) ,  @IsDeleted = IsDeleted
    from SU_Record_Submited_CCRS_MED S
    where S.AbstractID = @AbstractID and S.Occurrence = @Occurrence
    order by S.ExecutionID desc
    
    set @RecordType = 'N'
    if isnull(@Seq, '') = '' 
        set @Seq = '00'
    else if isnumeric(@Seq) = 0 and @IsDeleted not in (1, 3)
        set @Seq = '00'
    else
    begin
        if @IsDeleted in (1, 3)
        begin
            set @i = cast(@Seq as int) + 1
            set @Seq = right('00' + cast(@i as varchar(10)), 2)
        end
        else
            set @RecordType = 'C'
    end
    


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [SU_CCRS_MED_Delete]
	@AbstractID [int]  ,
	@IsDeleted [int]       
as    
    select left(S.SubmitedRecord, 97) + 'D'
    from SU_Record_Submited_CCRS_MED S
        inner join
        (select AbstractID, Occurrence, max(ExecutionID) MID, max(CIHIDateSent) MDate 
        from SU_Record_Submited_CCRS_MED
        where AbstractID = @AbstractID
        group by AbstractID, Occurrence) t on s.ExecutionID = t.MID and s.AbstractID = t.AbstractID and s.Occurrence = t.Occurrence
            and s.CIHIDateSent = t.MDate
        left join CRS_Medication M 
        on S.Occurrence = M.Occurrence and S.AbstractID = M.AbstractID
    where S.AbstractID = @AbstractID and S.IsDeleted <> 1 and
        (@IsDeleted = 1 or (  @IsDeleted = 0 and M.Occurrence is null))

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create procedure [SU_CCRS_MED_SaveRecord](
    @ExecutionID int,
    @AbstractID [int],
	@Occurrence int,
	@IsCorrected int,
	@IsDeleted int,
	@SubmitedRecord varchar(4000)
)	
as    
    insert into dbo.SU_Record_Submited_CCRS_MED(
        ExecutionID, 
        AbstractID, 
        Occurrence, 
        IsCorrected, 
        IsDeleted, 
        CIHIDateSent, 
        SubmitedRecord)
    select 
        @ExecutionID,
        @AbstractID,
	    @Occurrence,
	    @IsCorrected,
	    @IsDeleted,
	    Getdate(),
	    @SubmitedRecord 
	    
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create procedure [SU_CheckBatchYear]
    @BatchYear int, @AppID int, @IsExists int output
as
    set @IsExists =isnull( (select count(*) from dbo.SU_StructureList 
                where BatchYear = @BatchYear and AppID = @AppID), 0)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE  procedure [SU_CheckForDADICD10Deletions]
    @ExecutionID int,
    @UseCareType int,
    @RecordCount int output
as

declare 
  @DateFr datetime
, @DateTo datetime
, @InstNoCode int

select 
  @DateFr = DateStart
, @DateTo = DateEnd
, @InstNoCode = InstNoCode
from SU_ExecProperties 
where ExecutionID = @ExecutionID

if @UseCareType = 15681 and @DateFr >= '2020/04/01' 
    select @RecordCount = count(AbstractID)
    from
    (select distinct AB_Abstract.AbstractID, Batchyear, BatchPeriod, BatchNumber, AbstractNumber
    from dbo.AB_Abstract
        inner join AB_Diagnosis on AB_Abstract.AbstractID = AB_Diagnosis.AbstractID
        inner join ICD_DiagFile10 on AB_Diagnosis.DiagnosisCode = ICD_DiagFile10.Code
    where (DischargeDate between @DateFr and @DateTo) 
        and (InstitutionNumber = @InstNoCode) 
        and (IsDeleted in (1, 3)) -- THE RECORD HAS BEEN DELETED
        and (IsCorrected = 2) 
        and ICD_DiagFile10.CIHIValue in ('U071', 'U072')) z
else
    --Ticket 13082 change IsDeleted = 1 to IsDeleted in (1, 3)
    select @RecordCount = count(AbstractID)
    from AB_Abstract 
    where DischargeDate between @DateFr and @DateTo 
    and InstitutionNumber = @InstNoCode
    and IsDeleted in (1, 3) -- THE RECORD HAS BEEN DELETED
    and IsCorrected = 2 

return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [SU_CheckForNacrsClosure]
    @InstNoCode int,
    @BatchYear int,
    @BatchPeriod int,
    @LevelCode   int,   --NP - 00125
    @IsClosureFile bit output
as

declare 
    @DateFr datetime,
    @DateTo datetime

select 
    @DateFr = dbo.SUF_GetPeriodDateFr( @BatchYear, @BatchPeriod ), 
    @DateTo = dbo.SUF_GetPeriodDateTo( @BatchYear, @BatchPeriod )

declare @Province varchar(12)	--PR - 04580
set @Province = (select top 1 p.CIHIValue from H_HospitalProfile h inner join lu_province p on h.ProvinceNumber = p.code)

if @LevelCode = 3
begin
    if exists 
    (
        select * 
        from AB_Abstract
        where AdmitDate between @DateFr and @DateTo
        and InstitutionNumber = @InstNoCode
        and ((IsSubmited = 2 and IsDeleted = 2) or (IsCorrected = 2))
        and isnull(isLiteSubmission, 0) <> 1
    )
        set @IsClosureFile = 0
    else
        set @IsClosureFile = 1
end
else if @LevelCode = 0	--2.x-0258
begin
		if exists 
		(
			select * 
			from AB_Abstract inner join lu_miscode on AB_Abstract.MISCode = lu_miscode.code
			where AdmitDate between @DateFr and @DateTo
			and InstitutionNumber = @InstNoCode
			and lu_miscode.AmcareGroup in ('CL', 'OT', 'DI')
            and isLiteSubmission = 1
			and ((IsSubmitLevel1 = 2 and IsDeleted = 2) or (IsCorrectLevel1 = 2))
		)
			set @IsClosureFile = 0
		else
			set @IsClosureFile = 1
end
else
begin
	--if @Province = '5'
	--begin
		if exists 
		(
			select * 
			from AB_Abstract inner join lu_miscode on AB_Abstract.MISCode = lu_miscode.code
			where AdmitDate between @DateFr and @DateTo
			and InstitutionNumber = @InstNoCode
			and (lu_miscode.AmcareGroup = 'ED' or (lu_miscode.CIHIValue like '7_310%' and lu_miscode.AmcareGroup is null))	--PR - 04580
			and ((IsSubmitLevel1 = 2 and IsDeleted = 2) or (IsCorrectLevel1 = 2))
		)
			set @IsClosureFile = 0
		else
			set @IsClosureFile = 1
	--end
	--else
	--begin
	--	if exists 
	--	(
	--		select * 
	--		from AB_Abstract
	--		where AdmitDate between @DateFr and @DateTo
	--		and InstitutionNumber = @InstNoCode
	--		and ((IsSubmitLevel1 = 2 and IsDeleted = 2) or (IsCorrectLevel1 = 2))
	--	)
	--		set @IsClosureFile = 0
	--	else
	--		set @IsClosureFile = 1
	--end
end

return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [SU_CheckLevel1Submission]
    @InstNoCode   int,
    @BatchYear    int,
    @BatchPeriod  int,
    @Level1RecordCount int output
as
--PR - 04904

declare 
    @DateFr varchar(10),
    @DateTo varchar(10)

select 
    @DateFr = dbo.SUF_GetPeriodDateFr( @BatchYear, @BatchPeriod ), 
    @DateTo = dbo.SUF_GetPeriodDateTo( @BatchYear, @BatchPeriod )

set @Level1RecordCount = 0

declare @NacrsLevelSetting int 
declare @CareType int

select @CareType = AssociationID, @NacrsLevelSetting = LevelCode   
from H_InstitutionProfile where Code = @InstNoCode
--Add level 2
if @CareType = 5 and (@NACRSLevelSetting in (4, 5))						
begin
    select @Level1RecordCount = count(*)
    from dbo.AB_Abstract a 
        inner join LU_MISCode l on a.MISCode = l.code and (l.CIHIValue like '71310%' or l.CIHIValue like '72310%' or l.CIHIValue like '73310%') 
    where ( AdmitDate between @DateFr and @DateTo )
      and ( InstitutionNumber = @InstNoCode )
      and IsSubmitLevel1 = 2
      and IsSubmited = 2
end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [SU_CheckLevel3Submission]
    @InstNoCode   int,
    @BatchYear    int,
    @BatchPeriod  int,
    @IsCorrection int,
    @NACRSLevelCode   int, 
    @CoderNumber int ,
    @Level3RecordCount int output
as
--ED - 02067

declare 
    @DateFr varchar(10),
    @DateTo varchar(10)

select 
    @DateFr = dbo.SUF_GetPeriodDateFr( @BatchYear, @BatchPeriod ), 
    @DateTo = dbo.SUF_GetPeriodDateTo( @BatchYear, @BatchPeriod )

set @Level3RecordCount = 0

declare @NacrsLevelSetting int 
declare @CareType int

select @CareType = AssociationID, @NacrsLevelSetting = LevelCode    --, @Level3Date = Level3Date 
from H_InstitutionProfile where Code = @InstNoCode
--Add level 2
if @CareType = 5 and ((@NacrsLevelCode = 1 and @NACRSLevelSetting = 4) or 
					  (@NacrsLevelCode = 2 and @NACRSLevelSetting = 5))						
begin

    update AB_Abstract 
    set IsCorrectLevel1 = 1
    where InstitutionNumber = @InstNoCode 
        and AdmitDate between @DateFr and @DateTo 
        and IsSubmitLevel1 = 2 
        and IsDeleted = 2 
        and IsCorrectLevel1 <> 1 
        --and IsSubmited = 2

    
    --PR - 05785 Client cannot create level 1 or 2 if level 3 file is created.
    select @Level3RecordCount = count(*)
    from dbo.AB_Abstract a 
        inner join LU_MISCode l on isnull(a.MISCode, 0) = l.code 
    where ( AdmitDate between @DateFr and @DateTo )
      and ( InstitutionNumber = @InstNoCode )
      and IsSubmited = 1
      and l.AmCareGroup = 'ED'  --PR - 07157
end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--13242
CREATE procedure [SU_CheckRehabDeletion]
    @InstNoCode  int,
    @BatchYear   int, 
    @BatchPeriod int,
    @Count       int output
as
declare @DateFr datetime, @DateTo datetime

select 
    @DateFr = dbo.SUF_GetPeriodDateFr( @BatchYear, @BatchPeriod ), 
    @DateTo = dbo.SUF_GetPeriodDateTo( @BatchYear, @BatchPeriod )

    select @Count = count(*)
    from RH_ClientInfo r
--PR - 04320 Base on Cindy comment. Do not check the date.
--    where ( ( AdmitDate between @DateFr and @DateTo and AssessmentType = 134 )
--           or ( DischargeDate between @DateFr and @DateTo and AssessmentType = 135 )
--           or ( FollowUpDate between @DateFr and @DateTo and AssessmentType = 136 ))
    where ( InstitutionNumber = @InstNoCode )
      and ( IsSubmited = 1 )
      and ( IsCorrected = 2)
      and ( IsDeleted in (1, 3) )
    if @Count is null set @Count = 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  procedure [SU_CheckUnSubmitedAdmission]
    @AppID  int, @InstitutionNumber int, @DateFrom varchar(10), @DateTo varchar(10)
as
if @AppID = 470
    select ChartNumber, m.AdmitDate
    from crs_demographic m inner join
    (select distinct linkid
    from crs_demographic demo
    where (case when AA8 in  (14507,14508,14509) then dischargedate
                when AA8 = 14510 then AB1b
                when AA8 <> 14501 then A3 end) between @DateFrom and @DateTo and isvalidated in (3, 4)) d
        on m.AbstractID = d.linkid
    where InstitutionNumber = @InstitutionNumber and m.admitdate < @DateFrom and m.IsSubmited <> 1
else if @AppID = 250
    select ChartNumber, m.AdmitDate
    from rh_clientinfo m inner join
    (select distinct linkid
    from rh_clientinfo demo
    where (case when AssessmentType = 135 then dischargedate
                when AssessmentType = 136 then followupdate
           end) between @DateFrom and @DateTo and isvalidated in (3, 4)) d
        on m.AbstractID = d.linkid
    where InstitutionNumber = @InstitutionNumber and m.admitdate < @DateFrom and m.IsSubmited <> 1
else if @AppID = 650
    select ChartNumber, m.AdmitDate
    from OMHRS_SecAA m 
    inner join OMHRS_SecA a on m.AbstractID = a.AbstractID
    inner join OMHRS_RecInfo r on m.AbstractID = r.AbstractID 
    inner join (select distinct linkid
		from OMHRS_SecAA aa
		inner join OMHRS_SecA a on aa.AbstractID = a.AbstractID
		inner join OMHRS_RecInfo b on aa.AbstractID = b.AbstractID
		where A1 between @DateFrom and @DateTo and isvalidated in (3, 4)) d
    on m.AbstractID = d.linkid
    where InstitutionNumber = @InstitutionNumber and m.admitdate < @DateFrom and r.IsSubmited <> 1
    and a.A1 not between @DateFrom and @DateTo --PR - 04342

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create  procedure [SU_CheckUnSubmitedAdmissionIAR]
    @AppID  int, @InstitutionNumber int, @DateFrom varchar(10), @DateTo varchar(10)
as
--IAR for CCRS is future project
--if @AppID = 470
--    select ChartNumber, m.AdmitDate
--    from crs_demographic m inner join
--    (select distinct linkid
--    from crs_demographic demo
--    where (case when AA8 in  (14507,14508,14509) then dischargedate
--                when AA8 = 14510 then AB1b
--                when AA8 <> 14501 then A3 end) between @DateFrom and @DateTo and isvalidated in (3, 4)) d
--        on m.AbstractID = d.linkid
--    where InstitutionNumber = @InstitutionNumber and m.admitdate < @DateFrom and m.IsSubmited <> 1
--else if @AppID = 250
--    select ChartNumber, m.AdmitDate
--    from rh_clientinfo m inner join
--    (select distinct linkid
--    from rh_clientinfo demo
--    where (case when AssessmentType = 135 then dischargedate
--                when AssessmentType = 136 then followupdate
--           end) between @DateFrom and @DateTo and isvalidated in (3, 4)) d
--        on m.AbstractID = d.linkid
--    where InstitutionNumber = @InstitutionNumber and m.admitdate < @DateFrom and m.IsSubmited <> 1
--else 
if @AppID = 650
    select ChartNumber, m.AdmitDate
    from OMHRS_SecAA m 
    inner join OMHRS_SecA a on m.AbstractID = a.AbstractID
    inner join dbo.OMHRS_IAR_CCIM r on m.AbstractID = r.AbstractID 
    inner join (select distinct linkid
		from OMHRS_SecAA aa
		inner join OMHRS_SecA a on aa.AbstractID = a.AbstractID
		inner join OMHRS_RecInfo b on aa.AbstractID = b.AbstractID
		inner join dbo.OMHRS_IAR_CCIM c on aa.AbstractID = c.AbstractID
		where A1 between @DateFrom and @DateTo and isvalidated in (3, 4)
		    and isnull(c.IAR_CCIM_IsSubmitted, 0) in (0, 302151) ) d
    on m.AbstractID = d.linkid
    where InstitutionNumber = @InstitutionNumber and m.admitdate < @DateFrom and isnull(r.IAR_CCIM_IsSubmitted, 0) in (0, 302151)
    and a.A1 not between @DateFrom and @DateTo --PR - 04342


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [SU_CIHI_Batch_Initialize]
    @SU_Type      int,
    @DateFr       varchar(10),
    @DateTo       varchar(10),
    @InstNoCode   int,
    @BatchYear    int,
    @IsSubmitOnly    int,
    @IsCompletedOnly int,

    @RecordCount  int output,
    @RecordWidth  int output,
    @ExecutionID  int output,
    @NameOfFile   varchar(50),
    @CoderNumber  int = 999999
as

-- eSU_MOHLTC_RPC_BILLING_DAD   = 38  
-- eSU_MOHLTC_RPC_BILLING_NACRS = 39

declare @AbstractNumber int

declare 
    @SU_Const varchar(20),
    @GroupID  int,
    @ProvCode int,
    @DateSent datetime,
    @ICDType  char(1),
    @AppID    int,
    @CareType int,
    @SequenceNumber int

declare @InstNoCIHI varchar(10)
declare @BatPerCIHI varchar(10)
declare @ProvNoCIHI varchar(10)
declare @IsUseMentalHealth int

declare @MaxSubmit_ID int

declare @Sql varchar(2000)
declare @where varchar(2000)

select @SU_Const = su_const from SU_StructureType where su_id = @SU_Type
select top 1 @ProvCode = ProvinceNumber from H_HospitalProfile
select @ProvNoCIHI = CIHIValue from LU_Province where Code = @ProvCode
select @CareType = AssociationID from H_InstitutionProfile where Code = @InstNoCode


set @AppID = 
    case @SU_Const
        when 'DAD_I10_Batch' then case @CareType when 1 then 201 else 202 end
        when 'NAC_I10_Batch' then 401
    end

set @GroupID = dbo.SUF_GET_GroupID(@SU_Type, @AppID, @BatchYear, 0, 3)  --Ontario use only by now

set @ICDType = 'T'

--declare @Records table ( AbstractID int, OrderBy int identity(1,1) )

Create table #Records( AbstractID int, VisitDate datetime, ChartNumber varchar(20), OrderBy int identity(1,1) )

--
-- IF THE HOSPITAL IS ALBERTA THEN THE BATCH YEAR NEEDS TO BE INCREMENTED BY ONE.
--
if exists (select * from H_HospitalProfile where ProvinceNumber = 13) begin
    set @BatchYear = str( cast(@BatchYear as int) + 1, 4 )
end

set @DateSent = GetDate()

-- get a list of AbstractID's that will be used to creat the submission file

------------------------------------------------------------------------------------


if @SU_Const = 'DAD_I10_Batch'
    insert into #Records(AbstractID, VisitDate, ChartNumber)
    select AbstractID, DischargeDate, ChartNumber 
    from dbo.AB_Abstract 
    where DischargeDate between @DateFr and @DateTo and InstitutionNumber = @InstNoCode
        and (@IsSubmitOnly = 0 or (@IsSubmitOnly = 1 and IsSubmited = 1))
        and (@IsCompletedOnly = 0 or (@IsCompletedOnly = 1 and IsCompleted in (3, 4)))
    order by DischargeDate, DischargeTime, ChartNumber
else
    insert into #Records(AbstractID, VisitDate, ChartNumber)
    select AbstractID, DischargeDate, ChartNumber 
    from dbo.AB_Abstract 
    where AdmitDate between @DateFr and @DateTo and InstitutionNumber = @InstNoCode
        and (@IsSubmitOnly = 0 or (@IsSubmitOnly = 1 and IsSubmited = 1))
        and (@IsCompletedOnly = 0 or (@IsCompletedOnly = 1 and IsCompleted in (3, 4)))
    order by AdmitDate, AdmitTime, ChartNumber

insert SU_ExecProperties 
       ( ExecutionDate, GroupID,  CoderNumber,  DateStart, DateEnd, InstNoCode,  BatchYear,  BatchPeriod,  IsCorrection,  IsResubmit, BatchStart, BatchCount) 
values ( @DateSent,     @GroupID, @CoderNumber, @DateFr,   @DateTo, @InstNoCode, 0, 0, 0, 0, 0, 0 )

set @ExecutionID = @@identity

delete SU_RecordSelect where ExecutionID = @ExecutionID

insert SU_RecordSelect (          ExecutionID  , 
    AbstractID   , 
    OrderBy      , 
    IsCorrected  , 
    IsSubmited   , 
    IsValidated  , 
    IsCompleted  , 
    IsDeleted    , 
    CIHIDateSent , 
    BatchYear    , 
    BatchPeriod  , 
    BatchNumber  , 
    AbstractNumber )
select 
    @ExecutionID   , 
    r.AbstractID   , 
    r.OrderBy      ,
    a.IsReciprocalBilling,
    a.IsReciprocalBilling,
    a.IsValidated  ,
    a.IsCompleted  ,
    a.IsDeleted    ,
    @DateSent      ,
    a.BatchYear    ,
    a.BatchPeriod  ,
    a.BatchNumber  ,
    a.AbstractNumber
from #Records r 
    join AB_Abstract a on r.AbstractID = a.AbstractID
order by OrderBy
    
-- set the total number of records: 
set @RecordCount = @@rowcount
drop table #Records

declare @BatchStart int

set @BatchStart = 1


DBCC DBREINDEX (SU_RecordSelect)

select @RecordWidth = sum( TextLength ) from SU_StructureFile where GroupID = @GroupID
select @InstNoCIHI = CIHIValue from H_InstitutionProfile where Code = @InstNoCode

set @BatPerCIHI = '0'

select @IsUseMentalHealth = UseMentalHealthData from H_InstitutionProfile where Code = @InstNoCode

-- UPDATE THE EXECUTION PROPERTIES TABLE WITH THE VARIOUS VALUES
update SU_ExecProperties
set ICDType     = @ICDType    ,
    AppID       = @AppID      ,
    RecordCount = @RecordCount,
    BatchStart  = @BatchStart,
    RecordWidth = @RecordWidth,
    ProvNoCIHI  = @ProvNoCIHI ,
    InstNoCIHI  = @InstNoCIHI ,     
    BatPerCIHI  = @BatPerCIHI,
    IsUseMentalHealth = @IsUseMentalHealth,
    NameOfFile  = @NameOfFile
where ExecutionID = @ExecutionID

EXIT_PROCEDURE_NORMAL:
    return 0

ERROR___:
    return 1













GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [SU_CIHI_Batch_Terminate]
    @ExecutionID int,
    @IsTerminateWithError int
as
declare @cur cursor 
declare @sql nvarchar(200)

declare @coder int

-- update the Execution Properties table with the completion status.
update SU_ExecProperties 
set TerminateSuccess = case @IsTerminateWithError when 0 then 1 else 0 end
where ExecutionID = @ExecutionID

select @coder = CoderNumber from SU_ExecProperties where ExecutionID = @ExecutionID

update AB_Abstract 
set TSIDate = getdate()
  , TSITime = getdate()
  , TSICoder = @coder
from AB_Abstract a join SU_RecordSelect s on a.AbstractID = s.AbstractID 
where s.ExecutionID = @ExecutionID

-- After all is said and done, do some basic clean up.
delete from SU_RecordSelect   where ExecutionID = @ExecutionID
delete from SU_QueryStatement where ExecutionID = @ExecutionID


declare @oldExecIDs table ( ExecutionID int )

insert @oldExecIDs ( ExecutionID ) 
select ExecutionID 
from SU_ExecProperties
where datediff( day, ExecutionDate, getdate() ) > 1


delete SU_RecordSelect
from SU_RecordSelect r 
join @oldExecIDs x on r.ExecutionID = x.ExecutionID

delete SU_QueryStatement
from SU_QueryStatement r 
join @oldExecIDs x on r.ExecutionID = x.ExecutionID

delete SU_Record_Submited_OMH_Order
from SU_Record_Submited_OMH_Order r 
join @oldExecIDs x on r.ExecutionID = x.ExecutionID

delete SU_Record_Submited_IAR_MH_Order
from SU_Record_Submited_OMH_Order r 
join @oldExecIDs x on r.ExecutionID = x.ExecutionID


-- add code for temp table clean up.
-- drops any submission table greater than 1 hour old

set @cur = cursor local fast_forward for
    select sql = N'drop table ' + i.table_name
    from SU_ExecProperties t join (

        select table_name, ExecutionID = cast(substring(table_name, 3, patindex('%[0-9][A-Z]%', table_name)-2) as int)
        from information_schema.tables 
        where table_name like 'SU[0-9]%'
        and isnumeric(substring(table_name, 3, patindex('%[0-9][A-Z]%', table_name)-2)) = 1

    ) i on  t.ExecutionID = i.ExecutionID
    where datediff( hour, ExecutionDate, getdate() ) > 1

open @cur

while (1=1) begin

    fetch next from @cur into @sql
    if (@@fetch_status <> 0) break

    exec sp_executesql @sql
end

close @cur
deallocate @cur


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [SU_CIHIError_GetAbstractID]
    @FiscalYear varchar(4),
    @FiscalPeriod varchar(2),
    @BatchNumber varchar(2),
    @AbstractNumber varchar(3),
    @Institution varchar(12),
    @AbstractID int output
as

set @AbstractID = -1

select @AbstractID = AbstractID 
from AB_Abstract AB 
    inner join LU_BatchPeriod LU on AB.BatchPeriod = LU.Code
    inner join H_InstitutionProfile H on Ab.InstitutionNumber = H.Code
where AbstractNumber = cast(@AbstractNumber as int)
and BatchYear = cast(@FiscalYear as int)
and BatchNumber = cast(@BatchNumber as int)
and cast(LU.CIHIValue as int) = cast(@FiscalPeriod as int)
and @Institution = H.CIHIValue

set @AbstractID = isnull(@AbstractID, -1)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


Create procedure [SU_CIHIError_ProcessError]
    @AbstractID int,
    @ImportDateTime datetime
as

--According MSN with Sandra at 2005/04/29 2:50
--When the user physically goes into the abstract and saves the change.
--When CIHI file is loaded, the flag does not change.
--Only when the user correct the abstract and saves it, that's when it changes to P.

--     update AB_Abstract 
--     set IsSubmited = 1, 
--         IsCorrected = 2
--     from AB_Abstract ab
--         inner join dbo.AB_CIHIErrors e on ab.AbstractID = e.AbstractID
--     where ab.AbstractID = @AbstractID and e.ImportDateTime = @ImportDateTime

return 0


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE  procedure [SU_CIHIError_Results]
    @ImportDateTime datetime
as

select 
    [ ] = AbstractID,
    [Facility] = FacilityNumber, 
    [Year] = FiscalYear, 
    [Period] = FiscalPeriod, 
    [Batch #] = BatchNumber, 
    [Abstract #] = AbstractNumber, 
    [Abstract Type] = TypeOfAbstract, 
    [Error Type] = TypeOfError, 
    [Group, Field, Occ] = GroupFieldOcc, 
    [Error #] = ErrorNumber, 
    [Error Msg] = ErrorMessage, 
    [Orig Data] = OriginalData, 
    [Coder #] = CoderNumber, 
    [Discharge Date] = DischargeDate, 
    [Chart #] = ChartNumber
from AB_CIHIErrors 
where ImportDateTime = @ImportDateTime
order by BatchNumber, AbstractNumber





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [SU_CJRR_ControlRecord]
    @ExecutionID int,
    @ControlRecord varchar(234) output
as
begin

select top 1
    @ControlRecord = Replace(NameOfFile, '.txt', '') + right('00000' + cast(RecordCount as varchar(10)), 5) 
from SU_ExecProperties 
where ExecutionID = @ExecutionID

set @ControlRecord = @ControlRecord + space(234 - 22)


end
return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [SU_CJRR_Initialize]
    @SU_Type      int,
    @InstNoCode   int,
    @DateFr       varchar(10),
    @DateTo       varchar(10),
    @BatchYear    int,
    @BatchPeriod  int,
    @IsResubmit   int,
    @CoderNumber  int = 999999,
    @RecordCount  int output,
    @RecordWidth  int output,
    @ExecutionID  int output,
--    @ProvNoCIHI   varchar(1)   output,
--    @InstNoCIHI   varchar(5)   output,
--    @BatPerCIHI   varchar(2)   output,
    @FileName     varchar(50)  output
as

-- 42	CJRR_KNEE
-- 43	CJRR_HIP
--declare 
--    @DateFr varchar(10),
--    @DateTo varchar(10)

--select 
--    @DateFr = dbo.SUF_GetPeriodDateFr( @BatchYear, @BatchPeriod ), 
--    @DateTo = dbo.SUF_GetPeriodDateTo( @BatchYear, @BatchPeriod )

declare @province varchar(10)
declare @ProvNoCIHI   varchar(1)   
declare @InstNoCIHI   varchar(5)   
declare @BatPerCIHI   varchar(2)   


declare 
    @SU_Const varchar(20),
    @GroupID  int,
    @ProvCode int,
    @DateSent datetime,
    @ICDType  char(1),
    @AppID    int
--    @CareType int


select @SU_Const = su_const from SU_StructureType where su_id = @SU_Type
select top 1 @ProvCode = ProvinceNumber from H_HospitalProfile
select @ProvNoCIHI = CIHIValue from LU_Province where Code = @ProvCode
--select @CareType = AssociationID, @NacrsLevelSetting = LevelCode    --, @Level3Date = Level3Date 
--from H_InstitutionProfile where Code = @InstNoCode

set @AppID = 
    case @SU_Const
        when 'CJRR_KNEE' then 40000
        when 'CJRR_HIP'  then 40001
    end

set @GroupID = dbo.SUF_GET_GroupID(@SU_Type, @AppID, @BatchYear, @ProvCode, 0)

set @ICDType = 'T'

declare @Records table ( AbstractID int, OrderBy int identity(1,1) )

--
-- IF THE HOSPITAL IS ALBERTA THEN THE BATCH YEAR NEEDS TO BE INCREMENTED BY ONE.
--
if exists (select * from H_HospitalProfile where ProvinceNumber = 13) begin
    set @BatchYear = str( cast(@BatchYear as int) + 1, 4 )
end

set @DateSent = GetDate()

-- get a list of AbstractID's that will be used to creat the submission file

set @IsResubmit = 0 --PR - 05893 CJRR can clean submission flag. 
------------------------------------------------------------------------------------
if (@SU_Const in ('CJRR_KNEE')) begin

    insert @Records( AbstractID )
        select RecordID
        from dbo.CJRR_Abstract
        where (SurgeryDate between @DateFr and @DateTo) 
          and (InstitutionNumber = @InstNoCode) 
          and RecordType = 300001
          and (IsDeleted = 2) --CJRR does not support deletion
          and (IsSubmited = 2 or (IsSubmited = 1 and IsCorrected = 2))
          and (1 = case 
                when (@IsResubmit = 0 and (IsSubmited <> 1 or IsCorrected = 2 )) then 1 
                when (@IsResubmit = 1) then 1
                else 0 
                end)
          and (IsValidated in (3, 4) or @CoderNumber < 3 or (IsSubmited = 1 and IsDeleted in (1, 3)))
        order by SurgeryDate, ChartNumber  

end

else if (@SU_Const = 'CJRR_HIP') begin
    insert @Records( AbstractID )
        select RecordID
        from dbo.CJRR_Abstract
        where (SurgeryDate between @DateFr and @DateTo) 
          and (InstitutionNumber = @InstNoCode) 
          and RecordType = 300002
          and (IsDeleted = 2) --CJRR does not support deletion
          and (IsSubmited = 2 or (IsSubmited = 1 and IsCorrected = 2))
          and (1 = case 
                when (@IsResubmit = 0 and (IsSubmited <> 1 or IsCorrected = 2 )) then 1 
                when (@IsResubmit = 1) then 1
                else 0 
                end)
          and (IsValidated in (3, 4) or @CoderNumber < 3 or (IsSubmited = 1 and IsDeleted in (1, 3)))
        order by SurgeryDate, ChartNumber  

end



insert SU_ExecProperties 
       ( ExecutionDate, GroupID,  CoderNumber,  DateStart, DateEnd, InstNoCode,  BatchYear,  BatchPeriod,  IsCorrection,  IsResubmit ) 
values ( @DateSent,     @GroupID, @CoderNumber, @DateFr,   @DateTo, @InstNoCode, @BatchYear, @BatchPeriod, 0, @IsResubmit )

set @ExecutionID = @@identity

delete SU_RecordSelect where ExecutionID = @ExecutionID

insert SU_RecordSelect (          ExecutionID  , 
    AbstractID   , 
    OrderBy      , 
    IsCorrected  , 
    IsSubmited   , 
    IsValidated  , 
    IsCompleted  , 
    IsDeleted    , 
    CIHIDateSent , 
    --BatchYear    , 
    --BatchPeriod  , 
    BatchNumber  , 
    AbstractNumber )
select 
    @ExecutionID   , 
    r.AbstractID   , 
    r.OrderBy      ,
    a.IsCorrected  ,
    a.IsSubmited   ,
    a.IsValidated  ,
    a.IsCompleted  ,
    a.IsDeleted    ,
    @DateSent      ,
    --a.BatchYear    ,
    --a.BatchPeriod  ,
    BatchNumber = 1 ,
    AbstractNumber = 0
from @Records r join CJRR_Abstract a on r.AbstractID = a.RecordID
order by OrderBy



-- set the total number of records: 
set @RecordCount = @@rowcount


delete from @Records

DBCC DBREINDEX (SU_RecordSelect)



------------------------------------------------------------------------------------

update SU_RecordSelect 
set IsSubmited     = 1, 
    IsCorrected    = 1, 
    IsCompleted    = 4,
    BatchYear      = @BatchYear, 
    BatchPeriod    = @BatchPeriod
from CJRR_Abstract r 
join SU_RecordSelect s on r.RecordID = s.AbstractID and s.ExecutionID = @ExecutionID
where r.IsSubmited = 2 

update SU_RecordSelect 
set IsSubmited   = 1, 
    IsCorrected  = 3, 
    IsCompleted  = 4,
    BatchYear    = @BatchYear, 
    BatchPeriod  = @BatchPeriod
from CJRR_Abstract r 
join SU_RecordSelect s on r.RecordID = s.AbstractID and s.ExecutionID = @ExecutionID
where r.IsCorrected = 2


update CJRR_Abstract 
set recordsubmitobjective = 300032
from CJRR_Abstract r 
join SU_RecordSelect s on r.RecordID = s.AbstractID and s.ExecutionID = @ExecutionID
where r.IsCorrected = 2 and r.recordsubmitobjective = 300031


------------------------------------------------------------------------------------
select @RecordWidth = sum( TextLength ) from SU_StructureFile where GroupID = @GroupID
select @InstNoCIHI = CIHIValue from H_InstitutionProfile where Code = @InstNoCode
--Hack, How about for BC: Rehab and CCRS
if exists ( select * from H_HospitalProfile where ProvinceNumber <> 14 ) and 
    @BatchPeriod in (15401,15402,15403,15404,15405,15651,15652,15653,
        15654,15655,15656,15657,15658,15659,15660,15661,15662)
    select @BatPerCIHI = CIHIValue from LU_CodeFile where Code = @BatchPeriod
else
    select @BatPerCIHI = CIHIValue from LU_BatchPeriod where Code = @BatchPeriod


-----------------------------------------------------------------------------------
-- UPDATE THE EXECUTION PROPERTIES TABLE WITH THE VARIOUS VALUES
update SU_ExecProperties
set ICDType     = @ICDType    ,
    AppID       = @AppID      ,
    BatchStart  = 1 ,
    BatchCount  = 1 ,
    RecordCount = @RecordCount,
    RecordWidth = @RecordWidth,
    ProvNoCIHI  = @ProvNoCIHI ,
    InstNoCIHI  = @InstNoCIHI ,    
    BatPerCIHI  = @BatPerCIHI ,
    IsUseMentalHealth = 0,
    NacrsLevelCode = 0,
    Su_Type = @Su_Type
where ExecutionID = @ExecutionID

set @FileName = dbo.SU_FILENAME_CJRR( @ExecutionID, @SU_Const )

update SU_ExecProperties
set NameOfFile  = @FileName
where ExecutionID = @ExecutionID



EXIT_PROCEDURE_NORMAL:
    return 0

ERROR___:
    return 1

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [SU_CreateTempTable]
    @ExecutionID int,
    @SourceTable varchar(50),
    @TargetTable varchar(50),
    @IsDropOnly  bit = 0
as

declare @sql nvarchar(500)
declare @IndexField nvarchar(50)
declare @CareType nvarchar(100)	--ED - 02385
declare @AppID int --ED - 02385

declare @IndexTable table
(
    SourceTable varchar(50),
    IndexField nvarchar(50)
)

insert @IndexTable ( SourceTable, IndexField ) values ( 'AB_Diagnosis'      , 'DiagnosisOccurrence' )
insert @IndexTable ( SourceTable, IndexField ) values ( 'AB_Diagnosis'      , 'DiagnosisCode'       )
insert @IndexTable ( SourceTable, IndexField ) values ( 'AB_Intervention'   , 'IntervOccurrence'    )
insert @IndexTable ( SourceTable, IndexField ) values ( 'AB_Intervention'   , 'IntervCode'          )
insert @IndexTable ( SourceTable, IndexField ) values ( 'AB_MIS'            , 'MISOccurrence'       )
insert @IndexTable ( SourceTable, IndexField ) values ( 'AB_PatientService' , 'ServiceOccurrence'   )
insert @IndexTable ( SourceTable, IndexField ) values ( 'AB_Project'        , 'ProjectOccurrence'   )
insert @IndexTable ( SourceTable, IndexField ) values ( 'AB_Provider'       , 'ProviderOccurrence'  )
insert @IndexTable ( SourceTable, IndexField ) values ( 'AB_SpecialCareUnit', 'SCUOccurrence'       )
insert @IndexTable ( SourceTable, IndexField ) values ( 'CRS_Signature'     , 'ProviderOccurrence'  )
insert @IndexTable ( SourceTable, IndexField ) values ( 'AB_SpecialProjects', 'OccurrenceNumber'  )

--ED - 02385
if (@SourceTable = 'AB_SpecialProjects')
begin
	set @AppID = (select AppID from dbo.SU_ExecProperties where ExecutionID = @ExecutionID)
	set @CareType = (case when @AppID = 201 then '1'
						  when @AppID = 202 then '2'
						  when @AppID between 250 and 253 then '3'
						  when @AppID between 470 and 479 then '4'
						  when @AppID = 401 then '5'
						  when @AppID between 650 and 659 then '7'
						  when @AppID between 40000 and 40001 then '9'
						  else '0' end)
   						  
end
else 
	set @CareType = ''


-- if ((select object_id(N'tempdb..##BO1AB_Abstract')) is not null) drop table ##BO1AB_Abstract 
set @sql = N'if ((select object_id( N''' + @TargetTable + ''' )) is not null) drop table ' + @TargetTable 
exec sp_executesql @sql
print @sql

if (@IsDropOnly = 0) begin 
    
    --ED - 02444
    if @SourceTable like 'CJRR%'
    begin
        -- select a.* into ##BO1AB_Abstract 
        -- from SU_RecordSelect s join AB_Abstract a on s.AbstractID = a.AbstractID 
        -- where s.ExecutionID = @ExecutionID 
        --ED - 02385
        set @sql = N'' + 
            'select AbstractID = a.RecordID, a.* into ' + @TargetTable + ' ' + 
            'from SU_RecordSelect b join ' + @SourceTable + ' a on b.AbstractID = a.RecordID ' + 
            'where b.ExecutionID = ' + convert( nvarchar(10), @ExecutionID )
        exec sp_executesql @sql
        print @sql

        -- create index tmpIDX_BO1AB_Abstract_AbstractID on ##BO1AB_Abstract ( AbstractID ) 
        set @sql = N'create index tmpIDX_' + @TargetTable + '_AbstractID on ' + @TargetTable + ' ( AbstractID ) '
        exec sp_executesql @sql
        print @sql
    end
    else
    begin
        -- select a.* into ##BO1AB_Abstract 
        -- from SU_RecordSelect s join AB_Abstract a on s.AbstractID = a.AbstractID 
        -- where s.ExecutionID = @ExecutionID 
        --ED - 02385
        set @sql = N'' + 
            'select a.* into ' + @TargetTable + ' ' + 
            'from SU_RecordSelect b join ' + @SourceTable + ' a on b.AbstractID = a.AbstractID ' + (case when @CareType = '' then '' else ' and a.CareType = ''' + @CareType + ''' ' end) + 
            'where b.ExecutionID = ' + convert( nvarchar(10), @ExecutionID )
        exec sp_executesql @sql
        print @sql

        -- create index tmpIDX_BO1AB_Abstract_AbstractID on ##BO1AB_Abstract ( AbstractID ) 
        set @sql = N'create index tmpIDX_' + @TargetTable + '_AbstractID on ' + @TargetTable + ' ( AbstractID ) '
        exec sp_executesql @sql
        print @sql
    end
    -- apply important indexes
    declare cur cursor local fast_forward for 
        select IndexField 
        from @IndexTable
        where SourceTable = @SourceTable

    open cur 

    while (1=1) begin
        fetch next from cur into @IndexField
        if (@@fetch_status <> 0) break
        
        set @sql = N'create index tmpIDX_' + @TargetTable  + '_' + @IndexField + ' on ' + @TargetTable + ' ( ' + @IndexField + ' ) '
        exec sp_executesql @sql
        print @sql
    end

    close cur
    deallocate cur
end
return 0




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


--ticket 10222, Add log from Inpatient Separate file form
CREATE  procedure [SU_DADSeparateSubmission]
    @SU_Type      int,
    @InstNoCIHI   varchar(5),
    @BatchYear    int,
    @BatchPeriod  int,
    @CoderNumber  int = 999999, 
    @NameOfFile   varchar(250),
    @ExecutionID  int output
as

-- eSU_DAD_I10_SUBMIT = 1  

declare 
    @BatchNumber int,
    @DateFr varchar(10),
    @DateTo varchar(10),
    @InstNoCode int,
    @BatPerCIHI varchar(2), 
    @BatchStart int,
    @ProvNoCIHI varchar(1)

set @BatchNumber = @BatchPeriod
set @BatPerCIHI = right('00' + cast(@BatchPeriod as varchar(2)), 2)

set @DateFr = cast( cast(@BatchYear as varchar(4)) + '/04/01' as datetime)
set @DateTo = cast( cast(@BatchYear + 1 as varchar(4)) + '/03/31' as datetime)


if exists ( select * from H_HospitalProfile where ProvinceNumber = 14 ) begin
    set @BatchPeriod = (select top 1 code from LU_BatchPeriod 
            where CIHIValue = @BatPerCIHI 
                and CIHIDateFrom between @DateFr and @DateTo
                and CIHIDateTo between @DateFr and @DateTo)
end

select 
    @DateFr = dbo.SUF_GetPeriodDateFr( @BatchYear, @BatchPeriod ), 
    @DateTo = dbo.SUF_GetPeriodDateTo( @BatchYear, @BatchPeriod )

set @InstNoCode = (select top 1 code from H_InstitutionProfile 
                   where CIHIValue = @InstNoCIHI 
                       and associationid in (1, 2)
                       and @DateFr between ValidFrom and ValidTo
                       and @DateTo between ValidFrom and ValidTo )

declare 
    @SU_Const varchar(20),
    @GroupID  int,
    @ProvCode int,
    @DateSent datetime,
    @ICDType  char(1),
    @AppID    int,
    @CareType int

select @SU_Const = su_const from SU_StructureType where su_id = @SU_Type
select @ProvCode = ProvinceNumber from H_HospitalProfile
select @CareType = AssociationID from H_InstitutionProfile where Code = @InstNoCode

set @AppID = 201
set @ICDType = 'T'

set @GroupID = dbo.SUF_GET_GroupID(@SU_Type, @AppID, @BatchYear, @ProvCode, 0)

-- IF THE HOSPITAL IS ALBERTA THEN THE BATCH YEAR NEEDS TO BE INCREMENTED BY ONE.
--
if exists (select * from H_HospitalProfile where ProvinceNumber = 13) begin
    set @BatchYear = @BatchYear + 1
end

set @DateSent = GetDate()
set @BatchStart = 1
select @ProvNoCIHI = CIHIValue from LU_Province where Code = @ProvCode
select @InstNoCIHI = CIHIValue from H_InstitutionProfile where Code = @InstNoCode

set @ExecutionID = isnull((select top 1 ExecutionID from SU_ExecProperties 
                    where GroupID = @GroupID 
                        and InstNoCode = @InstNoCode
                        and BatchYear = @BatchYear 
                        and BatchPeriod = @BatchPeriod
                        and BatchStart = 1), 0)
if isnull(@InstNoCode, 0) > 0
begin
    if @ExecutionID = 0 
    begin
        insert SU_ExecProperties 
               ( ExecutionDate, GroupID,  CoderNumber,  DateStart, DateEnd, InstNoCode,  BatchYear,  
                 BatchPeriod, BatchStart,  NameOfFile,  InstNoCIHI,  ICDType,   AppID, 
                 ProvNoCIHI,  BatPerCIHI,  BatchCount, RecordCount, 
                IsCorrection, IsResubmit, TerminateSuccess ) 
        values ( @DateSent,     @GroupID, @CoderNumber, @DateFr,   @DateTo, @InstNoCode, @BatchYear, 
                @BatchPeriod, @BatchStart, @NameOfFile, @InstNoCIHI, @ICDType,  @AppID, 
                 @ProvNoCIHI, @BatPerCIHI, 1, 1, 
                0, 0, 1 )
    
        set @ExecutionID = @@identity
    end
    else
    begin
        Update SU_ExecProperties
        set CoderNumber = @CoderNumber, 
            NameOfFile = @NameOfFile,
            ExecutionDate = @DateSent
        where ExecutionID = @ExecutionID
    end
    --Ticket 11540 Increase the batch period
    set @BatchNumber = @BatchNumber + 1 
    if exists ( select * from H_HospitalProfile where ProvinceNumber = 14 ) begin
         if @BatchNumber = 14 begin
            set @BatchNumber = 1
            set @BatchYear = @BatchYear + 1
            set @DateFr = cast( cast(@BatchYear as varchar(4)) + '/04/01' as datetime)
            set @DateTo = cast( cast(@BatchYear + 1 as varchar(4)) + '/03/31' as datetime)
        end
        set @BatPerCIHI = right('00' + cast(@BatchNumber as varchar(2)), 2)
        set @BatchPeriod = (select top 1 code from LU_BatchPeriod 
                where CIHIValue = @BatPerCIHI 
                    and CIHIDateFrom between @DateFr and @DateTo
                    and CIHIDateTo between @DateFr and @DateTo)
    end
    else begin
        if @BatchNumber = 13 begin
            set @BatchNumber = 1
            set @BatchYear = @BatchYear + 1
        end
        set @BatchPeriod = @BatchNumber
    end
    exec dbo.U_H_InstProfPostSubmit @InstNoCode, @BatchYear, @BatchPeriod
    -- end ticket 11540
end

EXIT_PROCEDURE_NORMAL:
    return 0



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  procedure [SU_GetBatchHeader]
    @ExecutionID int,
    @param0 varchar(50) = null,
    @param1 varchar(50) = null,
    @param2 varchar(50) = null,
    @BatchHeader varchar(4000) = '' output
as 

declare @SU_const varchar(20)

declare @ExecutionDate datetime
declare @GroupID       int
declare @DateStart     datetime
declare @DateEnd       datetime
declare @InstNoCode    varchar(10)
declare @BatchYear     varchar(4)
declare @BatchPeriod   varchar(10)
declare @IsCorrection  varchar(10)
declare @IsResubmit    varchar(10)
declare @BatchStart    varchar(10)
declare @BatchCount    varchar(10)
declare @RecCount_INT  int
declare @RecCount_CHR  varchar(10)
declare @RecordWidth   varchar(10)
declare @NameOfFile    varchar(250)
declare @ProvNoCIHI    varchar(1)
declare @InstNoCIHI    varchar(5)
declare @BatPerCIHI    varchar(2)
declare @AppID         int  -- EN - 00393
declare @NacrsLevelCode int -- ED - 01794


-- Carriage Return & Line Feed
declare @CrLf varchar(2)
set @CrLf = char(13) + char(10)

-- retrieve various common properties used 
-- throughout the submission program.
select 
    @AppID         = AppID, -- EN - 00393
    @ExecutionDate = ExecutionDate, 
    @GroupID       = GroupID, 
    @DateStart     = DateStart, 
    @DateEnd       = DateEnd, 
    @InstNoCode    = InstNoCode, 
    @BatchYear     = BatchYear, 
    @BatchPeriod   = BatchPeriod, 
    @IsCorrection  = IsCorrection, 
    @IsResubmit    = IsResubmit, 
    @BatchStart    = BatchStart, 
    @BatchCount    = BatchCount, 
    @RecCount_INT  = RecordCount, 
    @RecCount_CHR  = RecordCount, 
    @RecordWidth   = RecordWidth, 
    @NameOfFile    = NameOfFile, 
    @ProvNoCIHI    = ProvNoCIHI, 
    @InstNoCIHI    = InstNoCIHI, 
    @BatPerCIHI    = BatPerCIHI,
    @NacrsLevelCode = NacrsLevelCode
from SU_ExecProperties 
where ExecutionID = @ExecutionID


/** SUBMISSION CONSTANTS/ENUMS
    1	DAD_I10_SUBMIT
    2	DAD_I10_DELETE
    3	DAD_I9C_SUBMIT
    4	NAC_I10_SUBMIT
    5	NAC_I9C_SUBMIT
    6	NRS_DELETIONS
    7	NRS_ADMISSION
    8	NRS_DISCHARGE
    9	NRS_FOLLOW_UP
    10	CRS_ASSESS_QURT
    11	CRS_ASSESS_FULL
    12	CRS_ASSESS_DSCH
    13	CRS_ASSESS_ADMT
    14	CRS_ASSESS_RNTR
    15	CRS_ASSESS_MAST
    16	CRS_ASSESS_MEDI
    17	CRS_ASSESS_DEMO
  *
  **/


--select * from LU_Province

if @ProvNoCIHI = '8'
    select @SU_const = SU_Const 
    from SU_StructureType 
    where su_id in (
        select distinct SU_Type 
        from SU_StructureList 
        where GroupID = @GroupID and batchyear = (@BatchYear - 1) and SU_Type not in (38, 39, 40, 41))
else if @AppID in (250, 251, 252)   --EN - 00393
    select @SU_const = SU_Const 
    from SU_StructureType 
    where su_id in (
        select distinct SU_Type 
        from SU_StructureList 
        where GroupID = @GroupID)
else
    select @SU_const = SU_Const 
    from SU_StructureType 
    where su_id in (
        select distinct SU_Type 
        from SU_StructureList 
        where GroupID = @GroupID and batchyear = @BatchYear and SU_Type not in (38, 39, 40, 41))
-- SU_Type 38, 39 is for billing. The billing use the same format with DAD & NACRS.


-- branch off to the section which 
-- corresponds to the GroupID
if (@SU_const in ('DAD_I10_SUBMIT',
                  'DAD_I10_DELETE',
                  'MADE_I10_SUBMIT',
                  'MADE_I10_DELETE')) 

    goto DAD_ICD_10_BatchHeader

else 
if (@SU_const in ('DAD_I9C_SUBMIT')) 
    goto DAD_ICD_9_CM_BatchHeader

else 
if (@SU_const in ('NAC_I10_SUBMIT', 'NAC_CJRR_SUBMIT') ) 

    if (@ProvNoCIHI = '8' and @BatchYear = '2004')
        goto NACRS_ICD_10_BatchHeader_ALBERTA_2004

    else
    if (@ProvNoCIHI = '8')
        goto NACRS_ICD_10_BatchHeader_ALBERTA

    else
        goto NACRS_ICD_10_BatchHeader

else 
if (@SU_const in ('NAC_I9C_SUBMIT')) 

    if (@ProvNoCIHI = '8')
        goto NACRS_ICD_9_CM_BatchHeader_ALBERTA

    else
        goto NACRS_ICD_9_CM_BatchHeader

else 
if (@SU_const in ('NRS_FOLLOW_UP')) 
    goto REHAB_ICD_10_BatchHeader

else goto EXIT_STORED_PROCEDURE


/******************************************************************************* 
******************************************************************************** 
**** ASSEMBLE AND RETURN BATCH HEADER/FOOTER INFORMATION: 
********************************************************************************
*******************************************************************************/

declare 
    @WinRecsVersion char(8),
    @Version char(3),
    @BatchNumber varchar(6), 
    @AbstractCount varchar(3), 
    @BatchType varchar(1), 
    @CIHIDateSent varchar(8), 
    @ClosePeriod varchar(1)


--___________________________________________________________________________________________________________________________________________________________
--===========================================================================================================================================================
DAD_ICD_10_BatchHeader:

        
        if (@ProvNoCIHI <> '8') begin
        /*******************************
          * FOR NON ALBERTA SUBMISSION
          *
          */

        /** @param0 = Batch Number [99]
          * @param1 = Abstract Count [999]
          * @param2 = Is Last Batch [<true>, <false>]
          */
            set @BatchNumber   = replicate('0', 2-len(@param0)) + @param0
            set @AbstractCount = replicate('0', 3-len(@param1)) + @param1
            set @RecCount_CHR  = replicate('0', 3-len(@RecCount_CHR)) + @RecCount_CHR
    
            if (@SU_const in ('DAD_I10_DELETE', 'MADE_I10_DELETE')) 
                set @BatchType = 'D' 
            else    --PR - 03038
                set @BatchType = case when (@IsCorrection = 1) then 'C' when (@param2 in ('True', 'Vrai', '1')) then 'B' else 'A' end 
    
            set @CIHIDateSent  = convert(varchar(8), @ExecutionDate, 112)
        
            set @BatchHeader = @InstNoCIHI + @BatchYear 
        
            -- Submission specific info
            if (@IsCorrection = 0)
                set @BatchHeader = @BatchHeader + @BatPerCIHI + @BatchNumber + '000L' + @AbstractCount
        
            -- Correction specific info
            else if (@IsCorrection = 1)
                set @BatchHeader = @BatchHeader + '0000000L' + @RecCount_CHR
        
    
            set @BatchHeader = @BatchHeader + @BatchType + @CIHIDateSent --+ space(2471)
    
            --Ticket: 11539 Reference 9260
            if (@SU_const in ('MADE_I10_SUBMIT', 'MADE_I10_DELETE')) begin
                
                if @BatchYear < 2012
                begin
                    select @WinRecsVersion = left(replace(replace(Version, '.', ''), '_', '') + '000000', 6)
                    from M_Version
                    set @BatchHeader = @BatchHeader + @WinRecsVersion + space(965)
                end
                else --ED - 02763
                begin
                    select @WinRecsVersion = left(replace(replace(Version, '.', ''), '_', '') + '00000000', 8)
                    from M_Version
                    set @BatchHeader = @BatchHeader + @WinRecsVersion + '01' + space(965)
                end                    
            end
            -- ED - 01201 Header size changed. 
            else if @BatchYear < 2007
                set @BatchHeader = @BatchHeader + space(2471)
            else if @BatchYear < 2014 
                set @BatchHeader = @BatchHeader + space(2771)
            --ED - 02970 
            else if @BatchYear < 2018
                set @BatchHeader = @BatchHeader + space(3425)
            else
			    set @BatchHeader = @BatchHeader --2.x-0887 OLD SQL does support varchar over 8000 + space(20999)
    
        end
        else begin
        /*******************************
          * FOR ALBERTA MORBIDITY SUBMISSION
          *
            =======================================
            | ELEMENT      | POS | LEN | TYPE     |
            =======================================
            | Version      |   1 |   3 | '001'    |
            |--------------|-----|-----|----------|
            | Inst No      |   4 |   5 | CHAR     |
            |--------------|-----|-----|----------|
            | Batch Year   |   9 |   4 | YYYY     |
            |--------------|-----|-----|----------|
            | Batch Period |  13 |   2 | Numeric  |
            |--------------|-----|-----|----------|
            | Batch Number |  15 |   2 | Numeric  |
            |--------------|-----|-----|----------|
            | Batch ID     |  17 |   3 | Numeric  |
            |--------------|-----|-----|----------|
            | Record ID    |  20 |   1 | CHAR     |
            |--------------|-----|-----|----------|
            | Batch Count  |  21 |   3 | Numeric  |
            |--------------|-----|-----|----------|
            | Batch Type   |  24 |   1 | CHAR     |
            |--------------|-----|-----|----------|
            | Date Submit  |  25 |   8 | YYYYMMDD |
            ======================================= 
        */

    
        /** @param0 = Batch Number [99]
          * @param1 = Abstract Count [999]
          * @param2 = Is Last Batch [<true>, <false>]
          */
          --Alter batch Year is one ahead
            set @Version = case when @BatchYear between '2004' and '2007' then '002' 
                                when @BatchYear between '2008' and '2009' then '003'  
                                when @BatchYear between '2010' and '2012' then '004' --ED - 01908
                                when @BatchYear between '2013' and '2017' then '005' --PR - 05835
                                when @BatchYear = '2018' then '006' --2.x-0798 
                                when @BatchYear = '2019' then '008' --2.x-1040
                                when @BatchYear = '2020' then '009' --2.x-1040
                                when @BatchYear > '2020' then '010' --2.x-1969 
                                else '001' end
            set @BatchYear     = @BatchYear
            set @BatchNumber   = replicate('0', 2-len(@param0)) + @param0
            set @AbstractCount = replicate('0', 3-len(@param1)) + @param1
            set @RecCount_CHR  = replicate('0', 3-len(@RecCount_CHR)) + @RecCount_CHR
    
            set @BatchHeader = @Version + @InstNoCIHI + @BatchYear + @BatPerCIHI + @BatchNumber + '000H' 

            if (@GroupID = 4) or (@GroupID = 18) 
                set @BatchType = 'D' 
            else
                set @BatchType = case when (@IsCorrection = 1) then 'C' else 'A' end 
    
            set @CIHIDateSent  = convert(varchar(8), @ExecutionDate, 112)
        
            set @BatchHeader = @BatchHeader + @AbstractCount + @BatchType + @CIHIDateSent
            --PR - 03843
            if @BatchYear >= '2009' and @BatchYear <= '2017'
                set @BatchHeader = @BatchHeader + space(2768)
            else if @BatchYear = '2018'
                set @BatchHeader = @BatchHeader + space(3422)   --2.x-0798 
            else if @BatchYear = '2019'
                set @BatchHeader = @BatchHeader + space(3438)   --2.x-1482
            else if @BatchYear > '2019'
                set @BatchHeader = @BatchHeader   --2.x-1482    SQL 2000 do not support over 8000 characters.
        end

        goto EXIT_STORED_PROCEDURE

--___________________________________________________________________________________________________________________________________________________________
--===========================================================================================================================================================
DAD_ICD_9_CM_BatchHeader:

        
    /** @param0 = Batch Number [99]
      * @param1 = Abstract Count [999]
      * @param2 = Is Last Batch [<true>, <false>]
      */
    
        set @BatchNumber   = replicate('0', 2-len(@param0)) + @param0
        set @AbstractCount = replicate('0', 3-len(@param1)) + @param1
        set @RecCount_CHR  = replicate('0', 3-len(@RecCount_CHR)) + @RecCount_CHR
        set @BatchType     = case when (@IsCorrection = 1) then 'C' when (@param2 = 'True') then 'B' else 'A' end 
        set @CIHIDateSent  = convert(varchar(8), @ExecutionDate, 112)
    
        set @BatchHeader = @ProvNoCIHI + @InstNoCIHI + @BatchYear 
    
        -- Submission specific info
        if (@IsCorrection = 0)
            set @BatchHeader = @BatchHeader + @BatPerCIHI +  @BatchNumber + '000L' + @AbstractCount 
    
        -- Correction specific info
        else if (@IsCorrection = 1)
            set @BatchHeader = @BatchHeader + '0000000L' + @RecCount_CHR 
    
        set @BatchHeader = @BatchHeader + @BatchType + @CIHIDateSent + space(971)
    
        goto EXIT_STORED_PROCEDURE


--___________________________________________________________________________________________________________________________________________________________
--===========================================================================================================================================================
NACRS_ICD_10_BatchHeader:
        --PR - 04855
        if @NacrsLevelCode = 3 and @BatchYear > 2009 and
            exists (select * from h_institutionprofile where code = @InstNoCode and LevelCode in (4, 5))
        begin
            set @ClosePeriod = 1 --PR - 04855
        end
        else
            set @ClosePeriod  = case when (@RecCount_INT = 0) then '1' else '0' end
        
        set @RecCount_CHR = replicate('0', 6-len(@RecCount_CHR)) + @RecCount_CHR
        set @CIHIDateSent = convert(varchar(8), @ExecutionDate, 112)

        set @BatchHeader = ''
        if @BatchYear < 2009
            set @BatchHeader = '0' + @InstNoCIHI + 'M0004' + @BatPerCIHI + @ClosePeriod + @RecCount_CHR + @CIHIDateSent + space(72)
        else    --ED - 01794
            set @BatchHeader = '0' + @InstNoCIHI + 'M0004' + @BatPerCIHI + @ClosePeriod + @RecCount_CHR + @CIHIDateSent + cast(@NacrsLevelCode as char(1)) + space(71)
        goto EXIT_STORED_PROCEDURE

--___________________________________________________________________________________________________________________________________________________________
--===========================================================================================================================================================
NACRS_ICD_9_CM_BatchHeader:

        set @ClosePeriod  = case when (@RecCount_INT = 0) then '1' else '0' end
        set @RecCount_CHR = replicate('0', 6-len(@RecCount_CHR)) + @RecCount_CHR
        set @CIHIDateSent = convert(varchar(8), @ExecutionDate, 112)
    
        set @BatchHeader = '0' + @ProvNoCIHI + @InstNoCIHI + 'M0002' + @BatPerCIHI + @ClosePeriod + @RecCount_CHR + @CIHIDateSent + space(672)
    
        goto EXIT_STORED_PROCEDURE


--___________________________________________________________________________________________________________________________________________________________
--===========================================================================================================================================================
NACRS_ICD_9_CM_BatchHeader_ALBERTA:


    /** @param0 = Record Type [<header>, <footer>]
      * @param1 = Batch Number [999999]
      */
        declare @SubmitterPrefix varchar(3)
        declare @RecordType varchar(1)
    
        set @SubmitterPrefix = dbo.SUF_GetAlbertaSubmitterPrefix( @InstNoCIHI )    
        set @RecordType  = case @param0 when 'header' then '2' when 'footer' then '4' else '' end
        
        select @BatchNumber = BatchNumber 
        from AB_Abstract 
        where @BatchYear = BatchYear and @BatchPeriod = BatchPeriod and @InstNoCode = InstitutionNumber
        group by BatchNumber 
        

        set @BatchNumber = replicate('0', 6 - len(@param1)) + @param1 
        set @RecCount_CHR = replicate('0', 8 - len(@RecCount_CHR)) + @RecCount_CHR

        set @BatchHeader = @RecordType + @SubmitterPrefix + @BatchNumber
    
        -- File header
        if (@param0 = 'header') begin
    
            set @BatchHeader = 
                @SubmitterPrefix + 'START OF FILE' + @CrLf + 
                @BatchHeader
                
    
        end
        -- File footer
        else if (@param0 = 'footer') begin
    
            set @BatchHeader = 
                @BatchHeader + @RecCount_CHR + @CrLf + 
                @SubmitterPrefix + 'END OF FILE'
    
        end
    
        goto EXIT_STORED_PROCEDURE

--___________________________________________________________________________________________________________________________________________________________
--===========================================================================================================================================================
NACRS_ICD_10_BatchHeader_ALBERTA:


    /*******************************
      * FOR ALBERTA MORBIDITY SUBMISSION
      *
        =======================================
        | ELEMENT      | POS | LEN | TYPE     |
        =======================================
        | Record Type  |   1 |   1 | 'H'      |
        |--------------|-----|-----|----------|
        | Version      |   2 |   3 | 001/003  |
        |--------------|-----|-----|----------|
        | Batch Number |   5 |   6 | Numeric  | * same as sequence number in file name
        |--------------|-----|-----|----------|
        | Record Count |  11 |   8 | Numeric  |
        ======================================= 

        Example:
        H00100000100004200
    **/


    /** @param0 = Batch Number [999999]
      */
        --
        -- GET THE SEQUENCE NUMBER FROM THE FILE NAME: THE LAST 3 DIGITS BEFORE EXTENSION.
        -- A-88035-2003-01-005.txt
        -- 
        set @param0 = right(replace(@NameOfFile, '.txt', ''), 3)
    
        if exists (select * from SU_ExecProperties where ExecutionID = @ExecutionID and BatchYear >= 2006)
            set @BatchHeader = 'H004'
        else if exists (select * from SU_ExecProperties where ExecutionID = @ExecutionID and BatchYear = 2005)
            set @BatchHeader = 'H003'
        else
            set @BatchHeader = 'H001'

        set @BatchHeader = @BatchHeader + replicate('0', 6 - len(@param0)) + @param0 + replicate('0', 8 - len(@RecCount_CHR)) + @RecCount_CHR
                
        goto EXIT_STORED_PROCEDURE

--___________________________________________________________________________________________________________________________________________________________
--===========================================================================================================================================================
NACRS_ICD_10_BatchHeader_ALBERTA_2004:


    /*******************************
      * FOR ALBERTA MORBIDITY SUBMISSION
      *
        =======================================
        | ELEMENT      | POS | LEN | TYPE     |
        =======================================
        | Record Type  |   1 |   1 | 'H'      |
        |--------------|-----|-----|----------|
        | Version      |   2 |   3 | '002'    |
        |--------------|-----|-----|----------|
        | Batch Number |   5 |   6 | Numeric  | * same as sequence number in file name
        |--------------|-----|-----|----------|
        | Record Count |  11 |   8 | Numeric  |
        ======================================= 

        Example:
        H00200000100004200
    **/


    /** @param0 = Batch Number [999999]
      */
        --
        -- GET THE SEQUENCE NUMBER FROM THE FILE NAME: THE LAST 3 DIGITS BEFORE EXTENSION.
        -- A-88035-2003-01-005.txt
        -- 
        set @param0 = right(replace(@NameOfFile, '.txt', ''), 3)
    
        set @BatchHeader = 'H002' + replicate('0', 6 - len(@param0)) + @param0 + replicate('0', 8 - len(@RecCount_CHR)) + @RecCount_CHR
                
        goto EXIT_STORED_PROCEDURE

--___________________________________________________________________________________________________________________________________________________________
--===========================================================================================================================================================
REHAB_ICD_10_BatchHeader:


    /** @param0 = RecordCount
      * @param1 = Is Last File [<true>, <false>]
      * 
      */

        declare @int int

        set @param0 = replicate('0', 6-len(@param0)) + @param0
        set @param1 = case @param1 
            when '<true>'  then '1'
            when '<false>' then '0'
            else '@' end

        if (isnumeric(@BatPerCIHI) = 1) set @int = cast(@BatPerCIHI as int) else set @int = 0
        set @BatPerCIHI = case 
            when @BatchPeriod in (15401, 15651, 15652, 15653) then '1'    --Quarter 1
            when @BatchPeriod in (15402, 15654, 15655, 15656) then '2'    --Quarter 2
            when @BatchPeriod in (15403, 15657, 15658, 15659) then '3'    --Quarter 3
            when @BatchPeriod in (15404, 15660, 15661, 15662) then '4'    --Quarter 4
            when (@int between  1 and  3) then '1'
            when (@int between  4 and  6) then '2'
            when (@int between  7 and  9) then '3'
            when (@int between 10 and 13) then '4'
            else '@' end
        if @BatchYear < '2008'
            set @BatchHeader = '0' + @InstNoCIHI + 'M0002' + @BatchYear + @BatPerCIHI + @param0 + convert(varchar(8), @ExecutionDate, 112) + @param1
        else
            set @BatchHeader = '0' + @InstNoCIHI + 'M0004' + @BatchYear + @BatPerCIHI + @param0 + convert(varchar(8), @ExecutionDate, 112) + @param1

        goto EXIT_STORED_PROCEDURE

--___________________________________________________________________________________________________________________________________________________________
--===========================================================================================================================================================
EXIT_STORED_PROCEDURE:

    if (nullif(@BatchHeader, '') is null)
        return 1
    else 
        return 0


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE procedure [SU_GetFacilityFileStructure]
    @FacilityType int,
    @RecordCount int output
as 

    select GroupID, FacilityType, FieldOrder, FieldName, FieldValue, FieldLength, FieldMask, FieldType, FieldRecode, TextPosition, TextLength, EditType
    from SU_FacilityFile  
    where FacilityType = @FacilityType
    order by FieldOrder 
    
    set @RecordCount = @@rowcount



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE procedure [SU_GetFileName] 
    @ExecutionID int
  , @FileName varchar(250) output
as

declare @SU_Const varchar(20)

declare 
    @ProvCode     int
  , @GroupID      int
  , @InstNoCode   int
  , @IsCorrection int
  , @BatchYear    int
  , @BatchPeriod  int
  , @InstNoCIHI   varchar(5)

declare 
    @f_Prefix varchar(3)
  , @f_BatPr  varchar(2)
  , @f_ProvNo varchar(1)
  , @f_InstNo varchar(5)
  , @f_Extens varchar(4)
  , @f_BatYr  varchar(4)
  , @f_SeqNo  varchar(2)
  , @f_Type   varchar(2)


declare @SequenceNumber int
declare @StartSequence  int
declare @IsDeletion int
declare @NACRSLevelCode int    --ED - 01838

select @ProvCode = ProvinceNumber from H_HospitalProfile

select 
      @GroupID      = GroupID
    , @InstNoCode   = InstNoCode
    , @InstNoCIHI   = InstNoCIHI
    , @IsCorrection = IsCorrection
    , @BatchYear    = BatchYear
    , @BatchPeriod  = BatchPeriod
    , @NACRSLevelCode = NACRSLevelCode
from SU_ExecProperties
where ExecutionID = @ExecutionID

select top 1 @SU_Const = su_const 
from SU_StructureList l join SU_StructureType t on l.SU_Type = t.su_id
where l.GroupID = @GroupID
    and su_const not in ('DAD_I10_Batch', 'NAC_I10_Batch', 'DAD_I10_Billing', 'NAC_I10_Billing') --PR - 04827

--=================================================================================
-- DAD ICD 10 
if (@SU_Const in ('DAD_I10_SUBMIT', 'DAD_I10_DELETE')) begin

    -- NON Alberta 
    if @ProvCode <> 13 begin
    
        select @SequenceNumber = count(*)
        from SU_ExecProperties
        where GroupID      = @GroupID
          and InstNoCode   = @InstNoCode
          and IsCorrection = @IsCorrection
          and BatchYear    = @BatchYear
          and 1 = (case 
            when @IsCorrection = 0 and BatchPeriod = @BatchPeriod then 1 
            when @IsCorrection = 1 then 1
            else 0 end)
--New add for fiscal 2005 to remove sequence not sync
          and 1 = (case when @BatchYear <= 2004 then 1
                        when @BatchYear > 2004 and (TerminateSuccess = 1 or ExecutionID = @ExecutionID) then 1
                        else 0 end)

        set @IsDeletion = (case when @SU_Const = 'DAD_I10_DELETE' then 1 else 0 end)

        set @FileName = dbo.SU_FILENAME_DAD_ICD10 ( @InstNoCode, @BatchYear, @BatchPeriod, @IsCorrection, @IsDeletion, @SequenceNumber )

    end
    else begin -- Alberta 
        --2019/01 Alberta file format: M-FFFFF-YYYY-MM-SSS. No correction and deletion differential. I think we should remove GroupID = @GroupID
        select @SequenceNumber = count(*)
        from SU_ExecProperties
        --where GroupID     = @GroupID
        Where InstNoCode  = @InstNoCode
          and BatchYear   = @BatchYear
          and BatchPeriod = @BatchPeriod

        set @FileName = dbo.SU_FILENAME_MACRS ( @InstNoCode, @BatchYear, @BatchPeriod, @SequenceNumber )

    end
end

--=================================================================================
-- MADE ICD 10 (Manitoba Only)
if (@SU_Const in ('MADE_I10_SUBMIT', 'MADE_I10_DELETE')) begin
    --PR - 06932 to make sure to match DAD CIHI Submission file's sequence
    set @GroupID = (select top 1 GroupID from dbo.SU_StructureList where BatchYear = @BatchYear
        and AppID = 201 and isnull(Province, 0) = 0
        and SU_type = (case when @SU_Const = 'MADE_I10_SUBMIT' then 1 else 2 end))
        
    select @SequenceNumber = count(*)
    from SU_ExecProperties
    where GroupID      = @GroupID
      and InstNoCode   = @InstNoCode
      and IsCorrection = @IsCorrection
      and BatchYear    = @BatchYear
      and 1 = (case 
        when @IsCorrection = 0 and BatchPeriod = @BatchPeriod then 1 
        when @IsCorrection = 1 then 1
        else 0 end)
--New add for fiscal 2005 to remove sequence not sync
      and 1 = (case when @BatchYear <= 2004 then 1
                    when @BatchYear > 2004 and (TerminateSuccess = 1) then 1    ----PR - 06932
                    --when @BatchYear > 2004 and (TerminateSuccess = 1 or ExecutionID = @ExecutionID) then 1
                    else 0 end)

    set @IsDeletion = (case when @SU_Const = 'MADE_I10_DELETE' then 1 else 0 end)

    set @FileName = dbo.SU_FILENAME_MADE_ICD10 ( @InstNoCode, @BatchYear, @BatchPeriod, @IsCorrection, @IsDeletion, @SequenceNumber )
end

--=================================================================================
-- DAD ICD 9CM/9 
else if (@SU_Const = 'DAD_I9C_SUBMIT') begin

    select @f_Prefix = 'P'
    select @f_BatPr  = CIHIValue from LU_BatchPeriod where Code = @BatchPeriod
    select @f_InstNo = CIHIValue from H_InstitutionProfile where Code = @InstNoCode
    select @f_ProvNo = CIHIValue from LU_Province where Code = @ProvCode
    select @f_Extens = case when @IsCorrection = 1 then '.DAC' else '.DAD' end

    select @FileName = @f_Prefix + @f_BatPr + @f_ProvNo + @f_InstNo + @f_Extens

end
--=================================================================================
-- NACRS ICD 10 
else if (@SU_Const in ('NAC_I10_SUBMIT', 'NAC_CJRR_SUBMIT')) begin
	if @BatchYear < 2022
    --PR - 02652 create duplicate sequence file
		select @SequenceNumber = count(*), @StartSequence = min((case when NameOfFile is null or BatchYear < 2006 then 2 when isnumeric(left(right(NameOfFile, 7), 3)) = 1 then cast(left(right(NameOfFile, 7), 3) as int) else 2 end))
		from SU_ExecProperties
		where GroupID     = @GroupID
		  and InstNoCode  = @InstNoCode
		  and BatchYear   = @BatchYear
		  and BatchPeriod = @BatchPeriod
		  and (TerminateSuccess = 1 or ExecutionID = @ExecutionID)  --PR - 05479
	else
	begin
		select @SequenceNumber = count(*), @StartSequence = min((case when NameOfFile is null or BatchYear < 2006 then 2 when isnumeric(left(right(NameOfFile, 7), 3)) = 1 then cast(left(right(NameOfFile, 7), 3) as int) else 2 end))
		from SU_ExecProperties
		where SU_type in (4, 22)	--4 - NACRS 22 - CJRR
		  and InstNoCode  = @InstNoCode
		  and BatchYear   = @BatchYear
		  and BatchPeriod = @BatchPeriod
		  and (TerminateSuccess = 1 or ExecutionID = @ExecutionID)  --PR - 05479
	end
    if isnull(@StartSequence, 1) > 1 and @SequenceNumber > 1 set @SequenceNumber = @SequenceNumber + 1

    if (@ProvCode = 13) -- Alberta Only
        set @FileName = dbo.SU_FILENAME_ACCS ( @InstNoCode, @BatchYear, @BatchPeriod, @SequenceNumber )
    else -- All other provinces
        --PR - 01811 Start at one
        set @FileName = dbo.SU_FILENAME_NACRS ( @InstNoCode, @BatchYear, @BatchPeriod, @SequenceNumber, @NACRSLevelCode ) --@SequenceNumber + 1

end

--=================================================================================
-- NACRS ICD 9/9CM 
else if (@SU_Const = 'NAC_I9C_SUBMIT') begin

    if @ProvCode <> 13 begin

        select @f_Prefix = case when @IsCorrection = 1 then 'N' else 'P' end
        select @f_BatPr  = CIHIValue from LU_BatchPeriod where Code = @BatchPeriod
        select @f_InstNo = CIHIValue from H_InstitutionProfile where Code = @InstNoCode
        select @f_ProvNo = CIHIValue from LU_Province where Code = @ProvCode
        select @f_Extens = case when @IsCorrection = 1 then '.DAC' else '.DAD' end
    
        select @FileName = @f_Prefix + @f_BatPr + @f_ProvNo + @f_InstNo + @f_Extens
    
    end
    else begin

        select @f_Prefix = case when @IsCorrection = 1 then 'N' else 'P' end
        select @f_BatPr  = CIHIValue from LU_BatchPeriod where Code = @BatchPeriod
        select @f_InstNo = CIHIValue from H_InstitutionProfile where Code = @InstNoCode
        select @f_ProvNo = CIHIValue from LU_Province where Code = @ProvCode
        select @f_Extens = case when @IsCorrection = 1 then '.NAC' else '.NAC' end
    
        select @FileName = @f_Prefix + @f_BatPr + @f_ProvNo + @f_InstNo + @f_Extens

    end
end

------------------------------------------------------------------------------------
-- REHAB SUBMISSION, Admission, Discharge, FollowUp
else if (@SU_Const in ('NRS_DELETIONS', 'NRS_ADMISSION', 'NRS_DISCHARGE', 'NRS_FOLLOW_UP')) begin


    set @f_Prefix = 'NRS'
    set @f_BatYr  = @BatchYear
    set @f_InstNo = @InstNoCIHI

-- Ticket 8525
--     set @f_BatPr = case 
--         when (@BatchPeriod between  1 and  3) then '01'
--         when (@BatchPeriod between  4 and  6) then '02'
--         when (@BatchPeriod between  7 and  9) then '03'
--         when (@BatchPeriod between 10 and 12) then '04'
--         else '@@' end

    set @f_BatPr = (case when @BatchPeriod in (15401,15651,15652,15653, 1, 2, 3) then '01'    --Quarter 1
                         when @BatchPeriod in (15402,15654,15655,15656, 4, 5, 6) then '02'    --Quarter 2
                         when @BatchPeriod in (15403,15657,15658,15659, 7, 8, 9) then '03'    --Quarter 3
                         when @BatchPeriod in (15404,15660,15661,15662,10,11,12) then '04'    --Quarter 4
                         when @BatchPeriod in (15405) then '00'    --Full Year
                         else '@@'
                    end)


    -- first gather all periods with like criteria.
    declare @seqTable table 
    (
        BatchPeriod int
    )

    insert @seqTable ( BatchPeriod ) 
    select BatchPeriod
    from SU_ExecProperties
    where --GroupID      = @GroupID        and --EN - 00393
      InstNoCode   = @InstNoCode   
      and IsCorrection = @IsCorrection 
      and BatchYear    = @BatchYear      


    -- if file is a correction, just do a count of all previous files
    if @IsCorrection = 1
        
        select @f_SeqNo = replace(str(count(*), 2) , ' ', '0')
        from @seqTable

    -- otherwise, just do a count of all previous files of the SAME quarter.
    else

-- Ticket 8525
--         select @f_SeqNo = replace(str(count(*), 2) , ' ', '0')
--         from @seqTable
--         where @f_BatPr = 
--         (
--             case
--             when BatchPeriod between  1 and  3 then '01'
--             when BatchPeriod between  4 and  6 then '02'
--             when BatchPeriod between  7 and  9 then '03'
--             when BatchPeriod between 10 and 12 then '04'
--             end
--         )

        --select @f_SeqNo = replace(str(count(*), 2) , ' ', '0')  --EN - 00393 4 submission each period.
        select @f_SeqNo = replace(str(count(*) / 4 + 1, 2) , ' ', '0')
        from @seqTable
        where @f_BatPr = 
        (case when BatchPeriod in (15401,15651,15652,15653, 1, 2, 3) then '01'    --Quarter 1
              when BatchPeriod in (15402,15654,15655,15656, 4, 5, 6) then '02'    --Quarter 2
              when BatchPeriod in (15403,15657,15658,15659, 7, 8, 9) then '03'    --Quarter 3
              when BatchPeriod in (15404,15660,15661,15662,10,11,12) then '04'    --Quarter 4
         end)
        
    set @f_Extens = '.txt'

    select @FileName = @f_Prefix + @f_BatYr + @f_BatPr + @f_InstNo + @f_SeqNo + @f_Extens
end
else if (@SU_Const in ('CRS_ASSESS_MAST', 'CRS_ASSESS_ADMT', 'CRS_ASSESS_DEMO', 'CRS_ASSESS_QURT', 'CRS_ASSESS_FULL', 'CRS_ASSESS_DSCH', 'CRS_ASSESS_RNTR', 'CRS_ASSESS_MEDI')) begin
    set @FileName = dbo.SU_FILENAME_CCRS( @ExecutionID, @SU_Const )
end

-----------------------------------------------------------------------------------
-- UPDATE THE FILE NAME IN THE EXECUTION PROPERTIES TABLE 
update SU_ExecProperties set NameOfFile = @FileName where ExecutionID = @ExecutionID
return 0

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE  procedure [SU_GetParameterList]
    @ExecutionID int, 
    @RecSetCount int output 
as 
 
-- Each SubGroupID with in a GroupID corresponds to a recordset  
-- within the exe. Return Recordset that provides a distinct  
-- list of SubGroupIDs applicable to the current ExecutionID and  
-- GroupID. 
select distinct s.GroupID, s.SubGroupID 
from SU_ExecProperties x
join SU_StructureFile s on x.GroupID = s.GroupID 
where x.ExecutionID = @ExecutionID 
order by s.GroupID, s.SubGroupID 
 
set @RecSetCount = @@rowcount 




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [SU_GetRecords]
  @ExecutionID int
, @GroupID     int
, @SubGroupID  int
, @CountVerify int output 
as 

set nocount on

declare 
  @txt varchar(1000) 
, @sql varchar(8000) 
 
-- HACK: Trick Program into thinking the it is Alberta Amcare. 
if exists (select * from H_HospitalProfile where ProvinceNumber = 13) and (@GroupID in (6, 7, 8)) 
    set @GroupID = 9 

declare cur cursor local fast_forward for 
    select txt = SqlSegment 
    from dbo.SUF_GetQuery ( @ExecutionID, @GroupID, @SubGroupID )
    order by SegmentType, OrderBy 

open cur 

set @sql = '' 
 
while (1=1) begin 
    fetch next from cur into @txt 
    if (@@fetch_status <> 0) break 
    set @sql = @sql + ' ' + @txt 
end 

close cur
deallocate cur

set nocount off

--print @sql

exec ( @sql ) 
set @CountVerify = @@rowcount 


return 0 


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE procedure [SU_GetStructureFile]
    @ExecutionID int, 
    @FieldCount  int output 
as  
select  
  GroupID      = s.GroupID
, SubGroupID   = s.SubGroupID
, ICDType      = s.ICDType
, FieldName    = dbo.SUF_GetTableAlias( s.FieldName, s.Occurrence ) 
, TextPosition = s.TextPosition
, TextLength   = s.TextLength
, TextFormat   = s.TextFormat  
from SU_StructureFile s 
join SU_ExecProperties x on s.GroupID = x.GroupID 
where ExecutionID = @ExecutionID 
 
set @FieldCount = @@rowcount 
return 0



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE  procedure [SU_GetStructureID]
    @AppID int,
    @BatchYear int,
    @GroupCount int output,
    @GroupID_0 int output,
    @GroupID_1 int output,
    @GroupID_2 int output
as
set nocount on 

declare @prov int
select top 1 @prov = ProvinceNumber from H_HospitalProfile

if not exists (
    select *
    from SU_StructureList 
    where AppID = @AppID
      and BatchYear = @BatchYear
      and Province = @prov)
set @prov = 0

declare @tbl table (ord int identity(0,1), grp int)

insert @tbl ( grp )
select GroupID
from SU_StructureList 
where AppID = @AppID
  and BatchYear = @BatchYear
  and Province = @prov
order by GroupOrder

set @GroupCount = @@rowcount

if @GroupCount > 0 select @GroupID_0 = grp from @tbl where ord = 0
if @GroupCount > 1 select @GroupID_1 = grp from @tbl where ord = 1
if @GroupCount > 2 select @GroupID_2 = grp from @tbl where ord = 2

set nocount off




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE procedure [SU_GetSubmissionSpecificTasks]
    @ExecutionID int,
    @TaskCount int output
as 

select TaskOrder, TaskName, TaskDescription
from SU_StructureTasks t join SU_ExecProperties x on t.GroupID = x.GroupID
where x.ExecutionID = @ExecutionID
order by TaskOrder

set @TaskCount = @@rowcount

return 0





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE  procedure [SU_GetTempTableList]
    @ExecutionID int
as
select distinct
    SourceTable = TableName,
    TargetTable = dbo.SUF_GetTempTable( ExecutionID, TableName )
from SU_ExecProperties x 
join SU_StructureFile  s on x.GroupID = s.GroupID
where ExecutionID = @ExecutionID
and nullif(TableName, '') is not null

return 0





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [SU_IAR_ControlRecord]
    @ExecutionID int,
    @RecordCount int,
    @ControlRecord varchar(350) output
as
--EN - 02782
set @ControlRecord = 'tt fffffyyyyqccccccddddddddooooaeeeeeeeeeevvvvv'

declare 
    @tt       char(2), -- Data record type 
    @dddddddd char(8), -- Date of submission 
    @pp       char(2), -- Province/territory code 
    @fffff    char(5), -- Facility number 
    @yyyy     char(4), -- Fiscal year for this submission 
    @q        char(1), -- Fiscal quarter for this submission 
    @cccccc   char(6), -- Number of data records in transmission
    @oooo     char(4), -- Organization ID 2131
    @a        char(1),  -- ApplicationID
    @eeeeeeeeee char(10),  -- Excution ID(Submission ID)
    @vvvvv char(5),  -- CIHI Vendor ID
    @OrgName  char(250) --Organization name

declare @inst int
    
set @a    = '1' 

set @tt = '1'

set @cccccc   = replace(str(@RecordCount, 6), ' ', '0')
set @eeeeeeeeee = replace(str(@ExecutionID, 10), ' ', '0')
set @vvvvv = 'M0004'

select 
  @dddddddd = convert( varchar(8), ExecutionDate, 112 )
, @fffff    = InstNoCIHI
, @yyyy     = convert( char(4), BatchYear)
, @q        = str(BatchPeriod, 1)
, @inst     = InstNoCode
from SU_ExecProperties 
where ExecutionID = @ExecutionID

select top 1 @oooo = left(MDS20_SubmissionOrgID, 4), @OrgName = ltrim(OrganizationName) from h_institutionprofile where code = @inst
--select top 1 @oooo = right('0000' + MDS20_SubmissionOrgID, 4), @OrgName = ltrim(OrganizationName) from h_institutionprofile where code = @inst


Update SU_ExecProperties 
set RecordCount = @RecordCount
where ExecutionID = @ExecutionID

--set @ControlRecord = 
--    replace(
--    replace(
--    replace(
--    replace(
--    replace(
--    replace(
--    replace(
--    replace(
--    replace(
--    replace(
--    replace(
--        @ControlRecord 
--    , 'tt'      , isnull( @tt      , 'tt'       ) )
--    , 'dddddddd', isnull( @dddddddd, 'dddddddd' ) )
--    , 'pp'      , isnull( @pp      , 'pp'       ) )
--    , 'fffff'   , isnull( @fffff   , 'fffff'    ) )
--    , 'yyyy'    , isnull( @yyyy    , 'yyyy'     ) )
--    , 'q'       , isnull( @q       , 'q'        ) )
--    , 'cccccc'  , isnull( @cccccc  , 'cccccc'   ) )
--    , 'oooo'    , isnull( @oooo    , 'oooo'     ) )
--    , 'a'       , isnull( @a       , 'a'        ) )
--    , 'eeeeeeeeee', isnull( @eeeeeeeeee, 'eeeeeeeeee') )
--    , 'vvvvv'  , isnull( @vvvvv    , 'vvvvv'    ) )

set @ControlRecord = @tt + @fffff + @yyyy + @q + @cccccc + @dddddddd + @oooo + @a + @eeeeeeeeee + @vvvvv

set @ControlRecord = @ControlRecord + isnull(@OrgName, 'xxxxxx')

return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [SU_IAR_MH_Initialize]
    @SU_Type     int,
    @date_fr     datetime,
    @date_to     datetime,
    @InstCode    int,
    @FiscalYr    int,
    @FiscalQt    int,
    @RecCount    int output,
    @RecWidth    int output,
    @ExecutionID int output,
    @NameOfFile  varchar(50) output,
    @CoderNumber int = 999999
as

declare @AppID    int
declare @GroupID  int
declare @DateSent datetime
declare @SU_Const varchar(20)
declare @Sql      varchar(1000)

declare @SubFiscalYear int  --ED - 01901
declare @RehabSubDate datetime --ED - 01901
declare @InstCIHI varchar(20) --ED - 01901

--44	IAR_MH_FULL
--45	IAR_MH_SHORT
--46	IAR_MH_QURT
--47	IAR_MH_CHG
--48	IAR_MH_DSCH
--49	IAR_MH_MED
--50	IAR_MH_DEL
--51	IAR_MH_MAST

select @SU_Const = su_const from SU_StructureType where su_id = @SU_Type

--ED - 01901
select top 1 @InstCIHI = CIHIValue , @RehabSubDate = RehabSubDate
from H_InstitutionProfile 
where Code = @InstCode

set @DateSent = GetDate()
set @SubFiscalYear = @FiscalYr  --For IAR submission, we need to convert into xml. It's better to keep the same year.

--if @RehabSubDate is null
--    set @SubFiscalYear = @FiscalYr
--else 
--begin
--    set @SubFiscalYear = datepart(year, @DateSent) - (case when datepart(month, @DateSent) in (1, 2, 3) then 1 else 0 end)
--    if @RehabSubDate >= @DateSent 
--    begin
--        if @FiscalYr < @SubFiscalYear
--            set @SubFiscalYear = @SubFiscalYear - 1
--        else if @FiscalYr > @SubFiscalYear
--            set @SubFiscalYear = @FiscalYr
--    end    
--    else if @RehabSubDate < @DateSent 
--    begin
--        set @SubFiscalYear = datepart(year, @RehabSubDate) - (case when datepart(month, @RehabSubDate) in (1, 2, 3) then 1 else 0 end)
--        if @FiscalYr > @SubFiscalYear
--            set @SubFiscalYear = @FiscalYr

--    end    
--end
--End ED - 01901

set @AppID = 
    case @SU_Type
        when 44 then 650
        when 45 then 651
        when 46 then 652
        when 47 then 653
        when 48 then 654
        when 49 then 650
        when 50 then 650
        when 51 then 650
    end


--ED - 01901
--set @GroupID = dbo.SUF_GET_GroupID( @SU_type, @AppID, @FiscalYr, 0 )
set @GroupID = dbo.SUF_GET_GroupID( @SU_type, @AppID, @SubFiscalYear, 0, 0 )

print 'GroupID = ' + str(@GroupID)

declare @Records table ( AbstractID int, OrderBy int identity(1,1) )

insert SU_ExecProperties 
       ( ExecutionDate, GroupID,  AppID,  CoderNumber,  DateStart, DateEnd,  InstNoCode, BatchYear, BatchPeriod, ICDType, SubFiscalYear, SU_type ) 
values ( @DateSent,     @GroupID, @AppID, @CoderNumber, @date_fr,  @date_to, @InstCode,  @FiscalYr, @FiscalQt, 'T', @SubFiscalYear, @SU_type ) 

set @ExecutionID = @@identity

------------------------------------------------------------------------------------
-- Master
if @SU_Const in ('IAR_MH_MAST')
begin
    --Deletion first
    insert @Records ( AbstractID ) 
    select AA.AbstractID
    from OMHRS_SecAA AA 
        inner join OMHRS_SecA on AA.AbstractID = OMHRS_SecA.AbstractID 
        inner join OMHRS_IAR_CCIM A on AA.AbstractID = A.AbstractID 
        inner join OMHRS_RecInfo R on AA.AbstractID = R.AbstractID 
        inner join H_InstitutionProfile h on h.code = aa.InstitutionNumber
        inner join (select m.AbstractID, max(n.Updated) MaxUpdated
                    from OMHRS_SecAA m 
                        inner join OMHRS_SecA p on m.AbstractID = p.AbstractID
                        inner join dbo.OMHRS_UpdateHistory n on m.AbstractID = n.AbstractID
                    where m.InstitutionNumber = @InstCode and p.A1 between @date_fr and @date_to
                        --and m.AppID = @AppID  --between 650 and 655
                        and n.UpdateType = 'Deleted'
                    group by m.AbstractID
                    ) u on AA.AbstractID = u.AbstractID    
    where InstitutionNumber = @InstCode
        and A1 between @date_fr and @date_to
        and (IAR_CCIM_IsSubmitted = 302152 and IsDeleted in (1, 3)) -- and IAR_CCIM_IsCorrected = 302162)
        --and AppID = @AppID  --in (650, 651)
        and ((u.MaxUpdated > DateSubmittedToCCIM and IAR_CCIM_IsCorrected = 302161) or (IAR_CCIM_IsCorrected = 302162 and u.MaxUpdated > DateCorrectedToCCIM))
    order by AA.AdmitDate, ChartNumber, OMHRS_SecA.A1 desc

    --Correction second
    insert @Records ( AbstractID ) 
    select AA.AbstractID
    from OMHRS_SecAA AA 
        inner join OMHRS_SecA on AA.AbstractID = OMHRS_SecA.AbstractID 
        inner join OMHRS_IAR_CCIM A on AA.AbstractID = A.AbstractID 
        inner join OMHRS_RecInfo R on AA.AbstractID = R.AbstractID 
        inner join H_InstitutionProfile h on h.code = aa.InstitutionNumber
        inner join (select m.AbstractID, max(n.Updated) MaxUpdated
                    from OMHRS_SecAA m 
                        inner join OMHRS_SecA p on m.AbstractID = p.AbstractID
                        inner join dbo.OMHRS_UpdateHistory n on m.AbstractID = n.AbstractID
                    where m.InstitutionNumber = @InstCode and p.A1 between @date_fr and @date_to
                        --and m.AppID in (650, 651)
                        and n.UpdateType = 'Saved'
                    group by m.AbstractID
                    ) u on AA.AbstractID = u.AbstractID    
    where InstitutionNumber = @InstCode
        and A1 between @date_fr and @date_to
        and IsDeleted = 2
        and IAR_CCIM_IsSubmitted = 302152 --and IAR_CCIM_IsCorrected = 302162)
        --and AA.AppID in (650, 651)
        and IsDeleted = 2
        and r.IsValidated in (3, 4)
        and ((u.MaxUpdated > DateSubmittedToCCIM and IAR_CCIM_IsCorrected = 302161) or (IAR_CCIM_IsCorrected = 302162 and u.MaxUpdated > DateCorrectedToCCIM))
    order by AA.AdmitDate, ChartNumber, OMHRS_SecA.A1
    --New third
    insert @Records ( AbstractID ) 
    select AA.AbstractID
    from OMHRS_SecAA AA 
        inner join OMHRS_SecA on AA.AbstractID = OMHRS_SecA.AbstractID 
        inner join OMHRS_IAR_CCIM A on AA.AbstractID = A.AbstractID 
        inner join OMHRS_RecInfo R on AA.AbstractID = R.AbstractID 
        inner join H_InstitutionProfile h on h.code = aa.InstitutionNumber
    where InstitutionNumber = @InstCode
        and A1 between @date_fr and @date_to
        and IsDeleted = 2
        and isnull(IAR_CCIM_IsSubmitted, 0) in (302151, 0) 
        --and AA.AppID in (650, 651)
        and r.IsValidated in (3, 4)
        and aa.LinkID not in (
            select m.AbstractID 
            from OMHRS_SecAA m 
            inner join OMHRS_SecA a on m.AbstractID = a.AbstractID
            inner join dbo.OMHRS_IAR_CCIM r on m.AbstractID = r.AbstractID 
            inner join (select distinct linkid
		        from OMHRS_SecAA aa
		        inner join OMHRS_SecA a on aa.AbstractID = a.AbstractID
		        inner join OMHRS_RecInfo b on aa.AbstractID = b.AbstractID
		        inner join dbo.OMHRS_IAR_CCIM c on aa.AbstractID = c.AbstractID
		        where A1 between @date_fr and @date_to and isvalidated in (3, 4)
		            and isnull(c.IAR_CCIM_IsSubmitted, 0) in (0, 302151) ) d
            on m.AbstractID = d.linkid
            where InstitutionNumber = @InstCode and m.admitdate < @date_fr and isnull(r.IAR_CCIM_IsSubmitted, 0) in (0, 302151)
            and a.A1 not between @date_fr and @date_to
            ) --exclude the assessment that admission asessment is not submited before
    order by AA.AdmitDate, ChartNumber, OMHRS_SecA.A1
end
-- Full Assessment
if @SU_Const in ('IAR_MH_FULL', 'IAR_MH_SHORT', 'IAR_MH_QURT', 'IAR_MH_CHG', 'IAR_MH_DSCH')
begin
    --Correction 
    insert @Records ( AbstractID ) 
    select AA.AbstractID
    from OMHRS_SecAA AA 
        inner join OMHRS_SecA on AA.AbstractID = OMHRS_SecA.AbstractID 
        inner join OMHRS_IAR_CCIM A on AA.AbstractID = A.AbstractID 
        inner join OMHRS_RecInfo R on AA.AbstractID = R.AbstractID 
        inner join H_InstitutionProfile h on h.code = aa.InstitutionNumber
        inner join (select m.AbstractID, max(n.Updated) MaxUpdated
                    from OMHRS_SecAA m 
                        inner join OMHRS_SecA p on m.AbstractID = p.AbstractID
                        inner join dbo.OMHRS_UpdateHistory n on m.AbstractID = n.AbstractID
                    where m.InstitutionNumber = @InstCode and p.A1 between @date_fr and @date_to
                        and m.AppID = @AppID    --in (650, 651)
                        and n.UpdateType = 'Saved'
                    group by m.AbstractID
                    ) u on AA.AbstractID = u.AbstractID    
    where InstitutionNumber = @InstCode
        and A1 between @date_fr and @date_to
        and IsDeleted = 2
        and IAR_CCIM_IsSubmitted = 302152 --and IAR_CCIM_IsCorrected = 302162)
        and AA.AppID = @AppID
        and IsDeleted = 2
        and r.IsValidated in (3, 4)
        and ((u.MaxUpdated > DateSubmittedToCCIM and IAR_CCIM_IsCorrected = 302161) or (IAR_CCIM_IsCorrected = 302162 and u.MaxUpdated > DateCorrectedToCCIM))
    order by AA.AdmitDate, ChartNumber, OMHRS_SecA.A1
    --New third
    insert @Records ( AbstractID ) 
    select AA.AbstractID
    from OMHRS_SecAA AA 
        inner join OMHRS_SecA on AA.AbstractID = OMHRS_SecA.AbstractID 
        inner join OMHRS_IAR_CCIM A on AA.AbstractID = A.AbstractID 
        inner join OMHRS_RecInfo R on AA.AbstractID = R.AbstractID 
        inner join H_InstitutionProfile h on h.code = aa.InstitutionNumber
    where InstitutionNumber = @InstCode
        and A1 between @date_fr and @date_to
        and IsDeleted = 2
        and isnull(IAR_CCIM_IsSubmitted, 0) in (302151, 0) 
        and AA.AppID = @AppID   --650
        and r.IsValidated in (3, 4)
        and aa.LinkID not in (
            select m.AbstractID 
            from OMHRS_SecAA m 
            inner join OMHRS_SecA a on m.AbstractID = a.AbstractID
            inner join dbo.OMHRS_IAR_CCIM r on m.AbstractID = r.AbstractID 
            inner join (select distinct linkid
		        from OMHRS_SecAA aa
		        inner join OMHRS_SecA a on aa.AbstractID = a.AbstractID
		        inner join OMHRS_RecInfo b on aa.AbstractID = b.AbstractID
		        inner join dbo.OMHRS_IAR_CCIM c on aa.AbstractID = c.AbstractID
		        where A1 between @date_fr and @date_to and isvalidated in (3, 4)
		            and isnull(c.IAR_CCIM_IsSubmitted, 0) in (0, 302151) ) d
            on m.AbstractID = d.linkid
            where InstitutionNumber = @InstCode and m.admitdate < @date_fr and isnull(r.IAR_CCIM_IsSubmitted, 0) in (0, 302151)
            and a.A1 not between @date_fr and @date_to
            ) --exclude the assessment that admission asessment is not submited before
    order by AA.AdmitDate, ChartNumber, OMHRS_SecA.A1

end
-- Medicine Assessment
if @SU_Const in ('IAR_MH_MED')
begin
    insert @Records ( AbstractID ) 
    select distinct AA.AbstractID
    from OMHRS_SecAA AA 
        inner join OMHRS_SecA on AA.AbstractID = OMHRS_SecA.AbstractID 
        inner join OMHRS_IAR_CCIM A on AA.AbstractID = A.AbstractID 
        inner join OMHRS_RecInfo R on AA.AbstractID = R.AbstractID 
        inner join OMHRS_Medication M on AA.AbstractID = M.AbstractID
        inner join H_InstitutionProfile h on h.code = aa.InstitutionNumber
        inner join (select m.AbstractID, max(n.Updated) MaxUpdated
                    from OMHRS_SecAA m 
                        inner join OMHRS_SecA p on m.AbstractID = p.AbstractID
                        inner join dbo.OMHRS_UpdateHistory n on m.AbstractID = n.AbstractID
                    where m.InstitutionNumber = @InstCode and p.A1 between @date_fr and @date_to
                        --and m.AppID = @AppID    --in (650, 651)
                        and n.UpdateType = 'Saved'
                    group by m.AbstractID
                    ) u on AA.AbstractID = u.AbstractID    
    where InstitutionNumber = @InstCode
        and OMHRS_SecA.A1 between @date_fr and @date_to
        and IsDeleted = 2
        and IAR_CCIM_IsSubmitted = 302152 --and IAR_CCIM_IsCorrected = 302162)
        --and AA.AppID = @AppID
        and IsDeleted = 2
        and r.IsValidated in (3, 4)
        and ((u.MaxUpdated > DateSubmittedToCCIM and IAR_CCIM_IsCorrected = 302161) or (IAR_CCIM_IsCorrected = 302162 and u.MaxUpdated > DateCorrectedToCCIM))
    --order by AA.AdmitDate, ChartNumber, OMHRS_SecA.A1
    
    --New third
    insert @Records ( AbstractID ) 
    select distinct AA.AbstractID
    from OMHRS_SecAA AA 
        inner join OMHRS_SecA on AA.AbstractID = OMHRS_SecA.AbstractID 
        inner join OMHRS_IAR_CCIM A on AA.AbstractID = A.AbstractID 
        inner join OMHRS_RecInfo R on AA.AbstractID = R.AbstractID 
        inner join OMHRS_Medication M on AA.AbstractID = M.AbstractID
        inner join H_InstitutionProfile h on h.code = aa.InstitutionNumber
    where InstitutionNumber = @InstCode
        and A1 between @date_fr and @date_to
        and IsDeleted = 2
        and isnull(IAR_CCIM_IsSubmitted, 0) in (302151, 0) 
        --and AA.AppID = @AppID   --650
        and r.IsValidated in (3, 4)
        and aa.LinkID not in (
            select m.AbstractID 
            from OMHRS_SecAA m 
            inner join OMHRS_SecA a on m.AbstractID = a.AbstractID
            inner join dbo.OMHRS_IAR_CCIM r on m.AbstractID = r.AbstractID 
            inner join (select distinct linkid
		        from OMHRS_SecAA aa
		        inner join OMHRS_SecA a on aa.AbstractID = a.AbstractID
		        inner join OMHRS_RecInfo b on aa.AbstractID = b.AbstractID
		        inner join dbo.OMHRS_IAR_CCIM c on aa.AbstractID = c.AbstractID
		        where A1 between @date_fr and @date_to and isvalidated in (3, 4)
		            and isnull(c.IAR_CCIM_IsSubmitted, 0) in (0, 302151) ) d
            on m.AbstractID = d.linkid
            where InstitutionNumber = @InstCode and m.admitdate < @date_fr and isnull(r.IAR_CCIM_IsSubmitted, 0) in (0, 302151)
            and a.A1 not between @date_fr and @date_to
            ) --exclude the assessment that admission asessment is not submited before
    --order by AA.AdmitDate, ChartNumber, OMHRS_SecA.A1    
end
-- Deletion Assessment
if @SU_Const in ('IAR_MH_DEL')
    --Deletion first
    insert @Records ( AbstractID ) 
    select AA.AbstractID
    from OMHRS_SecAA AA 
        inner join OMHRS_SecA on AA.AbstractID = OMHRS_SecA.AbstractID 
        inner join OMHRS_IAR_CCIM A on AA.AbstractID = A.AbstractID 
        inner join OMHRS_RecInfo R on AA.AbstractID = R.AbstractID 
        inner join H_InstitutionProfile h on h.code = aa.InstitutionNumber
        inner join (select m.AbstractID, max(n.Updated) MaxUpdated
                    from OMHRS_SecAA m 
                        inner join OMHRS_SecA p on m.AbstractID = p.AbstractID
                        inner join dbo.OMHRS_UpdateHistory n on m.AbstractID = n.AbstractID
                    where m.InstitutionNumber = @InstCode and p.A1 between @date_fr and @date_to
                        --and m.AppID = @AppID  --between 650 and 655
                        and n.UpdateType = 'Deleted'
                    group by m.AbstractID
                    ) u on AA.AbstractID = u.AbstractID    
    where InstitutionNumber = @InstCode
        and A1 between @date_fr and @date_to
        and (IAR_CCIM_IsSubmitted = 302152 and IsDeleted in (1, 3)) -- and IAR_CCIM_IsCorrected = 302162)
        --and AppID = @AppID  --in (650, 651)
        and ((u.MaxUpdated > DateSubmittedToCCIM and IAR_CCIM_IsCorrected = 302161) or (IAR_CCIM_IsCorrected = 302162 and u.MaxUpdated > DateCorrectedToCCIM))
    order by AA.AdmitDate, ChartNumber, OMHRS_SecA.A1 Desc


insert SU_RecordSelect ( 
    ExecutionID  , 
    AbstractID   ,     OrderBy      , 
    IsSubmited   , 
    IsCorrected  , 
    IsValidated  , 
    IsCompleted  , 
    IsDeleted    , 
    CIHIDateSent , 
    BatchYear    ,
    BatchPeriod  )
select top 500  --Conference Meeting this morning, the IAR submission max record is 500. 2012/07/08
    @ExecutionID  , 
    r.AbstractID  , 
    r.OrderBy, --min(r.OrderBy),
	302152, --Yes             ,
    (case when a.IsDeleted in (1, 3) then 302163 when IAR.IAR_CCIM_IsSubmitted = 302152 then 302162 else 302161 end), --D/C/N
	a.IsValidated ,
	4 ,
	a.IsDeleted   ,
	@DateSent     ,
	@FiscalYr     ,
    BatchPeriod = (case @FiscalQt when 1 then 15401
                                  when 2 then 15402
                                  when 3 then 15403
                                  when 4 then 15404
                                  else @FiscalQt
                   end)
from @Records r 
join dbo.OMHRS_RecInfo a on r.AbstractID = a.AbstractID 
join dbo.OMHRS_IAR_CCIM IAR on r.AbstractID = IAR.AbstractID
--group by r.AbstractID, a.IsCorrected, a.IsValidated, a.IsDeleted
order by r.OrderBy  --min(r.OrderBy)

if @SU_Const in ('IAR_MH_MAST')
begin
    insert SU_Record_Submited_IAR_MH_Order(ExecutionID, AbstractID, OrderBy)
    select ExecutionID, AbstractID, OrderBy from SU_RecordSelect
    where ExecutionID = @ExecutionID
end

-- set the total number of records: 
set @RecCount = (select count(*) from @Records) -- @@rowcount

delete from @Records

DBCC DBREINDEX (SU_RecordSelect)

select @RecWidth = sum(TextLength) 
from SU_StructureFile 
where GroupID = @GroupID


set @NameOfFile = dbo.SU_FILENAME_IAR_MH( @ExecutionID, @SU_Const )

-----------------------------------------------------------------------------------
-- UPDATE THE EXECUTION PROPERTIES TABLE WITH THE VARIOUS VALUES
update SU_ExecProperties
set RecordCount = @RecCount,
    RecordWidth = @RecWidth,
    NameOfFile  = @NameOfFile,
    InstNoCIHI  = @InstCIHI --(select CIHIValue from H_InstitutionProfile where Code = @InstCode)
where ExecutionID = @ExecutionID

EXIT_PROCEDURE_NORMAL:
    return 0
ERROR___INVALID_SUBMISSION_NUMBER:
    return 1


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE procedure [SU_IAR_MH_MED_Correct]
    @ExecutionID int,
	@AbstractID [int]  
as    
    select SubmitedRecord  
    from SU_Record_Submited_IAR_MH_MED S
    where S.AbstractID = @AbstractID and S.IsDeleted <> 1 and
        S.ExecutionID = @ExecutionID




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  procedure [SU_IAR_MH_MED_Delete]
	@AbstractID [int]  ,
	@IsDeleted [int]       
as    
    select '8 ' + substring(S.SubmitedRecord, 3, 10) + 'D' +
        substring(S.SubmitedRecord, 14, 32) + substring(s.SubmitedRecord, 82, 378)
    from SU_Record_Submited_IAR_MH_MED S
        left join OMHRS_Medication M 
        on S.X1 = M.X1 and S.AbstractID = M.AbstractID
    where S.AbstractID = @AbstractID and S.IsDeleted <> 1 and
        (@IsDeleted = 1 or (  @IsDeleted = 0 and M.X1 is null))


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create Procedure [SU_IAR_MH_MergeRecord]
	@ExecutionID  int
as    

    declare @AbstractID  int
    declare @X1          int
    declare @IsCorrected int
    declare @IsDeleted   int
    declare @RecordType  varchar(2)
    declare @Sub_Type    varchar(1)
    declare @CIHIDateSent datetime

    select S.AbstractID, S.IsCorrected, S.IsDeleted, S.SubmitedRecord
    from SU_Record_Submited S 
        inner join SU_Record_Submited_IAR_MH_Order R 
        on S.AbstractID = R.AbstractID and S.ExecutionID = R.ExecutionID
    where S.ExecutionID = @ExecutionID
    order by R.OrderBy



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create Procedure [SU_IAR_MH_SaveMED_Deletion]
	@ExecutionID  int
as    
    update SU_Record_Submited_IAR_MH_MED
    set IsCorrected = 3,
        IsDeleted   = 1,
	    CIHIDateSent = (select top 1 ExecutionDate from dbo.SU_ExecProperties where ExecutionID = @ExecutionID),
        ExecutionID = @ExecutionID
    from SU_Record_Submited_IAR_MH_MED S
        inner join dbo.SU_Record_Submited R 
            on R.AbstractID = S.AbstractID
        left join OMHRS_Medication M 
        on S.X1 = M.X1 and S.AbstractID = M.AbstractID
    where R.ExecutionID = @ExecutionID and
        (R.IsDeleted = 1 or M.X1 is null) 


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create Procedure [SU_IAR_MH_SaveRecord]
	@ExecutionID  int, 
    @SubData      varchar(4000)
as    

    declare @AbstractID  int
    declare @X1          int
    declare @IsCorrected int
    declare @IsDeleted   int
    declare @RecordType  varchar(2)
    declare @Sub_Type    varchar(1)
    declare @CIHIDateSent datetime

    set @AbstractID = left(@SubData, 10)
    set @RecordType = ltrim(rtrim(substring(@SubData, 11, 2)))
    set @X1 = cast(ltrim(rtrim(substring(@SubData, 13, 10))) as int)
    set @Sub_Type = ltrim(rtrim(substring(@SubData, 23, 1)))

    if @Sub_Type = 'N'
    begin
        set @IsCorrected = 0
        set @IsDeleted = 0
    end
    else if @Sub_Type = 'C'
    begin
        set @IsCorrected = 1
        set @IsDeleted = 0
    end
    else
    begin
        set @IsCorrected = 1
        set @IsDeleted = 1
    end

    set @CIHIDateSent = (select ExecutionDate from SU_ExecProperties where ExecutionID = @ExecutionID)

    if @RecordType = '8 '    --'08'  --PR - 02985
    begin
        if exists (select * from SU_Record_Submited_IAR_MH_MED where 
            abstractID = @AbstractID and X1 = @X1)
            update SU_Record_Submited_IAR_MH_MED
            set IsCorrected = 1,
        	    CIHIDateSent = @CIHIDateSent,
                SubmitedRecord = substring(@SubData, 11, 4000),
                ExecutionID = @ExecutionID
            where AbstractID = @AbstractID and X1 = @X1
        else
        begin
            set @SubData = (case when @Sub_Type = 'N' then substring(@SubData, 11, 4000)
                                 else substring(@SubData, 11, 12) + 'N' + substring(@SubData, 24, 4000)
                                 end)
            insert into SU_Record_Submited_IAR_MH_MED(ExecutionID, AbstractID,
    	        X1, IsCorrected, IsDeleted, CIHIDateSent, SubmitedRecord)
            values(@ExecutionID, @AbstractID,
    	        @X1, @IsCorrected, @IsDeleted, @CIHIDateSent, @SubData)
        end
    end
    else
        insert SU_Record_Submited (ExecutionID, AbstractID, X1, IsCorrected, 
            IsDeleted, CIHIDateSent, SubmitedRecord) 
        values(@ExecutionID, @AbstractID, @X1, @IsCorrected, @IsDeleted, 
            @CIHIDateSent, substring(@SubData, 11, 4000)) 

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [SU_Initialize_NACRS_CJRR]
      @SU_Type int
    , @PrevExecID  int
    , @BatchStart  int output
    , @BatchCount  int output
    , @RecordCount int output
    , @RecordWidth int output
    , @ExecutionID int output
    , @ProvNoCIHI  varchar(1) output
    , @InstNoCIHI  varchar(5) output
    , @BatPerCIHI  varchar(2) output
as

declare
      @GroupID   int
    , @AppID     int
    , @BatchYear int
    , @ProvCode  int
    , @SU_Const  varchar(20)

select @SU_Const = su_const from SU_StructureType where su_id = @SU_Type
select @BatchYear = BatchYear from SU_ExecProperties where ExecutionID = @PrevExecID
set @ProvCode = 0
set @AppID = 401
set @GroupID = dbo.SUF_GET_GroupID(@SU_Type, @AppID, @BatchYear, @ProvCode, 0)

--PRINT '@GroupID = ' + isnull( CONVERT(nvarchar, @GroupID), '<NULL>' ) 

insert SU_ExecProperties 
    ( ExecutionDate
    , CoderNumber
    , GroupID
    , DateStart
    , DateEnd
    , InstNoCode
    , ICDType
    , AppID
    , BatchYear
    , BatchPeriod
    , IsCorrection
    , IsResubmit
    , BatchStart
    , BatchCount
    , RecordCount
    , RecordWidth
    , ProvNoCIHI
    , InstNoCIHI
    , BatPerCIHI
	, NacrsLevelCode
	, SU_type)
select
      ExecutionDate
    , CoderNumber
    , GroupID = @GroupID
    , DateStart
    , DateEnd
    , InstNoCode
    , ICDType
    , AppID
    , BatchYear
    , BatchPeriod
    , IsCorrection
    , IsResubmit
    , BatchStart
    , BatchCount
    , RecordCount
    , RecordWidth = (select sum(TextLength) from SU_StructureFile where GroupID = @GroupID)
    , ProvNoCIHI
    , InstNoCIHI
    , BatPerCIHI
	, 3
	, @SU_Type
from SU_ExecProperties
where ExecutionID = @PrevExecID

set @ExecutionID = @@identity

delete SU_RecordSelect where ExecutionID = @ExecutionID

insert SU_RecordSelect
    ( ExecutionID
    , AbstractID
    , OrderBy
    , IsCorrected
    , IsSubmited
    , IsValidated
    , IsCompleted
    , IsDeleted
    , CIHIDateSent
    , BatchYear
    , BatchPeriod
    , BatchNumber
    , AbstractNumber )
select distinct 
      @ExecutionID
    , h.AbstractID
    , OrderBy
    , IsCorrected
    , IsSubmited
    , IsValidated
    , IsCompleted
    , IsDeleted
    , CIHIDateSent
    , BatchYear
    , BatchPeriod
    , BatchNumber
    , AbstractNumber
from SU_RecordHistory h
	inner join AB_CJRR r on h.AbstractID = r.AbstractID 
	left join AB_Intervention v on h.AbstractID = v.AbstractID 
	left join ICD_ProcFile10 f on v.IntervCode = f.code 
	left join LU_IntervAttStatus s on v.IntervAttribStatus = s.code 
where ExecutionID = @PrevExecID and r.Occurrence = 1 and (len(r.Component1) > 0 or len(r.Component2) > 0 or len(r.Component3) > 0)
	and IsDeleted not in (1, 3) and left(f.CIHIValue, 5) in ('1VG53', '1VP53', '1VA53', '1SQ53') and isnull(s.CIHIValue, '') <> 'A'
--	and (IsDeleted in (1, 3) or (IsDeleted not in (1, 3) and left(f.CIHIValue, 5) in ('1VG53', '1VP53', '1VA53', '1SQ53') and isnull(s.CIHIValue, '') <> 'A'))
set @RecordCount = @@ROWCOUNT 

Update SU_ExecProperties set RecordCount = @RecordCount where ExecutionID = @ExecutionID

DBCC DBREINDEX ( SU_RecordSelect )

select 
      @BatchStart  = BatchStart
    , @BatchCount  = BatchCount
    , @RecordCount = RecordCount
    , @RecordWidth = RecordWidth
    , @ProvNoCIHI  = ProvNoCIHI
    , @InstNoCIHI  = InstNoCIHI
    , @BatPerCIHI  = BatPerCIHI
from SU_ExecProperties 
where ExecutionID = @ExecutionID

return 0







GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [SU_InitializeSubmission]
    @SU_Type      int,
    @InstNoCode   int,
    @BatchYear    int,
    @BatchPeriod  int,
    @IsCorrection int,
    @IsResubmit   int,
    @UseCareType  int,
    @NACRSLevelCode   int,  --NP - 00125
    @BatchStart   int output,
    @BatchCount   int output,
    @RecordCount  int output,
    @RecordWidth  int output,
    @ExecutionID  int output,
    @ProvNoCIHI   varchar(1)   output,
    @InstNoCIHI   varchar(5)   output,
    @BatPerCIHI   varchar(2)   output,
    @CoderNumber  int = 999999,
    @DateFr varchar(10),
    @DateTo varchar(10)
as

-- eSU_DAD_I10_SUBMIT = 1  
-- eSU_DAD_I10_DELETE = 2  
-- eSU_DAD_I9C_SUBMIT = 3  
-- eSU_NAC_I10_SUBMIT = 4  
-- eSU_NAC_I9C_SUBMIT = 5  
-- eSU_NRS_DELETIONS  = 6  
-- eSU_NRS_ADMISSION  = 7  
-- eSU_NRS_DISCHARGE  = 8  
-- eSU_NRS_FOLLOW_UP  = 9  
--EN - 00464 the date range will be passed from WinRecs
--declare 
--    @DateFr varchar(10),
--    @DateTo varchar(10)

--select 
--    @DateFr = dbo.SUF_GetPeriodDateFr( @BatchYear, @BatchPeriod ), 
--    @DateTo = dbo.SUF_GetPeriodDateTo( @BatchYear, @BatchPeriod )

--PR - 05193
declare 
    @DateFromPeriod varchar(10),
    @DateToPeriod varchar(10)
select 
    @DateFromPeriod = dbo.SUF_GetPeriodDateFr( @BatchYear, @BatchPeriod ), 
    @DateToPeriod = dbo.SUF_GetPeriodDateTo( @BatchYear, @BatchPeriod )


declare @FakeRecordCount int set @FakeRecordCount = -1
declare @IsUseMentalHealth int
declare @AbstractNumber int
--declare @NacrsLevelCode int --ED - 01794
declare @Level3Date datetime    --ED - 01794
declare @NacrsLevelSetting int --NP - 00125
declare @province varchar(10)
declare @UseLite int	--2.x-0278

declare 
    @SU_Const varchar(20),
    @GroupID  int,
    @ProvCode int,
    @DateSent datetime,
    @ICDType  char(1),
    @AppID    int,
    @CareType int
--EN-00057 New field: CIHI_AbstractID
declare @MaxCIHI_AbstractID int
declare @MaxSubmit_ID int

select @SU_Const = su_const from SU_StructureType where su_id = @SU_Type
select top 1 @ProvCode = ProvinceNumber from H_HospitalProfile
select @ProvNoCIHI = CIHIValue from LU_Province where Code = @ProvCode
select @CareType = AssociationID, @NacrsLevelSetting = LevelCode, @UseLite = UseLite    --, @Level3Date = Level3Date 
from H_InstitutionProfile where Code = @InstNoCode

set @AppID = 
    case @SU_Const
        when 'DAD_I10_SUBMIT' then case @CareType when 1 then 201 else 202 end
        when 'DAD_I10_DELETE' then case @CareType when 1 then 201 else 202 end
        when 'DAD_I9C_SUBMIT' then case @CareType when 1 then 101 else 102 end
        when 'NAC_I10_SUBMIT' then 401
        when 'NAC_I9C_SUBMIT' then 301
        when 'NRS_DELETIONS'  then 250
        when 'NRS_ADMISSION'  then 250
        when 'NRS_DISCHARGE'  then 251
        when 'NRS_FOLLOW_UP'  then 252
        when 'MADE_I10_SUBMIT' then 201
        when 'MADE_I10_DELETE' then 201
    end

--ED - 01794
if @CareType = 5
begin
    if @batchyear < 2009
        set @NacrsLevelCode = 3
--NP - 00125
--    else
--    begin
--        if @NacrsLevelCode = 3 and @Level3Date is not null
--        begin
--            if @DateFr < @Level3Date
--                set @NacrsLevelCode = 1
--        end
--    end
end
else
    set @NacrsLevelCode = null


set @GroupID = dbo.SUF_GET_GroupID(@SU_Type, @AppID, @BatchYear, @ProvCode, isnull(@NacrsLevelCode, 0))

if @AppID in (201, 202, 401, 250, 251, 252) 
    set @ICDType = 'T'
else 
    if exists(select * from H_InstitutionProfile where Code = @InstNoCode and ICDCMLive is null)
        set @ICDType = '9'
    else
        set @ICDType = 'C'


declare @Records table ( AbstractID int, OrderBy int identity(1,1) )

--
-- IF THE HOSPITAL IS ALBERTA THEN THE BATCH YEAR NEEDS TO BE INCREMENTED BY ONE.
--
if exists (select * from H_HospitalProfile where ProvinceNumber = 13) begin
    set @BatchYear = str( cast(@BatchYear as int) + 1, 4 )
end

set @DateSent = GetDate()

-- get a list of AbstractID's that will be used to creat the submission file

------------------------------------------------------------------------------------
-- INPATIENT/SDS INSTITUTIONS ICD 9, 9CM, ICD 10
if (@SU_Const in ('DAD_I10_SUBMIT', 'DAD_I9C_SUBMIT')) begin

    -- only do this if it is not Alberta
    if not exists (select * from H_HospitalProfile where ProvinceNumber = 13) 
        if (@IsCorrection = 1)
            set @DateFr = dbo.SUF_GetPeriodDateFr( @BatchYear, 1 )

    if (@IsCorrection = 0) 

        if @IsResubmit = 2 
        begin
            if @UseCareType = 15681 and @DateFr >= '2019/04/01' 
                insert @Records( AbstractID )
                select AbstractID
                from
                (select distinct AB_Abstract.AbstractID, Batchyear, BatchPeriod, BatchNumber, AbstractNumber
                from dbo.AB_Abstract
                    inner join AB_Diagnosis on AB_Abstract.AbstractID = AB_Diagnosis.AbstractID
                    inner join ICD_DiagFile10 on AB_Diagnosis.DiagnosisCode = ICD_DiagFile10.Code
                where (DischargeDate between @DateFr and @DateTo) 
                  and (InstitutionNumber = @InstNoCode) 
                  and (IsDeleted = 2) 
                  and IsSubmited = 1
                  and ( 1 = case 
                            when (@CoderNumber < 3) then 1 
                            when (@CoderNumber >= 3 and (IsValidated in (3, 4)) ) then 1 
                            else 0 end ) --2.x-1821 Allow partial submission
                  and ICD_DiagFile10.CIHIValue in ('U071', 'U072')) z
                order by Batchyear, BatchPeriod, BatchNumber, AbstractNumber  -- dbo.SU_ChartNumberFillLeadingZero(ChartNumber)
            else
                insert @Records( AbstractID )
                select AbstractID
                from dbo.AB_Abstract
                where (DischargeDate between @DateFr and @DateTo) 
                  and (InstitutionNumber = @InstNoCode) 
                  and (IsDeleted = 2) 
                  and ( 1 = case 
                            when (@CoderNumber < 3) then 1 
                            when (@CoderNumber >= 3 and (IsValidated in (3, 4)) ) then 1 
                            else 0 end ) --2.x-1821 Allow partial submission
                  and IsSubmited = 1
                order by Batchyear, BatchPeriod, BatchNumber, AbstractNumber  -- dbo.SU_ChartNumberFillLeadingZero(ChartNumber)
        end
        else
        begin
            if @UseCareType = 15681 and @DateFr >= '2019/04/01' 
                insert @Records( AbstractID)
                select AbstractID
                from
                (select distinct AB_Abstract.AbstractID, DischargeDate, ChartNumber
                from dbo.AB_Abstract
                    inner join AB_Diagnosis on AB_Abstract.AbstractID = AB_Diagnosis.AbstractID
                    inner join ICD_DiagFile10 on AB_Diagnosis.DiagnosisCode = ICD_DiagFile10.Code
                where (DischargeDate between @DateFr and @DateTo) 
                  and (InstitutionNumber = @InstNoCode) 
                  and (IsDeleted = 2) 
                  and (1 = case 
                        when (@IsResubmit = 0 and IsSubmited <> 1) then 1 
                        when (@IsResubmit = 1) then 1
                        else 0 
                        end)
                  and ( 1 = case 
                            when (@CoderNumber < 3) then 1 
                            when (@CoderNumber >= 3 and (IsValidated in (3, 4)) ) then 1 
                            else 0 end ) --2.x-1821 Allow partial submission
                  and ICD_DiagFile10.CIHIValue in ('U071', 'U072')) z
                order by DischargeDate, ChartNumber  -- dbo.SU_ChartNumberFillLeadingZero(ChartNumber)
            else
                insert @Records( AbstractID )
                select AbstractID
                from dbo.AB_Abstract
                where (DischargeDate between @DateFr and @DateTo) 
                  and (InstitutionNumber = @InstNoCode) 
                  and (IsDeleted = 2) 
                  and (1 = case 
                        when (@IsResubmit = 0 and IsSubmited <> 1) then 1 
                        when (@IsResubmit = 1) then 1
                        else 0 
                        end)
                  and ( 1 = case 
                            when (@CoderNumber < 3) then 1 
                            when (@CoderNumber >= 3 and (IsValidated in (3, 4)) ) then 1 
                            else 0 end ) --2.x-1821 Allow partial submission

                order by DischargeDate, ChartNumber  -- dbo.SU_ChartNumberFillLeadingZero(ChartNumber)
        end
    else 
    begin
        -- return the first 999 record that are flagged as correction.
        if @UseCareType = 15681 and @DateFr >= '2019/04/01' 
            insert @Records( AbstractID )
            select top 999 AbstractID
            from
            (select distinct AB_Abstract.AbstractID, BatchPeriod, BatchNumber, AbstractNumber           
            from dbo.AB_Abstract
                inner join AB_Diagnosis on AB_Abstract.AbstractID = AB_Diagnosis.AbstractID
                inner join ICD_DiagFile10 on AB_Diagnosis.DiagnosisCode = ICD_DiagFile10.Code
            where (DischargeDate between @DateFr and @DateTo) 
              and (InstitutionNumber = @InstNoCode) 
              and (IsDeleted = 2) 
              and (IsCorrected = 2) 
              and (IsValidated in (3, 4)) --2.x-1821 Allow partial submission
              and ICD_DiagFile10.CIHIValue in ('U071', 'U072')) x
            order by BatchPeriod, BatchNumber, AbstractNumber --PR - 05297 -- DischargeDate, ChartNumber  -- dbo.SU_ChartNumberFillLeadingZero(ChartNumber)
        else
            insert @Records( AbstractID )
            select top 999 AbstractID             from dbo.AB_Abstract
            where (DischargeDate between @DateFr and @DateTo) 
              and (InstitutionNumber = @InstNoCode) 
              and (IsDeleted = 2) 
              and (IsCorrected = 2) 
              and (IsValidated in (3, 4))   --2.x-1821 Allow partial submission
            order by BatchPeriod, BatchNumber, AbstractNumber --PR - 05297 -- DischargeDate, ChartNumber  -- dbo.SU_ChartNumberFillLeadingZero(ChartNumber)
    end
end

------------------------------------------------------------------------------------
-- DAD ICD 10, DELETION FILE
else if (@SU_Const = 'DAD_I10_DELETE') begin

    -- only do this if it is not Alberta
    if not exists (select * from H_HospitalProfile where ProvinceNumber = 13) 
        if (@IsCorrection = 1)
            set @DateFr = dbo.SUF_GetPeriodDateFr( @BatchYear, 1 )

    if @UseCareType = 15681 and @DateFr >= '2019/04/01' 
        insert @Records( AbstractID )
        select top 999 AbstractID
        from
        (select distinct AB_Abstract.AbstractID, Batchyear, BatchPeriod, BatchNumber, AbstractNumber
        from dbo.AB_Abstract
            inner join AB_Diagnosis on AB_Abstract.AbstractID = AB_Diagnosis.AbstractID
            inner join ICD_DiagFile10 on AB_Diagnosis.DiagnosisCode = ICD_DiagFile10.Code
        where (DischargeDate between @DateFr and @DateTo) 
            and (InstitutionNumber = @InstNoCode) 
            and (IsDeleted in (1, 3)) -- THE RECORD HAS BEEN DELETED
            and (IsCorrected = 2) 
            and ICD_DiagFile10.CIHIValue in ('U071', 'U072')) z
        order by Batchyear, BatchPeriod, BatchNumber, AbstractNumber  -- dbo.SU_ChartNumberFillLeadingZero(ChartNumber)
    else
    -- return the first 999 record that are flagged as correction.
        insert @Records( AbstractID )
        select top 999 AbstractID
        from dbo.AB_Abstract
        where (DischargeDate between @DateFr and @DateTo) 
          and (InstitutionNumber = @InstNoCode) 
          and (IsDeleted in (1, 3)) -- THE RECORD HAS BEEN DELETED
          and (IsCorrected = 2) 
        order by DischargeDate, ChartNumber  -- dbo.SU_ChartNumberFillLeadingZero(ChartNumber)

end


------------------------------------------------------------------------------------
-- AMCARE INSTITUTIONS, ICD 10 (AND ALBERTA) Level 3
else if (@SU_Const in ('NAC_I10_SUBMIT')) and @NacrsLevelCode = 3 begin
	

    if(@IsCorrection = 1) begin
--Ticket 11942. client try to correct and meet record not match problem
--Client has IsValidated = 2 and IsDeleted = 1 
        select @FakeRecordCount = count(*)
        from dbo.AB_Abstract a 
			join dbo.NACRS_CareType_MisCodes(@UseCareType) l on isnull(a.MisCode, 0) = l.Code
			join H_InstitutionProfile h on a.InstitutionNumber = h.code
			join LU_MISCode m on a.MISCode = m.code
        where ( AdmitDate between @DateFr and @DateTo )
          and ( InstitutionNumber = @InstNoCode )
          and ( 1 = case 
                when (@CoderNumber < 3) then 1 
                when (@CoderNumber >= 3 and (IsValidated in (3, 4) or IsDeleted in (1, 3))) then 1 
                else 0 end )
          and (IsCorrected = 2) 
          and (CIHIReturnStatus in (2, 3, 4)) 
          --2.x-1585 Just use IsLiteSubmission flag
          --2.x-1430
		  --and (isnull(h.UseLite, 0) <> 1 or (h.UseLite = 1 and (m.AmCareGroup not in ('CL', 'DI', 'OT') or (m.AmCareGroup = 'CL' and isnull(IsLiteSubmission, 2) <> 1 and isnull(IsSubmitLevel1, 0) <> 1)) and a.AdmitDate > '2018/03/31') or a.AdmitDate <= '2018/03/31')	--2.x-0501
          and (a.AdmitDate <= '2018/03/31' or isnull(h.UseLite, 0) <> 1 or m.AmCareGroup not in ('CL', 'DI', 'OT') or (h.UseLite = 1 and isnull(IsLiteSubmission, 2) <> 1)) --2.x-1585

        set @DateFr = dbo.SUF_GetPeriodDateRange((select top 1 ProvinceNumber from H_HospitalProfile), @BatchPeriod, @DateTo, 0)
        set @DateTo = dbo.SUF_GetPeriodDateRange((select top 1 ProvinceNumber from H_HospitalProfile), @BatchPeriod, @DateTo, 1)
    end 

    -- PR - 03014 Chatham has IsSubmited = 1 and IsCorrected = 2
    update AB_Abstract 
    set IsCorrected = 1
    where InstitutionNumber = @InstNoCode 
    and AdmitDate between @DateFr and @DateTo 
    and IsSubmited = 2 
    and IsDeleted = 2 
    and IsCorrected <> 1 
    

    -- ensure that CIHIReturnStatus matches IsSubmited, IsCorrected and IsDeleted flags.
    update AB_Abstract 
    set CIHIReturnStatus = 1
    where InstitutionNumber = @InstNoCode 
    and AdmitDate between @DateFr and @DateTo 
    and IsCorrected = 1 
    and IsSubmited = 2 
    and IsDeleted = 2 

    update AB_Abstract 
    set CIHIReturnStatus = 2 
    where InstitutionNumber = @InstNoCode 
    and AdmitDate between @DateFr and @DateTo 
    and IsSubmited = 1 
    and IsCorrected = 2 
    and IsDeleted in (1, 3)

    update AB_Abstract 
    set CIHIReturnStatus = 4 
    where InstitutionNumber = @InstNoCode 
    and AdmitDate between @DateFr and @DateTo 
    and IsSubmited = 1 
    and IsCorrected = 2 
    and IsDeleted = 2 

    -- this currently works only for records that have not been Submitted yet. 
    if @UseCareType = 15645 and cast(@DateFr as datetime) >= cast('2017-04-01' as datetime)  --2.x-0920
        insert @Records( AbstractID )
            select AbstractID
            from
            (select distinct a.AbstractID, CIHIReturnStatus, CIHI_AbstractID, AdmitDate, ChartNumber
            from dbo.AB_Abstract a 
			    --join H_InstitutionProfile h on a.InstitutionNumber = h.code
			    join LU_MISCode m on a.MISCode = m.code
                join AB_Diagnosis d on a.AbstractID = d.AbstractID
                join ICD_DiagFile10 f on d.DiagnosisCode = f.Code
                --left join LU_diagnosisPrefix p on d.DiagnosisPrefix = p.code --2.x-1900 remove it
            where ( AdmitDate between @DateFr and @DateTo )
              and ( InstitutionNumber = @InstNoCode )
              and ( 1 = case 
                    when (@CoderNumber < 3) then 1 
                    when (@CoderNumber >= 3 and (IsValidated in (3, 4) or (@IsCorrection = 1 and IsDeleted in (1, 3))) ) then 1 
                    else 0 end )
              and ( 1 = case 
                    when (@IsCorrection = 0) and (IsSubmited <> 1) and (IsDeleted = 2) and (CIHIReturnStatus = 1) then 1 
                    when (@IsCorrection = 1) and (IsCorrected = 2) and (CIHIReturnStatus in (2, 3, 4)) then 1 
                    else 0 end )
		      and m.AmCareGroup = 'ED'
              and left(f.CIHIValue, 4) in ('T400', 'T401', 'T402', 'T403', 'T404', 'T406')
              --and isnull(p.CIHIValue, '') <> 'Q'  --2.x-1900 remove it
              ) z
            order by CIHIReturnStatus, isnull(CIHI_AbstractID, 0), AdmitDate, ChartNumber  -- dbo.SU_ChartNumberFillLeadingZero(ChartNumber)
    else if @UseCareType = 15647 and cast(@DateFr as datetime) >= cast('2019-04-01' as datetime)  --2.x-1804
        insert @Records( AbstractID )
            select AbstractID
            from
            (select distinct a.AbstractID, CIHIReturnStatus, CIHI_AbstractID, AdmitDate, ChartNumber
            from dbo.AB_Abstract a 
			    --join H_InstitutionProfile h on a.InstitutionNumber = h.code
			    join LU_MISCode m on a.MISCode = m.code
                join AB_Diagnosis d on a.AbstractID = d.AbstractID
                join ICD_DiagFile10 f on d.DiagnosisCode = f.Code
            where ( AdmitDate between @DateFr and @DateTo )
              and ( InstitutionNumber = @InstNoCode )
              and ( 1 = case 
                    when (@CoderNumber < 3) then 1 
                    when (@CoderNumber >= 3 and (IsValidated in (3, 4) or (@IsCorrection = 1 and IsDeleted in (1, 3))) ) then 1 
                    else 0 end )
              and ( 1 = case 
                    when (@IsCorrection = 0) and (IsSubmited <> 1) and (IsDeleted = 2) and (CIHIReturnStatus = 1) then 1 
                    when (@IsCorrection = 1) and (IsCorrected = 2) and (CIHIReturnStatus in (2, 3, 4)) then 1 
                    else 0 end )
		      and m.AmCareGroup = 'ED'
              and left(f.CIHIValue, 4) in ('U071', 'U072')) z
            order by CIHIReturnStatus, isnull(CIHI_AbstractID, 0), AdmitDate, ChartNumber  -- dbo.SU_ChartNumberFillLeadingZero(ChartNumber)
    else
        insert @Records( AbstractID )
            select AbstractID
            from dbo.AB_Abstract a 
			    join dbo.NACRS_CareType_MisCodes(@UseCareType) l on isnull(a.MisCode, 0) = l.Code
			    join H_InstitutionProfile h on a.InstitutionNumber = h.code
			    join LU_MISCode m on a.MISCode = m.code
            where ( AdmitDate between @DateFr and @DateTo )
              and ( InstitutionNumber = @InstNoCode )
              and ( 1 = case 
                    when (@CoderNumber < 3) then 1 
                    when (@CoderNumber >= 3 and (IsValidated in (3, 4) or (@IsCorrection = 1 and IsDeleted in (1, 3))) ) then 1 
                    else 0 end )
              and ( 1 = case 
                    when (@IsCorrection = 0) and (IsSubmited <> 1) and (IsDeleted = 2) and (CIHIReturnStatus = 1) then 1 
                    when (@IsCorrection = 1) and (IsCorrected = 2) and (CIHIReturnStatus in (2, 3, 4)) then 1 
                    else 0 end )
              --2.x-1585 Just use IsLiteSubmission flag
              --2.x-1430
    		  --and (isnull(h.UseLite, 0) <> 1 or (h.UseLite = 1 and (m.AmCareGroup not in ('CL', 'DI', 'OT') or (m.AmCareGroup = 'CL' and isnull(IsLiteSubmission, 2) <> 1 and isnull(IsSubmitLevel1, 0) <> 1)) and a.AdmitDate > '2018/03/31') or a.AdmitDate <= '2018/03/31')	--2.x-0501
              and (a.AdmitDate <= '2018/03/31' or isnull(h.UseLite, 0) <> 1 or m.AmCareGroup not in ('CL', 'DI', 'OT') or (h.UseLite = 1 and isnull(IsLiteSubmission, 2) <> 1)) --2.x-1585

		      --and (isnull(h.UseLite, 0) <> 1 or (h.UseLite = 1 and m.AmCareGroup not in ('DI', 'OT') and a.AdmitDate > '2018/03/31'))	--2.x-0501
            order by CIHIReturnStatus, isnull(CIHI_AbstractID, 0), AdmitDate, ChartNumber  -- dbo.SU_ChartNumberFillLeadingZero(ChartNumber)
end

-- AMCARE INSTITUTIONS, ICD 10 (AND ALBERTA) Level 1 only, 
--NP - 00125
else if (@SU_Const in ('NAC_I10_SUBMIT')) and ((@NacrsLevelCode = 1 and @NACRSLevelSetting = 1) or 
	(@NacrsLevelCode = 2 and @NACRSLevelSetting = 2))  begin

    if(@IsCorrection = 1) begin
--Ticket 11942. client try to correct and meet record not match problem
--Client has IsValidated = 2 and IsDeleted = 1 
        select @FakeRecordCount = count(*)
        from dbo.AB_Abstract a 
            --PR - 05710 Level 1 or 2 is for ED visit only
            --join  dbo.NACRS_CareType_MisCodes(@UseCareType) l on isnull(a.MisCode, 0) = l.Code
            inner join LU_MISCode l on isnull(a.MISCode, 0) = l.code and 
				(((l.CIHIValue like '71310%' or l.CIHIValue like '72310%' or l.CIHIValue like '73310%') and AdmitDate < '2010/04/01') or
				 ((isnull(l.AmCareGroup, '') = 'ED') and AdmitDate >= '2010/04/01'))
        where ( AdmitDate between @DateFr and @DateTo )
          and ( InstitutionNumber = @InstNoCode )
          and ( 1 = case 
                when (@CoderNumber < 3) then 1 
                when (@CoderNumber >= 3 and (IsValidLevel1 in (3, 4) or IsDeleted in (1, 3))) then 1 
                else 0 end )
          and IsSubmitLevel1 = 1
          and (IsCorrectLevel1 = 2) 
          and (CIHIReturnStatusLevel1 in (2, 3, 4)) 
          --and IsSubmited = 2

        set @DateFr = dbo.SUF_GetPeriodDateRange((select top 1 ProvinceNumber from H_HospitalProfile), @BatchPeriod, @DateTo, 0)
        set @DateTo = dbo.SUF_GetPeriodDateRange((select top 1 ProvinceNumber from H_HospitalProfile), @BatchPeriod, @DateTo, 1)
    end 

    -- PR - 03014 Chatham has IsSubmited = 1 and IsCorrected = 2
    update AB_Abstract 
    set IsCorrectLevel1 = 1
    where InstitutionNumber = @InstNoCode 
        and AdmitDate between @DateFr and @DateTo 
        and IsSubmitLevel1 = 2 
        and IsDeleted = 2 
        and IsCorrectLevel1 <> 1 
        --and IsSubmited = 2
    

    -- ensure that CIHIReturnStatus matches IsSubmited, IsCorrected and IsDeleted flags.
    update AB_Abstract 
    set CIHIReturnStatusLevel1 = 1
    where InstitutionNumber = @InstNoCode 
        and AdmitDate between @DateFr and @DateTo 
        and IsCorrectLevel1 = 1 
        and IsSubmitLevel1 = 2 
        and IsDeleted = 2 
        --and IsSubmited = 2

    update AB_Abstract 
    set CIHIReturnStatusLevel1 = 2 
    where InstitutionNumber = @InstNoCode 
        and AdmitDate between @DateFr and @DateTo 
        and IsSubmitLevel1 = 1 
        and IsCorrectLevel1 = 2 
        and IsDeleted in (1, 3)
        --and IsSubmited = 2

    update AB_Abstract 
    set CIHIReturnStatusLevel1 = 4 
    where InstitutionNumber = @InstNoCode 
        and AdmitDate between @DateFr and @DateTo 
        and IsSubmitLevel1 = 1 
        and IsCorrectLevel1 = 2 
        and IsDeleted = 2 
        --and IsSubmited = 2

    -- this currently works only for records that have not been Submitted yet. 
    if @UseCareType = 15645 and cast(@DateFr as datetime) >= cast('2017-04-01' as datetime)  --2.x-0920
        insert @Records( AbstractID )
            select AbstractID
            from 
            (select distinct a.AbstractID, a.CIHIReturnStatusLevel1, a.CIHI_AbstractID, a.AdmitDate, a.ChartNumber
            from dbo.AB_Abstract a 
			    join LU_MISCode m on a.MISCode = m.code
                join AB_Diagnosis d on a.AbstractID = d.AbstractID
                join ICD_DiagFile10 f on d.DiagnosisCode = f.Code
                --left join LU_diagnosisPrefix p on d.DiagnosisPrefix = p.code --2.x-1900 remove it
            where ( AdmitDate between @DateFr and @DateTo )
              and ( InstitutionNumber = @InstNoCode )
              and ( 1 = case 
                    when (@CoderNumber < 3) then 1 
                    when (@CoderNumber >= 3 and (IsValidLevel1 in (3, 4) or (@IsCorrection = 1 and IsDeleted in (1, 3))) ) then 1 
                    else 0 end )
              and ( 1 = case 
                    when (@IsCorrection = 0) and (IsSubmitLevel1 <> 1) and (IsDeleted = 2) and (CIHIReturnStatusLevel1 = 1) then 1 
                    when (@IsCorrection = 1) and (IsCorrectLevel1 = 2) and (CIHIReturnStatusLevel1 in (2, 3, 4)) then 1 
                    else 0 end )
		      and m.AmCareGroup = 'ED'
              and left(f.CIHIValue, 4) in ('T400', 'T401', 'T402', 'T403', 'T404', 'T406')
              --and isnull(p.CIHIValue, '') <> 'Q' --2.x-1900 remove it
              ) x
            order by CIHIReturnStatusLevel1, isnull(CIHI_AbstractID, 0), AdmitDate, ChartNumber  -- dbo.SU_ChartNumberFillLeadingZero(ChartNumber)
    else if @UseCareType = 15647 and cast(@DateFr as datetime) >= cast('2019-04-01' as datetime)  --2.x-1804
    begin
        if @NacrsLevelCode = 2 
            insert @Records( AbstractID )
            select AbstractID
            from 
            (select distinct a.AbstractID, a.CIHIReturnStatusLevel1, a.CIHI_AbstractID, a.AdmitDate, a.ChartNumber
            from dbo.AB_Abstract a 
			    join LU_MISCode m on a.MISCode = m.code
                left join AB_Diagnosis d on a.AbstractID = d.AbstractID
                left join ICD_DiagFile10 f on d.DiagnosisCode = f.Code
                left join AB_DischargeDiagnosis dd on a.AbstractID = dd.AbstractID
                left join ICD_DiagFile10 df on dd.DischargeDiagnosis = df.Code
            where ( AdmitDate between @DateFr and @DateTo )
              and ( InstitutionNumber = @InstNoCode )
              and ( 1 = case 
                    when (@CoderNumber < 3) then 1 
                    when (@CoderNumber >= 3 and (IsValidLevel1 in (3, 4) or (@IsCorrection = 1 and IsDeleted in (1, 3))) ) then 1 
                    else 0 end )
              and ( 1 = case 
                    when (@IsCorrection = 0) and (IsSubmitLevel1 <> 1) and (IsDeleted = 2) and (CIHIReturnStatusLevel1 = 1) then 1 
                    when (@IsCorrection = 1) and (IsCorrectLevel1 = 2) and (CIHIReturnStatusLevel1 in (2, 3, 4)) then 1 
                    else 0 end )
		      and m.AmCareGroup = 'ED'
              and (left(f.CIHIValue, 4) in ('U071', 'U072') or left(df.CIHIValue, 4) in ('U071', 'U072'))) x
            order by CIHIReturnStatusLevel1, isnull(CIHI_AbstractID, 0), AdmitDate, ChartNumber  -- dbo.SU_ChartNumberFillLeadingZero(ChartNumber)
        else
            insert @Records( AbstractID )
            select AbstractID
            from 
            (select distinct a.AbstractID, a.CIHIReturnStatusLevel1, a.CIHI_AbstractID, a.AdmitDate, a.ChartNumber
            from dbo.AB_Abstract a 
			    join LU_MISCode m on a.MISCode = m.code
                join AB_Diagnosis d on a.AbstractID = d.AbstractID
                join ICD_DiagFile10 f on d.DiagnosisCode = f.Code
            where ( AdmitDate between @DateFr and @DateTo )
              and ( InstitutionNumber = @InstNoCode )
              and ( 1 = case 
                    when (@CoderNumber < 3) then 1 
                    when (@CoderNumber >= 3 and (IsValidLevel1 in (3, 4) or (@IsCorrection = 1 and IsDeleted in (1, 3))) ) then 1 
                    else 0 end )
              and ( 1 = case 
                    when (@IsCorrection = 0) and (IsSubmitLevel1 <> 1) and (IsDeleted = 2) and (CIHIReturnStatusLevel1 = 1) then 1 
                    when (@IsCorrection = 1) and (IsCorrectLevel1 = 2) and (CIHIReturnStatusLevel1 in (2, 3, 4)) then 1 
                    else 0 end )
		      and m.AmCareGroup = 'ED'
              and left(f.CIHIValue, 4) in ('U071', 'U072')) x
            order by CIHIReturnStatusLevel1, isnull(CIHI_AbstractID, 0), AdmitDate, ChartNumber  -- dbo.SU_ChartNumberFillLeadingZero(ChartNumber)
    end
    else
        insert @Records( AbstractID )
            select AbstractID
            from dbo.AB_Abstract a join dbo.NACRS_CareType_MisCodes(@UseCareType) l on isnull(a.MisCode, 0) = l.Code
            where ( AdmitDate between @DateFr and @DateTo )
              and ( InstitutionNumber = @InstNoCode )
              and ( 1 = case 
                    when (@CoderNumber < 3) then 1 
                    when (@CoderNumber >= 3 and (IsValidLevel1 in (3, 4) or (@IsCorrection = 1 and IsDeleted in (1, 3))) ) then 1 
                    else 0 end )
              and ( 1 = case 
                    when (@IsCorrection = 0) and (IsSubmitLevel1 <> 1) and (IsDeleted = 2) and (CIHIReturnStatusLevel1 = 1) then 1 
                    when (@IsCorrection = 1) and (IsCorrectLevel1 = 2) and (CIHIReturnStatusLevel1 in (2, 3, 4)) then 1 
                    else 0 end )
            order by CIHIReturnStatusLevel1, isnull(CIHI_AbstractID, 0), AdmitDate, ChartNumber  -- dbo.SU_ChartNumberFillLeadingZero(ChartNumber)
end
-- AMCARE INSTITUTIONS, ICD 10 (AND ALBERTA) Level 4 only for both level 1 and level 3, 
--NP - 00125
else if (@SU_Const in ('NAC_I10_SUBMIT')) and @NacrsLevelCode  in (1, 2) and @NACRSLevelSetting in (4, 5) begin

    if(@IsCorrection = 1) begin
--Ticket 11942. client try to correct and meet record not match problem
--Client has IsValidated = 2 and IsDeleted = 1 
        select @FakeRecordCount = count(*)
        from dbo.AB_Abstract a 
            inner join LU_MISCode l on isnull(a.MISCode, 0) = l.code and 
				(((l.CIHIValue like '71310%' or l.CIHIValue like '72310%' or l.CIHIValue like '73310%') and AdmitDate < '2010/04/01') or
				 ((isnull(l.AmCareGroup, '') = 'ED') and AdmitDate >= '2010/04/01'))
            --join dbo.NACRS_CareType_MisCodes(@UseCareType) l on isnull(a.MisCode, 0) = l.Code
        where ( AdmitDate between @DateFr and @DateTo )
          and ( InstitutionNumber = @InstNoCode )
          and ( 1 = case 
                when (@CoderNumber < 3) then 1 
                when (@CoderNumber >= 3 and (IsValidLevel1 in (3, 4) or IsDeleted in (1, 3))) then 1 
                else 0 end )
          and IsSubmitLevel1 = 1
          and (IsCorrectLevel1 = 2) 
          and (CIHIReturnStatusLevel1 in (2, 3, 4)) 
          and (AdmitDate < '2010/04/01' or IsSubmited = 2) --ED - 02102
          --and IsSubmited = 2

        set @DateFr = dbo.SUF_GetPeriodDateRange((select top 1 ProvinceNumber from H_HospitalProfile), @BatchPeriod, @DateTo, 0)
        set @DateTo = dbo.SUF_GetPeriodDateRange((select top 1 ProvinceNumber from H_HospitalProfile), @BatchPeriod, @DateTo, 1)
    end 

    -- PR - 03014 Chatham has IsSubmited = 1 and IsCorrected = 2
    update AB_Abstract 
    set IsCorrectLevel1 = 1
    where InstitutionNumber = @InstNoCode 
        and AdmitDate between @DateFr and @DateTo 
        and IsSubmitLevel1 = 2 
        and IsDeleted = 2 
        and IsCorrectLevel1 <> 1 
        --and IsSubmited = 2
    

    -- ensure that CIHIReturnStatus matches IsSubmited, IsCorrected and IsDeleted flags.
    update AB_Abstract 
    set CIHIReturnStatusLevel1 = 1
    where InstitutionNumber = @InstNoCode 
        and AdmitDate between @DateFr and @DateTo 
        and IsCorrectLevel1 = 1 
        and IsSubmitLevel1 = 2 
        and IsDeleted = 2 
        --and IsSubmited = 2

    update AB_Abstract 
    set CIHIReturnStatusLevel1 = 2 
    where InstitutionNumber = @InstNoCode 
        and AdmitDate between @DateFr and @DateTo 
        and IsSubmitLevel1 = 1 
        and IsCorrectLevel1 = 2 
        and IsDeleted in (1, 3)
        --and IsSubmited = 2

    update AB_Abstract 
    set CIHIReturnStatusLevel1 = 4 
    where InstitutionNumber = @InstNoCode 
        and AdmitDate between @DateFr and @DateTo 
        and IsSubmitLevel1 = 1 
        and IsCorrectLevel1 = 2 
        and IsDeleted = 2 
        and (AdmitDate < '2010/04/01' or IsSubmited = 2) --ED - 02102
        --and IsSubmited = 2

    -- this currently works only for records that have not been Submitted yet. 
    if @UseCareType = 15645 and cast(@DateFr as datetime) >= cast('2017-04-01' as datetime)  --2.x-0920
        insert @Records( AbstractID )
            select AbstractID
            from (select distinct a.AbstractID, a.CIHIReturnStatusLevel1, a.CIHI_AbstractID, a.AdmitDate, a.ChartNumber
            from dbo.AB_Abstract a 
			    join LU_MISCode m on a.MISCode = m.code
                join AB_Diagnosis d on a.AbstractID = d.AbstractID
                join ICD_DiagFile10 f on d.DiagnosisCode = f.Code
                --left join LU_diagnosisPrefix p on d.DiagnosisPrefix = p.code --2.x-1900 remove it
            where ( AdmitDate between @DateFr and @DateTo )
              and ( InstitutionNumber = @InstNoCode )
              and ( 1 = case 
                    when (@CoderNumber < 3) then 1 
                    when (@CoderNumber >= 3 and (IsValidLevel1 in (3, 4) or (@IsCorrection = 1 and IsDeleted in (1, 3))) ) then 1 
                    else 0 end )
              and ( 1 = case 
                    when (@IsCorrection = 0) and (IsSubmitLevel1 <> 1) and (IsDeleted = 2) and (CIHIReturnStatusLevel1 = 1) then 1 
                    when (@IsCorrection = 1) and (IsCorrectLevel1 = 2) and (CIHIReturnStatusLevel1 in (2, 3, 4)) then 1 
                    else 0 end )
              and IsSubmited = 2
		      and m.AmCareGroup = 'ED'
              and left(f.CIHIValue, 4) in ('T400', 'T401', 'T402', 'T403', 'T404', 'T406')
              --and isnull(p.CIHIValue, '') <> 'Q' --2.x-1900 remove it
              ) x
            order by CIHIReturnStatusLevel1, isnull(CIHI_AbstractID, 0), AdmitDate, ChartNumber  -- dbo.SU_ChartNumberFillLeadingZero(ChartNumber)
    else if @UseCareType = 15647 and cast(@DateFr as datetime) >= cast('2019-04-01' as datetime)  --2.x-1804
    begin
        if @NacrsLevelCode = 2 
            insert @Records( AbstractID )
            select AbstractID
            from 
            (select distinct a.AbstractID, a.CIHIReturnStatusLevel1, a.CIHI_AbstractID, a.AdmitDate, a.ChartNumber
            from dbo.AB_Abstract a 
			    join LU_MISCode m on a.MISCode = m.code
                left join AB_Diagnosis d on a.AbstractID = d.AbstractID
                left join ICD_DiagFile10 f on d.DiagnosisCode = f.Code
                left join AB_DischargeDiagnosis dd on a.AbstractID = dd.AbstractID
                left join ICD_DiagFile10 df on dd.DischargeDiagnosis = df.Code
            where ( AdmitDate between @DateFr and @DateTo )
              and ( InstitutionNumber = @InstNoCode )
              and ( 1 = case 
                    when (@CoderNumber < 3) then 1 
                    when (@CoderNumber >= 3 and (IsValidLevel1 in (3, 4) or (@IsCorrection = 1 and IsDeleted in (1, 3))) ) then 1 
                    else 0 end )
              and ( 1 = case 
                    when (@IsCorrection = 0) and (IsSubmitLevel1 <> 1) and (IsDeleted = 2) and (CIHIReturnStatusLevel1 = 1) then 1 
                    when (@IsCorrection = 1) and (IsCorrectLevel1 = 2) and (CIHIReturnStatusLevel1 in (2, 3, 4)) then 1 
                    else 0 end )
		      and m.AmCareGroup = 'ED'
              and (left(f.CIHIValue, 4) in ('U071', 'U072') or left(df.CIHIValue, 4) in ('U071', 'U072'))) x
            order by CIHIReturnStatusLevel1, isnull(CIHI_AbstractID, 0), AdmitDate, ChartNumber  -- dbo.SU_ChartNumberFillLeadingZero(ChartNumber)
        else
            insert @Records( AbstractID )
            select AbstractID
            from (select distinct a.AbstractID, a.CIHIReturnStatusLevel1, a.CIHI_AbstractID, a.AdmitDate, a.ChartNumber
            from dbo.AB_Abstract a 
			    join LU_MISCode m on a.MISCode = m.code
                join AB_Diagnosis d on a.AbstractID = d.AbstractID
                join ICD_DiagFile10 f on d.DiagnosisCode = f.Code
                left join LU_diagnosisPrefix p on d.DiagnosisPrefix = p.code
            where ( AdmitDate between @DateFr and @DateTo )
              and ( InstitutionNumber = @InstNoCode )
              and ( 1 = case 
                    when (@CoderNumber < 3) then 1 
                    when (@CoderNumber >= 3 and (IsValidLevel1 in (3, 4) or (@IsCorrection = 1 and IsDeleted in (1, 3))) ) then 1 
                    else 0 end )
              and ( 1 = case 
                    when (@IsCorrection = 0) and (IsSubmitLevel1 <> 1) and (IsDeleted = 2) and (CIHIReturnStatusLevel1 = 1) then 1 
                    when (@IsCorrection = 1) and (IsCorrectLevel1 = 2) and (CIHIReturnStatusLevel1 in (2, 3, 4)) then 1 
                    else 0 end )
              and IsSubmited = 2
		      and m.AmCareGroup = 'ED'
              and left(f.CIHIValue, 4) in ('U071', 'U072')) x
            order by CIHIReturnStatusLevel1, isnull(CIHI_AbstractID, 0), AdmitDate, ChartNumber  -- dbo.SU_ChartNumberFillLeadingZero(ChartNumber)
    end
    else
        insert @Records( AbstractID )
            select AbstractID
            from dbo.AB_Abstract a 
                inner join LU_MISCode l on isnull(a.MISCode, 0) = l.code and 
				    (((l.CIHIValue like '71310%' or l.CIHIValue like '72310%' or l.CIHIValue like '73310%') and AdmitDate < '2010/04/01') or
				     ((isnull(l.AmCareGroup, '') = 'ED') and AdmitDate >= '2010/04/01'))
                --join dbo.NACRS_CareType_MisCodes(@UseCareType) l on isnull(a.MisCode, 0) = l.Code
            where ( AdmitDate between @DateFr and @DateTo )
              and ( InstitutionNumber = @InstNoCode )
              and ( 1 = case 
                    when (@CoderNumber < 3) then 1 
                    when (@CoderNumber >= 3 and (IsValidLevel1 in (3, 4) or (@IsCorrection = 1 and IsDeleted in (1, 3))) ) then 1 
                    else 0 end )
              and ( 1 = case 
                    when (@IsCorrection = 0) and (IsSubmitLevel1 <> 1) and (IsDeleted = 2) and (CIHIReturnStatusLevel1 = 1) then 1 
                    when (@IsCorrection = 1) and (IsCorrectLevel1 = 2) and (CIHIReturnStatusLevel1 in (2, 3, 4)) then 1 
                    else 0 end )
              and (AdmitDate < '2010/04/01' or IsSubmited = 2) --ED - 02102
            order by CIHIReturnStatusLevel1, isnull(CIHI_AbstractID, 0), AdmitDate, ChartNumber  -- dbo.SU_ChartNumberFillLeadingZero(ChartNumber)
end

--2.x-0278
else if (@SU_Const in ('NAC_I10_SUBMIT')) and @NacrsLevelCode= 0 and @UseLite = 1 begin
	
    if(@IsCorrection = 1) begin
--Ticket 11942. client try to correct and meet record not match problem
--Client has IsValidated = 2 and IsDeleted = 1 
        select @FakeRecordCount = count(*)
        from dbo.AB_Abstract a 
            inner join LU_MISCode l on isnull(a.MISCode, 0) = l.code and 
				 (@UseCareType in (15642, 15646) and l.AmCareGroup in ('CL', 'OT', 'DI')) 
                 and AdmitDate >= '2018/04/01'
            --join dbo.NACRS_CareType_MisCodes(@UseCareType) l on isnull(a.MisCode, 0) = l.Code
        where ( AdmitDate between @DateFr and @DateTo )
          and ( InstitutionNumber = @InstNoCode )
          and ( 1 = case 
                when (@CoderNumber < 3) then 1 
                when (@CoderNumber >= 3 and (IsValidLevel1 in (3, 4) or IsDeleted in (1, 3))) then 1 
                else 0 end )
          and IsSubmitLevel1 = 1
          and (IsCorrectLevel1 = 2) 
          and (CIHIReturnStatusLevel1 in (2, 3, 4)) 
          and IsSubmited = 2
          and IsLiteSubmission = 1

        set @DateFr = dbo.SUF_GetPeriodDateRange((select top 1 ProvinceNumber from H_HospitalProfile), @BatchPeriod, @DateTo, 0)
        set @DateTo = dbo.SUF_GetPeriodDateRange((select top 1 ProvinceNumber from H_HospitalProfile), @BatchPeriod, @DateTo, 1)
    end 

    -- PR - 03014 Chatham has IsSubmited = 1 and IsCorrected = 2
    update AB_Abstract 
    set IsCorrectLevel1 = 1
    where InstitutionNumber = @InstNoCode 
        and AdmitDate between @DateFr and @DateTo 
        and IsSubmitLevel1 = 2 
        and IsDeleted = 2 
        and IsCorrectLevel1 <> 1 
        --and IsSubmited = 2
    

    -- ensure that CIHIReturnStatus matches IsSubmited, IsCorrected and IsDeleted flags.
    update AB_Abstract 
    set CIHIReturnStatusLevel1 = 1
    where InstitutionNumber = @InstNoCode 
        and AdmitDate between @DateFr and @DateTo 
        and IsCorrectLevel1 = 1 
        and IsSubmitLevel1 = 2 
        and IsDeleted = 2 
        --and IsSubmited = 2

    update AB_Abstract 
    set CIHIReturnStatusLevel1 = 2 
    where InstitutionNumber = @InstNoCode 
        and AdmitDate between @DateFr and @DateTo 
        and IsSubmitLevel1 = 1 
        and IsCorrectLevel1 = 2 
        and IsDeleted in (1, 3)
        --and IsSubmited = 2

    update AB_Abstract 
    set CIHIReturnStatusLevel1 = 4 
    where InstitutionNumber = @InstNoCode 
        and AdmitDate between @DateFr and @DateTo 
        and IsSubmitLevel1 = 1 
        and IsCorrectLevel1 = 2 
        and IsDeleted = 2 
        and IsSubmited = 2

    -- this currently works only for records that have not been Submitted yet. 
    insert @Records( AbstractID )
        select AbstractID
        from dbo.AB_Abstract a 
            inner join H_InstitutionProfile h on a.InstitutionNumber = h.code
            inner join LU_MISCode l on isnull(a.MISCode, 0) = l.code and 
				  l.AmCareGroup in ('CL', 'OT', 'DI') and 
                  AdmitDate >= '2018/04/01'
        where ( AdmitDate between @DateFr and @DateTo )
          and ( InstitutionNumber = @InstNoCode )
          and ( 1 = case 
                when (@CoderNumber < 3) then 1 
                when (@CoderNumber >= 3 and (IsValidLevel1 in (3, 4) or (@IsCorrection = 1 and IsDeleted in (1, 3))) ) then 1 
                else 0 end )
          and ( 1 = case 
                when (@IsCorrection = 0) and (IsSubmitLevel1 <> 1) and (IsDeleted = 2) and (CIHIReturnStatusLevel1 = 1) then 1 
                when (@IsCorrection = 1) and (IsCorrectLevel1 = 2) and (CIHIReturnStatusLevel1 in (2, 3, 4)) then 1 
                else 0 end )
          and IsSubmited = 2
          and IsLiteSubmission = 1
        order by CIHIReturnStatusLevel1, isnull(CIHI_AbstractID, 0), AdmitDate, ChartNumber  -- dbo.SU_ChartNumberFillLeadingZero(ChartNumber)
end
------------------------------------------------------------------------------------
-- AMCARE INSTITUTIONS, ICD 9, 9CM
else if (@SU_Const in ('NAC_I9C_SUBMIT')) begin     

    if(@IsCorrection = 1) begin

        select @FakeRecordCount = count(*)
        from dbo.AB_Abstract
        where ( AdmitDate between @DateFr and @DateTo )           and ( InstitutionNumber = @InstNoCode )
          and ( 1 = case 
                when (@CoderNumber < 3) then 1 
                when (@CoderNumber >= 3 and IsValidated in (3, 4)) then 1 
                else 0 end )
          and (IsCorrected = 2) 
          and (CIHIReturnStatus in (2, 3, 4)) 

        set @DateFr = dbo.SUF_GetPeriodDateRange((select top 1 ProvinceNumber from H_HospitalProfile), @BatchPeriod, @DateTo, 0)
        set @DateTo = dbo.SUF_GetPeriodDateRange((select top 1 ProvinceNumber from H_HospitalProfile), @BatchPeriod, @DateTo, 1)
    end

    -- ensure that CIHIReturnStatus matches IsSubmited, IsCorrected and IsDeleted flags.
    update AB_Abstract 
    set CIHIReturnStatus = 1
    where InstitutionNumber = @InstNoCode 
    and AdmitDate between @DateFr and @DateTo 
    and IsCorrected = 1 
    and IsSubmited = 2 
    and IsDeleted = 2 

    update AB_Abstract 
    set CIHIReturnStatus = 2 
    where InstitutionNumber = @InstNoCode 
    and AdmitDate between @DateFr and @DateTo 
    and IsSubmited = 1 
    and IsCorrected = 2 
    and IsDeleted = 1 

    update AB_Abstract 
    set CIHIReturnStatus = 4 
    where InstitutionNumber = @InstNoCode 
    and AdmitDate between @DateFr and @DateTo 
    and IsSubmited = 1 
    and IsCorrected = 2 
    and IsDeleted = 2 

    -- this currently works only for records that have not been Submitted yet.
    insert @Records( AbstractID )
        select AbstractID
        from dbo.AB_Abstract         
        where ( AdmitDate between @DateFr and @DateTo )
          and ( InstitutionNumber = @InstNoCode )
          and ( 1 = case 
                when (@CoderNumber < 3) then 1 
                when (@CoderNumber >= 3 and IsValidated in (3, 4)) then 1 
                else 0 end )
          and ( 1 = case 
                when (@IsCorrection = 0) and (IsSubmited <> 1) and (IsDeleted = 2) and (CIHIReturnStatus = 1) then 1 
                when (@IsCorrection = 1) and (IsCorrected = 2) and (CIHIReturnStatus in (2, 3, 4)) then 1 
                else 0 end )
        order by CIHIReturnStatus, AdmitDate, ChartNumber  -- dbo.SU_ChartNumberFillLeadingZero(ChartNumber)
        

end

------------------------------------------------------------------------------------
-- REHAB SUBMISSION, Admission, Discharge, FollowUp
else if (@SU_Const in ('NRS_DELETIONS', 'NRS_ADMISSION', 'NRS_DISCHARGE', 'NRS_FOLLOW_UP')) begin


    if (@SU_Const = 'NRS_DELETIONS')
        --13242
        insert @Records( AbstractID )
        select AbstractID 
        from RH_ClientInfo r
--        where (( AdmitDate between @DateFr and @DateTo and AssessmentType = 134 )
--           or ( DischargeDate between @DateFr and @DateTo and AssessmentType = 135 )
--           or ( FollowUpDate between @DateFr and @DateTo and AssessmentType = 136 ))
        where ( AdmitDate between @DateFr and @DateTo )
          and ( InstitutionNumber = @InstNoCode )
          and ( IsSubmited = 1 )
          and ( IsCorrected = 2)
          and ( IsDeleted in (1, 3) )
        order by AssessmentType desc, AdmitDate

    else
    if (@SU_Const = 'NRS_ADMISSION')

        insert @Records( AbstractID )
        select AbstractID 
        from RH_ClientInfo 
        where ( AdmitDate between @DateFr and @DateTo )
          and ( InstitutionNumber = @InstNoCode )
          and ( 1 = case 
                when (@IsResubmit = 0 and ( IsSubmited = 2 or IsCorrected = 2 )) then 1 
                when (@IsResubmit = 1) then 1
                else 0 
                end )
          and ( IsDeleted = 2 )           and ( AssessmentType = 134 )
        order by IsCorrected, AdmitDate, ChartNumber

    else
    if (@SU_Const = 'NRS_DISCHARGE')

        insert @Records( AbstractID )
        select AbstractID 
        from RH_ClientInfo 
        where ( DischargeDate between @DateFr and @DateTo )
          and ( InstitutionNumber = @InstNoCode )
          and ( 1 = case 
                when (@IsResubmit = 0 and ( IsSubmited = 2 or IsCorrected = 2 )) then 1 
                when (@IsResubmit = 1) then 1
                else 0 
                end )
          and ( IsDeleted = 2 )
          and ( AssessmentType = 135 )
        order by IsCorrected, AdmitDate, ChartNumber

    else
    if (@SU_Const = 'NRS_FOLLOW_UP')

        insert @Records( AbstractID )
        select AbstractID 
        from RH_ClientInfo 
        where ( FollowUpDate between @DateFr and @DateTo )
          and ( InstitutionNumber = @InstNoCode )
          and ( 1 = case 
                when (@IsResubmit = 0 and ( IsSubmited = 2 or IsCorrected = 2 )) then 1 
                when (@IsResubmit = 1) then 1
                else 0 
                end )
          and ( IsDeleted = 2 )
          and ( AssessmentType = 136 )
        order by IsCorrected, AdmitDate, ChartNumber

end

insert SU_ExecProperties 
       ( ExecutionDate, GroupID,  CoderNumber,  DateStart, DateEnd, InstNoCode,  BatchYear,  BatchPeriod,  IsCorrection,  IsResubmit ) 
values ( @DateSent,     @GroupID, @CoderNumber, @DateFr,   @DateTo, @InstNoCode, @BatchYear, @BatchPeriod, @IsCorrection, @IsResubmit )

set @ExecutionID = @@identity

delete SU_RecordSelect where ExecutionID = @ExecutionID

-- REHAB
if (@SU_Const in ('NRS_DELETIONS', 'NRS_ADMISSION', 'NRS_DISCHARGE', 'NRS_FOLLOW_UP')) begin

    insert SU_RecordSelect ( 
        ExecutionID  , 
        AbstractID   , 
        OrderBy      , 
        IsCorrected  , 
        IsSubmited   , 
        IsValidated  , 
        IsCompleted  , 
        IsDeleted    , 
        CIHIDateSent , 
        BatchYear    , 
        BatchPeriod  , 
        AbstractNumber)
    select 
        @ExecutionID   , 
        r.AbstractID   , 
        r.OrderBy      ,
        a.IsCorrected  ,
        a.IsSubmited   ,
        a.IsValidated  ,
        a.IsCompleted  ,
        a.IsDeleted    ,
        @DateSent      ,
        a.BatchYear    ,
        a.BatchPeriod  ,
        a.AbstractNumber
    from @Records r join RH_ClientInfo a on r.AbstractID = a.AbstractID 
    order by OrderBy

end
else begin
    --NP - 00125
    if (@SU_Const in ('NAC_I10_SUBMIT')) and @NacrsLevelCode in (1, 2)
        insert SU_RecordSelect (          ExecutionID  , 
            AbstractID   , 
            OrderBy      , 
            IsCorrected  , 
            IsSubmited   , 
            IsValidated  , 
            IsCompleted  , 
            IsDeleted    , 
            CIHIDateSent , 
            BatchYear    , 
            BatchPeriod  , 
            BatchNumber  , 
            AbstractNumber,
			SubmissionLevel)
        select 
            @ExecutionID   , 
            r.AbstractID   , 
            r.OrderBy      ,
            a.IsCorrectLevel1  ,
            a.IsSubmitLevel1   ,
            a.IsValidLevel1  ,
            a.IsCompleted  ,
            a.IsDeleted    ,
            @DateSent      ,
            a.BatchYear    ,
            a.BatchPeriod  ,
            a.BatchNumber  ,
            a.AbstractNumber,
			@NACRSLevelCode
        from @Records r join AB_Abstract a on r.AbstractID = a.AbstractID
        order by OrderBy
    else
        insert SU_RecordSelect (          ExecutionID  , 
            AbstractID   , 
            OrderBy      , 
            IsCorrected  , 
            IsSubmited   , 
            IsValidated  , 
            IsCompleted  , 
            IsDeleted    , 
            CIHIDateSent , 
            BatchYear    , 
            BatchPeriod  , 
            BatchNumber  , 
            AbstractNumber,
			SubmissionLevel)
        select 
            @ExecutionID   , 
            r.AbstractID   , 
            r.OrderBy      ,
            a.IsCorrected  ,
            a.IsSubmited   ,
            a.IsValidated  ,
            a.IsCompleted  ,
            a.IsDeleted    ,
            @DateSent      ,
            a.BatchYear    ,
            a.BatchPeriod  ,
            a.BatchNumber  ,
            a.AbstractNumber,
			@NACRSLevelCode 
        from @Records r join AB_Abstract a on r.AbstractID = a.AbstractID
        order by OrderBy
    
end


-- set the total number of records: 
set @RecordCount = @@rowcount
--PR - 05785 Not sure why the @FakeRecordCount is assigned to @RecordCount. disable this code
--if(@FakeRecordCount > -1) set @RecordCount = @FakeRecordCount


delete from @Records

DBCC DBREINDEX (SU_RecordSelect)


-- If this is a normal submission, the Batch Number must 
-- start at 1 PLUS where the last one Batch Number left off.
-- Otherwise, just start at 1
if (@IsCorrection = 0 and (@IsResubmit = 0 or @CoderNumber > 2)) 
begin
    set @BatchStart = 1 + isnull( 
        (
            select max(BatchNumber)
            from AB_Abstract
            where BatchYear = @BatchYear
            and BatchPeriod = @BatchPeriod
            and InstitutionNumber = @InstNoCode
            and IsSubmited = 1
        ), 0)
    if @AppID in (200, 201, 202) and @BatchStart = 1
    begin
        if exists (select * from dbo.SU_ExecProperties where ExecutionID < @ExecutionID and InstNoCode = @InstNoCode
                and BatchYear = @BatchYear and BatchPeriod = @BatchPeriod and RecordWidth is null)
            set @BatchStart = 2
    end
end
else
    set @BatchStart = 1

------------------------------------------------------------------------------------
-- for Amcare 10
if @SU_Const = 'NAC_I10_SUBMIT' begin

    -- if it is a Correction just set the values for the Correction
    -- if not, reset the Batch Year, Period, BatchNumber and AbstractNumber fields
    if (@IsCorrection = 0) 
    begin
		declare @CIHI_AbstractID int --ED - 02104
        --EN-00057
        --PR - 01629
        -- set @MaxCIHI_AbstractID = isnull((select max(ab.AbstractNumber) from AB_Abstract ab 
        --    where ab.CareType = 5 and ab.IsSubmited = 1 and ab.BatchYear = @BatchYear 
        --        and BatchPeriod = @BatchPeriod and ab.AbstractNumber < 9000000), 0)
        --ED - 02104 I feel this is not acurate
        --set @MaxCIHI_AbstractID = isnull((select max(ab.AbstractNumber) from AB_Abstract ab 
        --    where ab.CareType = 5 and ab.BatchYear = @BatchYear 
        --        and BatchPeriod = @BatchPeriod and ab.AbstractNumber < 9000000), 0)
        
        select @MaxCIHI_AbstractID = max((case when isnull(AbstractNumber, 0) < 9000000 then isnull(AbstractNumber, 0) else 0 end)),
			   @CIHI_AbstractID = max((case when isnull(CIHI_AbstractID, 0) < 9000000 then isnull(CIHI_AbstractID, 0) else 0 end))
        from AB_Abstract
        --PR - 05192 ticket EN - 00464 use partail period. That cause duplicate abstractid issue. change to use whole period.
        --where InstitutionNumber = @InstNoCode and AdmitDate between @DateFr and @DateTo 
        where InstitutionNumber = @InstNoCode and AdmitDate between @DateFromPeriod and @DateToPeriod 
            
		
		if @MaxCIHI_AbstractID is null set @MaxCIHI_AbstractID = 0
		if @CIHI_AbstractID >  @MaxCIHI_AbstractID set @MaxCIHI_AbstractID = isnull(@CIHI_AbstractID, 0)

        update SU_RecordSelect 
        set IsSubmited     = 1, 
            IsCorrected    = 1, 
            IsCompleted    = 4,
            BatchYear      = @BatchYear, 
            BatchPeriod    = @BatchPeriod, 
            BatchNumber    = @BatchStart,
       	    --PR-01550
            AbstractNumber = (case when @ProvNoCIHI = '8' then a.AbstractID  --Ticket PR-00915
                              when isnull(a.CIHI_AbstractID, 0) > 0 then a.CIHI_AbstractID                                    
                              when isnull(a.AbstractNumber, 0) > 0 and a.BatchYear > 0 and a.BatchPeriod > 0 then a.AbstractNumber  --NP - 00125                                  
                              else s.OrderBy + @MaxCIHI_AbstractID end) 

--             AbstractNumber = (case when isnull(a.CIHI_AbstractID, 0) >= 9000000 then a.CIHI_AbstractID 
--                                    when @BatchYear < 2006 or @ProvNoCIHI = '8' then a.AbstractID  --Ticket PR-00915
--                                    when @IsResubmit = 1 and @CoderNumber <= 2 and isnull(a.AbstractNumber, 0) > 0 then a.AbstractNumber
--                                    else s.OrderBy + @MaxCIHI_AbstractID end) --, --a.AbstractID -- ** Use AbstractID for AbstractNumber in NACRS ICD 10 
-- --            CIHI_AbstractID = (case when isnull(a.CIHI_AbstractID, 0) > 8999999 then a.CIHI_AbstractID when @BatchYear < 2006 then a.AbstractID else s.OrderBy + @MaxCIHI_AbstractID end)
        from AB_Abstract a 
        join SU_RecordSelect s on a.AbstractID = s.AbstractID and s.ExecutionID = @ExecutionID
        --PR - 05128 Duplicate Abstract ID -----------------------------
        declare @ID int
        declare Cur_Dup_ID cursor STATIC for
            select s.AbstractID 
            from SU_RecordSelect s inner join
                (select AbstractNumber, min(AbstractID) as minID from SU_RecordSelect 
                 where ExecutionID = @ExecutionID and AbstractNumber < 9000000 
                 group by AbstractNumber having count(*) > 1) d
                 on s.AbstractNumber = d.AbstractNumber 
            where s.ExecutionID = @ExecutionID and s.AbstractID <> d.minID
        
        set @MaxCIHI_AbstractID = @MaxCIHI_AbstractID + 1
        set @CIHI_AbstractID = isnull((select max(AbstractNumber) from SU_RecordSelect where ExecutionID = @ExecutionID), 0) + 1
        if @CIHI_AbstractID > @MaxCIHI_AbstractID set @MaxCIHI_AbstractID = @CIHI_AbstractID
        
        open Cur_Dup_ID
        fetch next from Cur_Dup_ID into @ID
        while(@@fetch_status = 0)
        begin
            update SU_RecordSelect 
            set AbstractNumber = @MaxCIHI_AbstractID
            where AbstractID = @ID and ExecutionID = @ExecutionID
            
            set @MaxCIHI_AbstractID = @MaxCIHI_AbstractID + 1
            fetch next from Cur_Dup_ID into @ID            
        end         
        close Cur_Dup_ID
        deallocate Cur_Dup_ID
        --end  PR - 05128 ---------------------------------------------   
    end
    else if (@IsCorrection = 1)

        update SU_RecordSelect 
        set IsSubmited   = 1, 
            IsCorrected  = 3, 
            IsCompleted  = 4
        from AB_Abstract a 
        join SU_RecordSelect s on a.AbstractID = s.AbstractID and s.ExecutionID = @ExecutionID
end

------------------------------------------------------------------------------------
-- for Amcare 9, 9cm, (Alberta)
else if (@SU_Const = 'NAC_I9C_SUBMIT') begin

    -- if it is a Correction just set the values for the Correction
    -- if not, reset the Batch Year, Period, BatchNumber and AbstractNumber fields
    if (@IsCorrection = 0) 
    
        update SU_RecordSelect 
        set IsSubmited     = 1, 
            IsCorrected    = 1, 
            IsCompleted    = 4,
            BatchYear      = @BatchYear, 
            BatchPeriod    = @BatchPeriod, 
            BatchNumber    = @BatchStart,
            AbstractNumber = s.OrderBy 
        from AB_Abstract a 
        join SU_RecordSelect s on a.AbstractID = s.AbstractID and s.ExecutionID = @ExecutionID
    
    else if (@IsCorrection = 1)

        update SU_RecordSelect 
        set IsSubmited   = 1, 
            IsCorrected  = 3, 
            IsCompleted  = 4
        from AB_Abstract a 
        join SU_RecordSelect s on a.AbstractID = s.AbstractID and s.ExecutionID = @ExecutionID

end

------------------------------------------------------------------------------------
-- for InPatient
else if (@SU_Const in ('DAD_I10_SUBMIT', 'DAD_I9C_SUBMIT')) begin 

    -- if it is a Correction just set the values for the Correction
    -- if not, reset the Batch Year, Period, BatchNumber and AbstractNumber fields
    if (@IsCorrection = 0 and @IsResubmit <> 2)     --EN - 00519 I just duplicate use @IsResubmit <> 2.
    
        update SU_RecordSelect 
        set IsSubmited     = 1, 
            IsCorrected    = 1, 
            IsCompleted    = 4,
            BatchYear      = @BatchYear, 
            BatchPeriod    = @BatchPeriod, 
            BatchNumber    = (((s.OrderBy - 1) / 100) + @BatchStart), 
            AbstractNumber = (((s.OrderBy - 1) % 100) + 1)
        from AB_Abstract a 
        join SU_RecordSelect s on a.AbstractID = s.AbstractID and s.ExecutionID = @ExecutionID
    
    else if (@IsCorrection = 1)

        update SU_RecordSelect 
        set IsSubmited   = 1, 
            IsCorrected  = 3, 
            IsCompleted  = 4
        from AB_Abstract a 
        join SU_RecordSelect s on a.AbstractID = s.AbstractID and s.ExecutionID = @ExecutionID
end
------------------------------------------------------------------------------------
-- for REHAB
else if (@SU_Const in ('NRS_DELETIONS', 'NRS_ADMISSION', 'NRS_DISCHARGE', 'NRS_FOLLOW_UP')) begin 

    update SU_RecordSelect 
    set IsSubmited     = 1, 
        IsCorrected    = 1, 
        IsCompleted    = 4,
        BatchYear      = @BatchYear, 
        BatchPeriod    = @BatchPeriod, 
        AbstractNumber = r.AbstractID
    from RH_ClientInfo r 
    join SU_RecordSelect s on r.AbstractID = s.AbstractID and s.ExecutionID = @ExecutionID
    where r.IsSubmited = 2 

    update SU_RecordSelect 
    set IsSubmited   = 1, 
        IsCorrected  = 3, 
        IsCompleted  = 4
    from RH_ClientInfo r 
    join SU_RecordSelect s on r.AbstractID = s.AbstractID and s.ExecutionID = @ExecutionID
    where r.IsCorrected = 2

end



------------------------------------------------------------------------------------
-- CALCULATE VARIOUS RUNTIME PROPERTIES NEEDED TO RUN THE SUBMISSION PROGRAM.

if (0 < (select count(*) from SU_RecordSelect)) 
    select @BatchCount = ((count(*) - 1) / 100) + 1 from SU_RecordSelect where ExecutionID = @ExecutionID
else 
    set @BatchCount = 0

select @RecordWidth = sum( TextLength ) from SU_StructureFile where GroupID = @GroupID
select @InstNoCIHI = CIHIValue from H_InstitutionProfile where Code = @InstNoCode
--Hack, How about for BC: Rehab and CCRS
if exists ( select * from H_HospitalProfile where ProvinceNumber <> 14 ) and 
    @BatchPeriod in (15401,15402,15403,15404,15405,15651,15652,15653,
        15654,15655,15656,15657,15658,15659,15660,15661,15662)
    select @BatPerCIHI = CIHIValue from LU_CodeFile where Code = @BatchPeriod
else
    select @BatPerCIHI = CIHIValue from LU_BatchPeriod where Code = @BatchPeriod

select @IsUseMentalHealth = UseMentalHealthData from H_InstitutionProfile where Code = @InstNoCode

--PR - 00316  Some chart can pass WinRecs validation without provider service and specialty. CIHI will give errors.
if @AppID = 401 --and @IsCorrection = 0
begin
    if exists (select top 1 p.* 
               from SU_RecordSelect r 
                inner join AB_Provider p on r.abstractID = p.AbstractID and r.ExecutionID = @ExecutionID
               where isnull(p.ProviderSpecialty, 0) = 0 and ProviderNumber > 0)
        Update AB_Provider
        set ProviderSpecialty = s.Code
        from AB_Abstract a 
            inner join SU_RecordSelect r on a.AbstractID = r.AbstractID and r.ExecutionID = @ExecutionID
            inner join AB_Provider p on a.abstractID = p.AbstractID 
            inner join llu_ProviderSpecialty s on p.ProviderNumber = s.AssociationID
        where isnull(p.ProviderSpecialty, 0) = 0 and s.type = 1 and a.Admitdate between s.ValidFrom and s.ValidTo
            and p.ProviderNumber > 0
            
    if exists (select top 1 p.* 
               from SU_RecordSelect r 
                inner join AB_Intervention p on r.abstractID = p.AbstractID and r.ExecutionID = @ExecutionID
               where isnull(p.IntervProviderService, 0) = 0 and IntervProviderNumber > 0)
        Update AB_Intervention
        set IntervProviderService = s.Code
        from AB_Abstract a 
            inner join SU_RecordSelect r on a.AbstractID = r.AbstractID and r.ExecutionID = @ExecutionID
            inner join AB_Intervention p on a.abstractID = p.AbstractID 
            inner join llu_ProviderSpecialty s on p.IntervProviderNumber = s.AssociationID
        where isnull(p.IntervProviderService, 0) = 0 and s.type = 1 and a.Admitdate between s.ValidFrom and s.ValidTo
            and p.IntervProviderNumber > 0
    --2.x-1575 Consult Service is blank.
    if exists (select top 1 p.* 
               from SU_RecordSelect r 
                inner join AB_Consult p on r.abstractID = p.AbstractID and r.ExecutionID = @ExecutionID
               where isnull(p.ConsultService, 0) = 0 and ConsultNumber > 0)
        Update AB_Consult
        set ConsultService = s.Code
        from AB_Abstract a 
            inner join SU_RecordSelect r on a.AbstractID = r.AbstractID and r.ExecutionID = @ExecutionID
            inner join AB_Consult p on a.abstractID = p.AbstractID 
            inner join llu_ProviderSpecialty s on p.ConsultNumber = s.AssociationID
        where isnull(p.ConsultService, 0) = 0 and s.type = 1 and a.Admitdate between s.ValidFrom and s.ValidTo
            and p.ConsultNumber > 0

end
else if @AppID in (201, 202) --and @IsCorrection = 0
begin
    if exists (select top 1 p.* 
               from SU_RecordSelect r 
                inner join AB_Provider p on r.abstractID = p.AbstractID and r.ExecutionID = @ExecutionID
               where isnull(p.ProviderService, 0) = 0 and ProviderNumber > 0)
        Update AB_Provider
        set ProviderService = s.Code
        from AB_Abstract a 
            inner join SU_RecordSelect r on a.AbstractID = r.AbstractID and r.ExecutionID = @ExecutionID
            inner join AB_Provider p on a.abstractID = p.AbstractID 
            inner join llu_ProviderServices S on p.ProviderNumber = s.AssociationID
            inner join lu_ProviderService l on s.code = l.code and len(CIHIValue) = 5
        where isnull(p.ProviderService, 0) = 0 and s.type = 1 and a.DischargeDate between s.ValidFrom and s.ValidTo
            and p.ProviderNumber > 0

    if exists (select top 1 p.* 
               from SU_RecordSelect r 
                inner join AB_Intervention p on r.abstractID = p.AbstractID and r.ExecutionID = @ExecutionID
               where isnull(p.IntervProviderService, 0) = 0 and IntervProviderNumber > 0)
        Update AB_Intervention
        set IntervProviderService = s.Code
        from AB_Abstract a 
            inner join SU_RecordSelect r on a.AbstractID = r.AbstractID and r.ExecutionID = @ExecutionID
            inner join AB_Intervention p on a.abstractID = p.AbstractID 
            inner join llu_ProviderServices S on p.IntervProviderNumber = s.AssociationID
            inner join lu_ProviderService l on s.code = l.code and len(CIHIValue) = 5
        where isnull(p.IntervProviderService, 0) = 0 and s.type = 1 and a.DischargeDate between s.ValidFrom and s.ValidTo
            and p.IntervProviderNumber > 0
end

-----------------------------------------------------------------------------------
-- UPDATE THE EXECUTION PROPERTIES TABLE WITH THE VARIOUS VALUES
update SU_ExecProperties
set ICDType     = @ICDType    ,
    AppID       = @AppID      ,
    BatchStart  = @BatchStart ,
    BatchCount  = @BatchCount ,
    RecordCount = @RecordCount,
    RecordWidth = @RecordWidth,
    ProvNoCIHI  = @ProvNoCIHI ,
    InstNoCIHI  = @InstNoCIHI ,     BatPerCIHI  = @BatPerCIHI ,
    IsUseMentalHealth = @IsUseMentalHealth,
    NacrsLevelCode = @NacrsLevelCode,
    Su_Type = @Su_Type
where ExecutionID = @ExecutionID

EXIT_PROCEDURE_NORMAL:
    return 0

ERROR___:
    return 1
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE procedure [SU_MADE_Initialize]
      @SU_Type int
    , @PrevExecID  int
    , @BatchStart  int output
    , @BatchCount  int output
    , @RecordCount int output
    , @RecordWidth int output
    , @ExecutionID int output
    , @ProvNoCIHI  varchar(1) output
    , @InstNoCIHI  varchar(5) output
    , @BatPerCIHI  varchar(2) output
as

declare
      @GroupID   int
    , @AppID     int
    , @BatchYear int
    , @ProvCode  int
    , @SU_Const  varchar(20)

select @SU_Const = su_const from SU_StructureType where su_id = @SU_Type
select @BatchYear = BatchYear from SU_ExecProperties where ExecutionID = @PrevExecID
set @ProvCode = 11
set @AppID = 201
set @GroupID = dbo.SUF_GET_GroupID(@SU_Type, @AppID, @BatchYear, @ProvCode, 0)

PRINT '@GroupID = ' + isnull( CONVERT(nvarchar, @GroupID), '<NULL>' ) 

insert SU_ExecProperties 
    ( ExecutionDate
    , CoderNumber
    , GroupID
    , DateStart
    , DateEnd
    , InstNoCode
    , ICDType
    , AppID
    , BatchYear
    , BatchPeriod
    , IsCorrection
    , IsResubmit
    , BatchStart
    , BatchCount
    , RecordCount
    , RecordWidth
    , ProvNoCIHI
    , InstNoCIHI
    , BatPerCIHI )
select
      ExecutionDate
    , CoderNumber
    , GroupID = @GroupID
    , DateStart
    , DateEnd
    , InstNoCode
    , ICDType
    , AppID
    , BatchYear
    , BatchPeriod
    , IsCorrection
    , IsResubmit
    , BatchStart
    , BatchCount
    , RecordCount
    , RecordWidth = (select sum(TextLength) from SU_StructureFile where GroupID = @GroupID)
    , ProvNoCIHI
    , InstNoCIHI
    , BatPerCIHI
from SU_ExecProperties
where ExecutionID = @PrevExecID

set @ExecutionID = @@identity

delete SU_RecordSelect where ExecutionID = @ExecutionID

insert SU_RecordSelect
    ( ExecutionID
    , AbstractID
    , OrderBy
    , IsCorrected
    , IsSubmited
    , IsValidated
    , IsCompleted
    , IsDeleted
    , CIHIDateSent
    , BatchYear
    , BatchPeriod
    , BatchNumber
    , AbstractNumber )
select
      @ExecutionID
    , AbstractID
    , OrderBy
    , IsCorrected
    , IsSubmited
    , IsValidated
    , IsCompleted
    , IsDeleted
    , CIHIDateSent
    , BatchYear
    , BatchPeriod
    , BatchNumber
    , AbstractNumber
from SU_RecordHistory h
where ExecutionID = @PrevExecID

DBCC DBREINDEX ( SU_RecordSelect )

select 
      @BatchStart  = BatchStart
    , @BatchCount  = BatchCount
    , @RecordCount = RecordCount
    , @RecordWidth = RecordWidth
    , @ProvNoCIHI  = ProvNoCIHI
    , @InstNoCIHI  = InstNoCIHI
    , @BatPerCIHI  = BatPerCIHI
from SU_ExecProperties 
where ExecutionID = @ExecutionID

return 0







GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE procedure [SU_ManageTempTables] 
    @ExecutionID int,
    @IsDropOnly  bit = 0
as

declare @sql varchar(200)
declare @TblSource varchar(50)
declare @TblTarget varchar(50)
declare @CareType nvarchar(100)	--ED - 02385
declare @AppID int --ED - 02385

declare @IXFldName varchar(50)

declare curTbls cursor local fast_forward for
    select distinct
        TblSource = TableName,
        TblTarget = dbo.SUF_GetTempTable ( ExecutionID, TableName )
    from SU_ExecProperties x join SU_StructureFile  s on x.GroupID = s.GroupID
    where ExecutionID = @ExecutionID
    and nullif(TableName, '') is not null
    
open curTbls

while (1 = 1) begin    
    
    fetch next from curTbls into @TblSource, @TblTarget
    if (@@fetch_status <> 0) break

    -- if ((select object_id(N'tempdb..##BO1AB_Abstract')) is not null) drop table ##BO1AB_Abstract 
    set @sql = 'if ((select object_id( N''' + @TblTarget + ''' )) is not null) drop table ' + @TblTarget 
    exec (@sql)
    print @sql


    if (@IsDropOnly = 0) begin 

		--ED - 02385
		if (@TblTarget = 'AB_SpecialProjects')
		begin
			set @AppID = (select AppID from dbo.SU_ExecProperties where ExecutionID = @ExecutionID)
			set @CareType = (case when @AppID = 201 then '1'
								  when @AppID = 202 then '2'
								  when @AppID between 250 and 253 then '3'
								  when @AppID between 470 and 479 then '4'
								  when @AppID = 401 then '5'
								  when @AppID between 650 and 659 then '7'
								  else '0' end)
		   						  
		end
		else 
			set @CareType = ''
					-- select a.* into ##BO1AB_Abstract 
        -- from SU_RecordSelect s join AB_Abstract a on s.AbstractID = a.AbstractID 
        -- where s.ExecutionID = @ExecutionID 
        set @sql = 
            'select a.* into ' + @TblTarget + ' ' + 
            'from SU_RecordSelect b join ' + @TblSource + ' a on b.AbstractID = a.AbstractID ' + (case when @CareType = '' then '' else ' and a.CareType = ''' + @CareType + ''' ' end) + 
            'where b.ExecutionID = ' + convert( varchar(5), @ExecutionID )
        exec (@sql)
        print @sql
    
        -- create index tmpIDX_BO1AB_Abstract_AbstractID on ##BO1AB_Abstract ( AbstractID ) 
        set @sql = 'create index tmpIDX_' + @TblTarget + '_AbstractID on ' + @TblTarget + ' ( AbstractID ) '
        exec (@sql)
        print @sql
    
        -- catch tables with Occurrence Number fields
        set @IXFldName = case @TblSource 
            when 'AB_Diagnosis'        then 'DiagnosisOccurrence'
            when 'AB_Intervention'     then 'IntervOccurrence'
            when 'AB_MIS'              then 'MISOccurrence'
            when 'AB_PatientService'   then 'ServiceOccurrence'
            when 'AB_Project'          then 'ProjectOccurrence'
            when 'AB_Provider'         then 'ProviderOccurrence'
            when 'AB_SpecialCareUnit'  then 'SCUOccurrence'
            when 'CRS_Signature'       then 'ProviderOccurrence'
            when 'AB_SpecialProjects'  then 'OccurrenceNumber'
            else ''
        end 
    
        if ( @IXFldName <> '' ) begin
            set @sql = 'create index tmpIDX_' + @TblTarget  + '_' + @IXFldName + ' on ' + @TblTarget + ' ( ' + @IXFldName + ' ) '
            exec (@sql)
            print @sql
        end
    
        -- catch tables an other fields 
        set @IXFldName = case @TblSource 
            when 'AB_Diagnosis'        then 'DiagnosisCode'
            when 'AB_Intervention'     then 'IntervCode'
            else ''
        end 
    
        if ( @IXFldName <> '' ) begin
            set @sql = 'create index tmpIDX_' + @TblTarget + '_' + @IXFldName + ' on ' + @TblTarget + ' ( ' + @IXFldName + ' ) '
            exec (@sql)
            print @sql
        end
    end
end 

return 0




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [SU_NACRS_Project_Level1]
    @ExecutionID  int
AS
    declare @SQL varchar(800)
    declare @tbl varchar(50)
    declare @tbl_ab varchar(50)

    declare @ICDType char(1)
    
    select 
        @ICDType = ICDType
    from SU_ExecProperties
    where ExecutionID = @ExecutionID

----------------------------------------------------------------------------------------------
    -- ReSequence the Project Occurrences 
    if ((select object_id('tempdb..#SU_ProjectReSequence')) is not null) drop table #SU_ProjectReSequence
    create table #SU_ProjectReSequence 
    (
        AbstractID int null,
        ProjectOccurrence int null,
        NewOccurrence int null,
        OrderBy int identity(1,1)
    )

    --PR - 04796 Remove project number < 500

    set @tbl = dbo.SUF_GetTempTable ( @ExecutionID, 'AB_Project' )
	set @SQL = 'Delete from ' + @tbl + ' where (ProjectNumber > 0 and 
			isnull(Question1, 0) = 0 and isnull(Question2, 0) = 0 and isnull(Question3, 0) = 0 and
			isnull(Question4, 0) = 0 and isnull(Question5, 0) = 0 and isnull(Question6, 0) = 0 and
			isnull(Question7, 0) = 0 and isnull(Question8, 0) = 0 and isnull(Question9, 0) = 0 and
			isnull(Question10, 0) = 0 and isnull(Question11, 0) = 0 and 
			isnull(Question12, 0) = 0 and isnull(Question13, 0) = 0 and 
			isnull(Question14, '''') = '''' and isnull(Question15, '''') = '''' and
			isnull(Question16, '''') = '''' and isnull(Question17, '''') = '''')
			or (isnull((select top 1 cast(right((case when isnumeric(cihivalue) = 1 then cihivalue else null end), 3) as int)
			    from lu_project where code = projectnumber), 0) < 500)'
    --print @sql
	exec (@sql)
	if @@rowcount > 0
	begin
    set @SQL = 
        'select AbstractID, ProjectOccurrence from ' + @tbl 
        
		-- select Doctors only
		insert into #SU_ProjectReSequence ( AbstractID, ProjectOccurrence ) exec ( @SQL )

		update #SU_ProjectReSequence
		set NewOccurrence = (r.OrderBy - minSeed.minOcc) + 1
		from #SU_ProjectReSequence r 
		join (
			select AbstractID, minOcc = min(OrderBy) 
			from #SU_ProjectReSequence
			group by AbstractID 
		) minSeed on r.AbstractID = minSeed.AbstractID 


		set @SQL = 
			'update ' + @tbl + ' ' + 
			'set ProjectOccurrence = r.NewOccurrence ' + 
			'from ' + @tbl + ' s join #SU_ProjectReSequence r ' +
			'on s.AbstractID = r.AbstractID and s.ProjectOccurrence = r.ProjectOccurrence '
		exec( @SQL )
		--
	end
	if ((select object_id('tempdb..#SU_ProjectReSequence')) is not null) drop table #SU_ProjectReSequence

    return 0
----------------------------------------------------------------------------------------------
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE   PROCEDURE [SU_NACRS_ReasonForVisit]
    @ExecutionID  int
AS
    declare @SQL varchar(800)
    declare @tbl varchar(50)
    declare @tbl_ab varchar(50)

    declare @ICDType char(1)

    select 
        @ICDType = ICDType
    from SU_ExecProperties
    where ExecutionID = @ExecutionID

----------------------------------------------------------------------------------------------
    -- ReSequence the Diagnosis Occurrences based on non R codes and R Codes
    -- Occurrence 1 to 10  will be NON-R-Codes
    -- Occurrence 11 will be R-Codes
    if ((select object_id('tempdb..#SU_ReSequence')) is not null) drop table #SU_ReSequence
    create table #SU_ReSequence 
    (
        AbstractID int null,
        DiagnosisOccurrence int null,
        NewOccurrence int null,
        IsRCode bit null,
        OrderBy int identity(1,1)
    )


    set @tbl = dbo.SUF_GetTempTable ( @ExecutionID, 'AB_Diagnosis' )
    set @tbl_ab = dbo.SUF_GetTempTable ( @ExecutionID, 'AB_Abstract' )

    set @SQL = 
        'select s.AbstractID, s.DiagnosisOccurrence, IsRCode = (case when f.CIHIValue = ''R'' and m.CIHIValue like ''7_310%'' then 1 else 0 end) ' +
        'from ' + @tbl + ' s inner join ' + @tbl_ab + ' ab on s.abstractid = ab.abstractid ' +
        'left join lu_diagnosisprefix f on s.DiagnosisPrefix = f.Code ' + 
        'left join lu_miscode m on ab.MISCode = m.Code ' + 
        'order by s.AbstractID, (case when f.CIHIValue = ''R'' and s.DiagnosisOccurrence = 1 then 0 when f.CIHIValue = ''R'' and m.CIHIValue like ''7_310%'' then 1 else 0 end), s.DiagnosisOccurrence '
        
    -- select Doctors only
    insert into #SU_ReSequence ( AbstractID, DiagnosisOccurrence, IsRCode ) exec ( @SQL )


    update #SU_ReSequence
    set NewOccurrence = ((r.OrderBy - minSeed.minOcc) + 1)
    from #SU_ReSequence r 
    join (
        select AbstractID, minOcc = min(OrderBy)  --IsRCode, 
        from #SU_ReSequence
        where IsRCode = 0 or DiagnosisOccurrence = 1
        group by AbstractID --, IsRCode
    ) minSeed on r.AbstractID = minSeed.AbstractID and (r.IsRCode = 0 or DiagnosisOccurrence = 1)

    update #SU_ReSequence
    set NewOccurrence = ((r.OrderBy - minSeed.minOcc) + 11)
    from #SU_ReSequence r 
    join (
        select AbstractID, minOcc = min(OrderBy) --, IsRCode
        from #SU_ReSequence
        where IsRCode = 1 and DiagnosisOccurrence <> 1
        group by AbstractID --, IsRCode
    ) minSeed on r.AbstractID = minSeed.AbstractID and r.IsRCode = 1 and DiagnosisOccurrence <> 1

    delete #SU_ReSequence where NewOccurrence > 10 and IsRCode = 0
    delete #SU_ReSequence where NewOccurrence > 11 and IsRCode = 1 

    set @SQL = 
        'delete ' + @tbl + ' ' + 
        'from ' + @tbl + ' s left join #SU_ReSequence r ' +
        'on s.AbstractID = r.AbstractID and s.DiagnosisOccurrence = r.DiagnosisOccurrence ' +
        'where r.DiagnosisOccurrence is null '
    exec( @SQL )
    
    set @SQL = 
        'update ' + @tbl + ' ' + 
        'set DiagnosisOccurrence = r.NewOccurrence ' + 
        'from ' + @tbl + ' s join #SU_ReSequence r ' +
        'on s.AbstractID = r.AbstractID and s.DiagnosisOccurrence = r.DiagnosisOccurrence '
    exec( @SQL )
    --
    set @sql = 'insert ' + @tbl + '(AbstractID, DiagnosisOccurrence, DiagnosisCode) ' +
        'select s.abstractid, 11, s.diagnosiscode ' +
        'from ' + @tbl + ' s join #SU_ReSequence r ' +
        'on s.AbstractID = r.AbstractID and s.DiagnosisOccurrence = r.DiagnosisOccurrence ' +
        'left join #SU_ReSequence v on s.AbstractID = v.AbstractID and v.NewOccurrence = 11 ' +
        'where s.DiagnosisOccurrence = 1 and r.IsRCode = 1 and v.abstractid is null '
    print @sql
    exec(@sql)

    set @sql = 'update ' + @tbl + ' ' +
        'set diagnosisprefix = null ' +
        'from ' + @tbl + ' s join #SU_ReSequence r ' +
        'on s.AbstractID = r.AbstractID and s.DiagnosisOccurrence = r.DiagnosisOccurrence ' +
        'where s.DiagnosisOccurrence = 1 and r.IsRCode = 1 '
    exec(@sql)

    if ((select object_id('tempdb..#SU_ReSequence')) is not null) drop table #SU_ReSequence


    return 0
----------------------------------------------------------------------------------------------




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE  procedure [SU_OMHRS_CIHIError_GetAbstractID]
    @Z1 varchar(2),
    @X1 int,
    @AA3 varchar(12),
    @ChartNumber varchar(12),
    @Institution varchar(12),
    @AbstractID int output
as

set @AbstractID = -1

if @z1 = '8'
    select top 1 @AbstractID = ab.AbstractID 
    from OMHRS_SecAA AB 
        inner join dbo.OMHRS_Medication m on ab.AbstractID = m.AbstractID
        inner join H_InstitutionProfile H on Ab.InstitutionNumber = H.Code
    where ChartNumber = @ChartNumber
    and AA3 = @AA3
    and m.X1 = @X1
    and @Institution = H.CIHIValue
else
    select @AbstractID = AbstractID 
    from OMHRS_SecAA AB 
        inner join H_InstitutionProfile H on Ab.InstitutionNumber = H.Code
    where ChartNumber = @ChartNumber
    and AA3 = @AA3
    and X1 = @X1
    and @Institution = H.CIHIValue

set @AbstractID = isnull(@AbstractID, -1)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE  procedure [SU_OMHRS_CIHIError_ProcessError]
    @AbstractID int,  @RecordType varchar(2), @X1 int
as
    declare @IsSubmited int, @IsCorrected int, @X2 varchar(12)

    select top 1 @IsSubmited = IsSubmited, @IsCorrected = IsCorrected from dbo.OMHRS_RecInfo where AbstractID = @AbstractID
    select top 1 @X2 = l.CIHIValue
    from dbo.OMHRS_SecAA aa inner join LU_CodeFile l on aa.X2 = l.Code
    where aa.AbstractID = @AbstractID

    if @RecordType = '8'  --Medication
    begin
        if @X2 = 'C'
        begin
            if @IsCorrected in (1, 3)
                update dbo.OMHRS_RecInfo set IsSubmited = 1,  IsCorrected = 2 where AbstractID = @AbstractID
        end
        else if @X2 = 'N' and @IsSubmited = 1
        begin
            update dbo.OMHRS_RecInfo set IsCorrected = 2 where AbstractID = @AbstractID
            update dbo.OMHRS_SecAA set X2 = 200302 where AbstractID = @AbstractID
        end
        delete from dbo.SU_Record_Submited_OMH_MED where AbstractID = @AbstractID and X1 = @X1 and IsCorrected = 1
    end
    else
    begin
        if @IsCorrected <> 3 and @X2 <> 'D'
        begin
            update dbo.OMHRS_SecAA
            set X2 = 200301    --(select top 1 code from lu_codeFile where lookupid = 501 and cihivalue = 'N')
            where AbstractID = @AbstractID 
            delete from dbo.SU_Record_Submited_OMH_MED where AbstractID = @AbstractID
        end
        if @IsCorrected <> 3 
            update dbo.OMHRS_RecInfo
            set IsSubmited = 2, 
                IsCorrected = 1
            where AbstractID = @AbstractID and IsDeleted = 2
        else
            update dbo.OMHRS_RecInfo
            set IsSubmited = 1, 
                IsCorrected = 2
            where AbstractID = @AbstractID and IsDeleted = 2
    end

return 0


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE   procedure [SU_OMHRS_CIHIError_Results]
    @ImportDateTime datetime
as
select 
    [ ] = AbstractID,
    [Facility] = FacilityNumber, 
    [Year] = FiscalYear, 
    [Quarter] = FiscalPeriod, 
    [Record ID(X1)] = [RecordID],
    [Record Type] = recordtype, 
    [Chart #] = ChartNumber,
    [Case Record Number(AA3)] = [CaseRecordNumber], 
    [Assessment Ref Date] = [AssessmentDate], 
    [Element Code] = [ElementCode], 
    [Orig Data] = [SubmittedValue], 
    [Error #] = [RuleNumber], 
    [Error Type] = [RuleType], 
    [Error Msg] = ErrorMessage 
from [OMHRS_CIHIErrors] 
where ImportDateTime = @ImportDateTime
order by [RecordID], [RuleType], [RuleNumber]





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [SU_OMHRS_ControlRecord]
    @ExecutionID int,
    @RecordCount int,
    @ControlRecord varchar(100) output
as

set @ControlRecord = 't fffffyyyyqccccccdddddddd'

declare 
    @tt       char(1), -- Data record type 
    @dddddddd char(8), -- Date of submission 
    @pp       char(2), -- Province/territory code 
    @fffff    char(5), -- Facility number 
    @yyyy     char(4), -- Fiscal year for this submission 
    @q        char(1), -- Fiscal quarter for this submission 
    @cccccc   char(6)  -- Number of data records in transmission

set @tt = '1'

set @cccccc   = replace(str(@RecordCount, 6), ' ', '0')

select 
  @dddddddd = convert( varchar(8), ExecutionDate, 112 )
, @fffff    = InstNoCIHI
, @yyyy     = convert( char(4), BatchYear)
, @q        = str(BatchPeriod, 1)
from SU_ExecProperties 
where ExecutionID = @ExecutionID

Update SU_ExecProperties 
set RecordCount = @RecordCount
where ExecutionID = @ExecutionID

set @ControlRecord = 
    replace(
    replace(
    replace(
    replace(
    replace(
    replace(
    replace(
        @ControlRecord 
    , 't'      , isnull( @tt      , 't'       ) )
    , 'dddddddd', isnull( @dddddddd, 'dddddddd' ) )
    , 'pp'      , isnull( @pp      , 'pp'       ) )
    , 'fffff'   , isnull( @fffff   , 'fffff'    ) )
    , 'yyyy'    , isnull( @yyyy    , 'yyyy'     ) )
    , 'q'       , isnull( @q       , 'q'        ) )
    , 'cccccc'  , isnull( @cccccc  , 'cccccc'   ) )

return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE procedure [SU_OMHRS_GetDeletionCount]
    @date_fr     datetime,
    @date_to     datetime,
    @InstCode    int,
    @DeletionCount int output
as
--PR-00907
    set @DeletionCount = isnull((select  count(*)
    from dbo.OMHRS_SecAA AA
        inner join dbo.OMHRS_SecA A on AA.AbstractID = A.AbstractID
        inner join dbo.OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
        inner join lu_codefile LU on AA.Z1 = LU.Code
        left  join OMHRS_SecS s on aa.AbstractID = s.AbstractID
    where InstitutionNumber = @InstCode
--Ticket PR-00263 to use admitdate to replace Assessment date for full admit assessment.
        and ((Lu.CIHIValue <> '3' and A.A1 between @date_fr and @date_to)
             or (Lu.CIHIValue = '3' and AA.AdmitDate between @date_fr and @date_to))
        and (R.IsSubmited = 1 and isnull(R.IsCorrected, 1) = 2 and IsDeleted in (1, 3))), 0)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [SU_OMHRS_Initialize]
    @SU_Type     int,
    @date_fr     datetime,
    @date_to     datetime,
    @InstCode    int,
    @FiscalYr    int,
    @FiscalQt    int,
    @RecCount    int output,
    @RecWidth    int output,
    @ExecutionID int output,
    @NameOfFile  varchar(50) output,
    @CoderNumber int = 999999
as

declare @AppID    int
declare @GroupID  int
declare @DateSent datetime
declare @SU_Const varchar(20)
declare @Sql      varchar(1000)

declare @SubFiscalYear int  --ED - 01901
declare @RehabSubDate datetime --ED - 01901
declare @InstCIHI varchar(20) --ED - 01901

-- 	30	OMH_ASSESS_FULL
-- 	31	OMH_ASSESS_SHORT
-- 	32	OMH_ASSESS_QURT
-- 	33	OMH_ASSESS_CHG
-- 	34	OMH_ASSESS_DSCH
-- 	35	OMH_ASSESS_MED
-- 	36	OMH_ASSESS_DEL
--  37  OMH_ASSESS_MAST

select @SU_Const = su_const from SU_StructureType where su_id = @SU_Type

--ED - 01901
select top 1 @InstCIHI = CIHIValue , @RehabSubDate = RehabSubDate
from H_InstitutionProfile 
where Code = @InstCode

set @DateSent = GetDate()
if @RehabSubDate is null
    set @SubFiscalYear = @FiscalYr
else 
begin
    set @SubFiscalYear = datepart(year, @DateSent) - (case when datepart(month, @DateSent) in (1, 2, 3) then 1 else 0 end)
    if @RehabSubDate >= @DateSent 
    begin
        if @FiscalYr < @SubFiscalYear and @DateSent >= cast(cast(datepart(year, @RehabSubDate) as varchar(10)) + '/04/01' as datetime)
            set @SubFiscalYear = @SubFiscalYear - 1
        else if @FiscalYr > @SubFiscalYear
            set @SubFiscalYear = @FiscalYr
    end    
    else if @RehabSubDate < @DateSent 
    begin
        set @SubFiscalYear = datepart(year, @RehabSubDate) - (case when datepart(month, @RehabSubDate) in (1, 2, 3) then 1 else 0 end)
        if @FiscalYr > @SubFiscalYear
            set @SubFiscalYear = @FiscalYr

    end    
end
--End ED - 01901

set @AppID = 
    case @SU_Type
        when 30 then 650
        when 31 then 651
        when 32 then 652
        when 33 then 653
        when 34 then 654
        when 35 then 650
        when 36 then 650
        when 37 then 650
    end

--ED - 01901
--set @GroupID = dbo.SUF_GET_GroupID( @SU_type, @AppID, @FiscalYr, 0 )
set @GroupID = dbo.SUF_GET_GroupID( @SU_type, @AppID, @SubFiscalYear, 0, 0 )

print 'GroupID = ' + str(@GroupID)

declare @Records table ( AbstractID int, OrderBy int identity(1,1) )

insert SU_ExecProperties 
       ( ExecutionDate, GroupID,  AppID,  CoderNumber,  DateStart, DateEnd,  InstNoCode, BatchYear, BatchPeriod, ICDType, SubFiscalYear ) 
values ( @DateSent,     @GroupID, @AppID, @CoderNumber, @date_fr,  @date_to, @InstCode,  @FiscalYr, @FiscalQt, 'T', @SubFiscalYear ) 

set @ExecutionID = @@identity

------------------------------------------------------------------------------------
-- GET A LIST OF ABSTRACTID'S THAT WILL BE USED TO CREAT THE SUBMISSION FILE
--
-- NOTE: Send AppID = -1 for master list of record keys
-- 
-- insert @Records ( AbstractID ) 
-- select AbstractID 
-- from dbo.SU_SELECT_CCRS( @SU_Const, @InstCode, @date_fr, @date_to )
-- where IsSubmited != 1
-- and IsDeleted = 2
-- order by patient_id, event_date, assessment 
if @SubFiscalYear < 2009
begin
    -- Master
    if @SU_Const in ('OMH_ASSESS_MAST')
    begin
        --Deletion first
        insert @Records ( AbstractID ) 
        select AA.AbstractID
        from dbo.OMHRS_SecAA AA
            inner join dbo.OMHRS_SecA A on AA.AbstractID = A.AbstractID
            inner join dbo.OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
            inner join lu_codefile LU on AA.Z1 = LU.Code
            left  join OMHRS_SecS s on aa.AbstractID = s.AbstractID
        where InstitutionNumber = @InstCode
    --Ticket PR-00263 to use admitdate to replace Assessment date for full admit assessment.
    --New E-mail from Judy about the change. PR - 00928
            and ((Lu.CIHIValue not in ('3', '5', '7') and A.A1 between @date_fr and @date_to)
                 or (Lu.CIHIValue in ('3', '7') and AA.AdmitDate between @date_fr and @date_to and A.A1 < '2009/04/01')
                 or (Lu.CIHIValue = '5' and s.X80 between @date_fr and @date_to and A.A1 < '2009/04/01'))
            and (R.IsSubmited = 1 and isnull(R.IsCorrected, 1) = 2 and IsDeleted in (1, 3))
        order by AA.ChartNumber, AA.AdmitDate, 
            (case when Lu.CIHIValue = '3' then AA.AdmitDate when Lu.CIHIValue = '5' then s.X80 else A.A1 end) desc, 
            LU.CIHIValue Desc
        --Correction second
        insert @Records ( AbstractID ) 
        select AA.AbstractID
        from dbo.OMHRS_SecAA AA
            inner join dbo.OMHRS_SecA A on AA.AbstractID = A.AbstractID
            inner join dbo.OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
            inner join lu_codefile LU on AA.Z1 = LU.Code
            left  join OMHRS_SecS s on aa.AbstractID = s.AbstractID
        where InstitutionNumber = @InstCode
    --New E-mail from Judy about the change. PR - 00928
            and ((Lu.CIHIValue not in ('3', '5', '7') and A.A1 between @date_fr and @date_to)
                 or (Lu.CIHIValue in ('3', '7') and AA.AdmitDate between @date_fr and @date_to and A.A1 < '2009/04/01')
                 or (Lu.CIHIValue = '5' and s.X80 between @date_fr and @date_to and A.A1 < '2009/04/01'))
            and (R.IsSubmited = 1 and ((R.IsValidated in (3, 4) and isnull(R.IsCorrected, 1) = 2) or @CoderNumber <= 2) and IsDeleted = 2)
        order by AA.ChartNumber, AA.AdmitDate, 
            (case when Lu.CIHIValue = '3' then AA.AdmitDate when Lu.CIHIValue = '5' then s.X80 else A.A1 end), 
            LU.CIHIValue  
        --New third
        insert @Records ( AbstractID ) 
        select AA.AbstractID
        from dbo.OMHRS_SecAA AA
            inner join dbo.OMHRS_SecA A on AA.AbstractID = A.AbstractID
            inner join dbo.OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
            inner join lu_codefile LU on AA.Z1 = LU.Code
            left  join OMHRS_SecS s on aa.AbstractID = s.AbstractID
        where InstitutionNumber = @InstCode
    --New E-mail from Judy about the change.
            and ((Lu.CIHIValue not in ('3', '5', '7') and A.A1 between @date_fr and @date_to)
                 or (Lu.CIHIValue in ('3', '7') and AA.AdmitDate between @date_fr and @date_to and A.A1 < '2009/04/01')
                 or (Lu.CIHIValue = '5' and s.X80 between @date_fr and @date_to and A.A1 < '2009/04/01'))
            and (R.IsSubmited = 2 and R.IsValidated in (3, 4) and IsDeleted = 2)
        order by AA.ChartNumber, AA.AdmitDate, 
            (case when Lu.CIHIValue = '3' then AA.AdmitDate when Lu.CIHIValue = '5' then s.X80 else A.A1 end), LU.CIHIValue  
    end
    -- Full Assessment
    if @SU_Const in ('OMH_ASSESS_FULL')
        insert @Records ( AbstractID ) 
        select AA.AbstractID
        from dbo.OMHRS_SecAA AA
            inner join dbo.OMHRS_SecA A on AA.AbstractID = A.AbstractID
            inner join dbo.OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
            inner join lu_codefile LU on AA.Z1 = LU.Code
        where InstitutionNumber = @InstCode
    --Ticket PR-00263 to use admitdate to replace Assessment date for full admit assessment.
    --        and A.A1 between @date_fr and @date_to
            and AA.AdmitDate between @date_fr and @date_to and A.A1 < '2009/04/01'
            and ((R.IsSubmited = 2 and R.IsValidated in (3, 4) and IsDeleted = 2)
                or (R.IsSubmited = 1 and ((R.IsValidated in (3, 4) and isnull(R.IsCorrected, 1) = 2) or @CoderNumber <= 2) and IsDeleted = 2))
            and LU.CIHIValue = '3'
        order by AA.ChartNumber, AA.AdmitDate, A.A1, LU.CIHIValue  

    -- Short Assessment
    if @SU_Const in ('OMH_ASSESS_SHORT')
        insert @Records ( AbstractID ) 
        select AA.AbstractID
        from dbo.OMHRS_SecAA AA
            inner join dbo.OMHRS_SecA A on AA.AbstractID = A.AbstractID
            inner join dbo.OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
            inner join lu_codefile LU on AA.Z1 = LU.Code
        where InstitutionNumber = @InstCode
    --E-mail From Judy PR - 00928
    --        and A.A1 between @date_fr and @date_to 
            and AA.AdmitDate between @date_fr and @date_to and A.A1 < '2009/04/01'
            and ((R.IsSubmited = 2 and R.IsValidated in (3, 4) and IsDeleted = 2)
                or (R.IsSubmited = 1 and ((R.IsValidated in (3, 4) and isnull(R.IsCorrected, 1) = 2) or @CoderNumber <= 2) and IsDeleted = 2))
            and LU.CIHIValue = '7'
        order by AA.ChartNumber, AA.AdmitDate, A.A1, LU.CIHIValue  

    -- Quarter Assessment
    if @SU_Const in ('OMH_ASSESS_QURT')
        insert @Records ( AbstractID ) 
        select AA.AbstractID
        from dbo.OMHRS_SecAA AA
            inner join dbo.OMHRS_SecA A on AA.AbstractID = A.AbstractID
            inner join dbo.OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
            inner join lu_codefile LU on AA.Z1 = LU.Code
        where InstitutionNumber = @InstCode
            and A.A1 between @date_fr and @date_to
            and ((R.IsSubmited = 2 and R.IsValidated in (3, 4) and IsDeleted = 2)
                or (R.IsSubmited = 1 and ((R.IsValidated in (3, 4) and isnull(R.IsCorrected, 1) = 2) or @CoderNumber <= 2) and IsDeleted = 2))
            and LU.CIHIValue = '4'
        order by AA.ChartNumber, AA.AdmitDate, A.A1 desc, LU.CIHIValue  

    -- Change Assessment
    if @SU_Const in ('OMH_ASSESS_CHG')
        insert @Records ( AbstractID ) 
        select AA.AbstractID
        from dbo.OMHRS_SecAA AA
            inner join dbo.OMHRS_SecA A on AA.AbstractID = A.AbstractID
            inner join dbo.OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
            inner join lu_codefile LU on AA.Z1 = LU.Code
        where InstitutionNumber = @InstCode
            and A.A1 between @date_fr and @date_to
            and ((R.IsSubmited = 2 and R.IsValidated in (3, 4) and IsDeleted = 2)
                or (R.IsSubmited = 1 and ((R.IsValidated in (3, 4) and isnull(R.IsCorrected, 1) = 2) or @CoderNumber <= 2) and IsDeleted = 2))
            and LU.CIHIValue = '6'
        order by AA.ChartNumber, AA.AdmitDate, A.A1, LU.CIHIValue  

    -- Discharge Assessment
    if @SU_Const in ('OMH_ASSESS_DSCH')
        insert @Records ( AbstractID ) 
        select AA.AbstractID
        from dbo.OMHRS_SecAA AA
            inner join dbo.OMHRS_SecA A on AA.AbstractID = A.AbstractID
            inner join dbo.OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
            inner join lu_codefile LU on AA.Z1 = LU.Code
            left  join OMHRS_SecS s on aa.AbstractID = s.AbstractID
        where InstitutionNumber = @InstCode
    --Emial from Judy PR - 00928
    --        and A.A1 between @date_fr and @date_to
            and s.X80 between @date_fr and @date_to and A.A1 < '2009/04/01'
            and ((R.IsSubmited = 2 and R.IsValidated in (3, 4) and IsDeleted = 2)
                or (R.IsSubmited = 1 and ((R.IsValidated in (3, 4) and isnull(R.IsCorrected, 1) = 2) or @CoderNumber <= 2) and IsDeleted = 2))
            and LU.CIHIValue = '5'
        order by AA.ChartNumber, AA.AdmitDate, A.A1, LU.CIHIValue  

    -- Medicine Assessment
    if @SU_Const in ('OMH_ASSESS_MED')
        insert @Records ( AbstractID ) 
        select Distinct AA.AbstractID
        from dbo.OMHRS_SecAA AA
            inner join dbo.OMHRS_SecA A on AA.AbstractID = A.AbstractID
            inner join dbo.OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
            inner join lu_codefile LU on AA.Z1 = LU.Code
            inner join OMHRS_Medication M on AA.AbstractID = M.AbstractID
            left  join OMHRS_SecS s on aa.AbstractID = s.AbstractID
        where InstitutionNumber = @InstCode
    --        and A.A1 between @date_fr and @date_to
    --Ticket PR-00263 to use admitdate to replace Assessment date for full admit assessment.
    --New E-mail from Judy about the change. PR - 00928
            and ((Lu.CIHIValue not in ('3', '5', '7') and A.A1 between @date_fr and @date_to)
                 or (Lu.CIHIValue in ('3', '7') and AA.AdmitDate between @date_fr and @date_to)
                 or (Lu.CIHIValue = '5' and s.X80 between @date_fr and @date_to))
            and ((R.IsSubmited = 2 and R.IsValidated in (3, 4) and IsDeleted = 2)
                or (R.IsSubmited = 1 and ((R.IsValidated in (3, 4) and isnull(R.IsCorrected, 1) = 2) or @CoderNumber <= 2) and IsDeleted = 2))
    --    order by AA.ChartNumber, AA.AdmitDate, A.A1, LU.CIHIValue  

    -- Deletion Assessment
    if @SU_Const in ('OMH_ASSESS_DEL')
        insert @Records ( AbstractID ) 
        select AA.AbstractID
        from dbo.OMHRS_SecAA AA
            inner join dbo.OMHRS_SecA A on AA.AbstractID = A.AbstractID
            inner join dbo.OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
            inner join lu_codefile LU on AA.Z1 = LU.Code
            left  join OMHRS_SecS s on aa.AbstractID = s.AbstractID
        where InstitutionNumber = @InstCode
    --        and A.A1 between @date_fr and @date_to
    --Ticket PR-00263 to use admitdate to replace Assessment date for full admit assessment.
    --New E-mail from Judy about the change. PR - 00928
            and ((Lu.CIHIValue not in ('3', '5', '7') and A.A1 between @date_fr and @date_to)
                 or (Lu.CIHIValue in ('3', '7') and AA.AdmitDate between @date_fr and @date_to and A.A1 < '2009/04/01')
                 or (Lu.CIHIValue = '5' and s.X80 between @date_fr and @date_to and A.A1 < '2009/04/01'))
            and (R.IsSubmited = 1 and isnull(R.IsCorrected, 1) = 2 and IsDeleted in (1, 3))
        order by AA.ChartNumber, AA.AdmitDate, A.A1, LU.CIHIValue Desc
end
else
begin   --2009 OMHRS use A1 to be the reference date
    -- Master
    if @SU_Const in ('OMH_ASSESS_MAST')
    begin
        --Deletion first
        insert @Records ( AbstractID ) 
        select AA.AbstractID
        from dbo.OMHRS_SecAA AA
            inner join dbo.OMHRS_SecA A on AA.AbstractID = A.AbstractID
            inner join dbo.OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
            inner join lu_codefile LU on AA.Z1 = LU.Code
            left  join OMHRS_SecS s on aa.AbstractID = s.AbstractID
        where InstitutionNumber = @InstCode
            and A.A1 between @date_fr and @date_to
            and (R.IsSubmited = 1 and isnull(R.IsCorrected, 1) = 2 and IsDeleted in (1, 3))
        order by AA.ChartNumber, AA.AdmitDate, 
            (case when Lu.CIHIValue = '3' then AA.AdmitDate when Lu.CIHIValue = '5' then s.X80 else A.A1 end) desc, 
            LU.CIHIValue Desc
        --Correction second
        insert @Records ( AbstractID ) 
        select AA.AbstractID
        from dbo.OMHRS_SecAA AA
            inner join dbo.OMHRS_SecA A on AA.AbstractID = A.AbstractID
            inner join dbo.OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
            inner join lu_codefile LU on AA.Z1 = LU.Code
            left  join OMHRS_SecS s on aa.AbstractID = s.AbstractID
        where InstitutionNumber = @InstCode
            and A.A1 between @date_fr and @date_to
            and (R.IsSubmited = 1 and ((R.IsValidated in (3, 4) and isnull(R.IsCorrected, 1) = 2) or @CoderNumber <= 2) and IsDeleted = 2)
        order by AA.ChartNumber, AA.AdmitDate, 
            (case when Lu.CIHIValue = '3' then AA.AdmitDate when Lu.CIHIValue = '5' then s.X80 else A.A1 end), 
            LU.CIHIValue  
        --New third
        insert @Records ( AbstractID ) 
        select AA.AbstractID
        from dbo.OMHRS_SecAA AA
            inner join dbo.OMHRS_SecA A on AA.AbstractID = A.AbstractID
            inner join dbo.OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
            inner join lu_codefile LU on AA.Z1 = LU.Code
            left  join OMHRS_SecS s on aa.AbstractID = s.AbstractID
        where InstitutionNumber = @InstCode
            and A.A1 between @date_fr and @date_to
            and (R.IsSubmited = 2 and R.IsValidated in (3, 4) and IsDeleted = 2)
        order by AA.ChartNumber, AA.AdmitDate, 
            (case when Lu.CIHIValue = '3' then AA.AdmitDate when Lu.CIHIValue = '5' then s.X80 else A.A1 end), LU.CIHIValue  
    end
    -- Full Assessment
    if @SU_Const in ('OMH_ASSESS_FULL')
        insert @Records ( AbstractID ) 
        select AA.AbstractID
        from dbo.OMHRS_SecAA AA
            inner join dbo.OMHRS_SecA A on AA.AbstractID = A.AbstractID
            inner join dbo.OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
            inner join lu_codefile LU on AA.Z1 = LU.Code
        where InstitutionNumber = @InstCode
            and A.A1 between @date_fr and @date_to
            and ((R.IsSubmited = 2 and R.IsValidated in (3, 4) and IsDeleted = 2)
                or (R.IsSubmited = 1 and ((R.IsValidated in (3, 4) and isnull(R.IsCorrected, 1) = 2) or @CoderNumber <= 2) and IsDeleted = 2))
            and LU.CIHIValue = '3'
        order by AA.ChartNumber, AA.AdmitDate, A.A1, LU.CIHIValue  

    -- Short Assessment
    if @SU_Const in ('OMH_ASSESS_SHORT')
        insert @Records ( AbstractID ) 
        select AA.AbstractID
        from dbo.OMHRS_SecAA AA
            inner join dbo.OMHRS_SecA A on AA.AbstractID = A.AbstractID
            inner join dbo.OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
            inner join lu_codefile LU on AA.Z1 = LU.Code
        where InstitutionNumber = @InstCode
            and A.A1 between @date_fr and @date_to 
            and ((R.IsSubmited = 2 and R.IsValidated in (3, 4) and IsDeleted = 2)
                or (R.IsSubmited = 1 and ((R.IsValidated in (3, 4) and isnull(R.IsCorrected, 1) = 2) or @CoderNumber <= 2) and IsDeleted = 2))
            and LU.CIHIValue = '7'
        order by AA.ChartNumber, AA.AdmitDate, A.A1, LU.CIHIValue  

    -- Quarter Assessment
    if @SU_Const in ('OMH_ASSESS_QURT')
        insert @Records ( AbstractID ) 
        select AA.AbstractID
        from dbo.OMHRS_SecAA AA
            inner join dbo.OMHRS_SecA A on AA.AbstractID = A.AbstractID
            inner join dbo.OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
            inner join lu_codefile LU on AA.Z1 = LU.Code
        where InstitutionNumber = @InstCode
            and A.A1 between @date_fr and @date_to
            and ((R.IsSubmited = 2 and R.IsValidated in (3, 4) and IsDeleted = 2)
                or (R.IsSubmited = 1 and ((R.IsValidated in (3, 4) and isnull(R.IsCorrected, 1) = 2) or @CoderNumber <= 2) and IsDeleted = 2))
            and LU.CIHIValue = '4'
        order by AA.ChartNumber, AA.AdmitDate, A.A1 desc, LU.CIHIValue  

    -- Change Assessment
    if @SU_Const in ('OMH_ASSESS_CHG')
        insert @Records ( AbstractID ) 
        select AA.AbstractID
        from dbo.OMHRS_SecAA AA
            inner join dbo.OMHRS_SecA A on AA.AbstractID = A.AbstractID
            inner join dbo.OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
            inner join lu_codefile LU on AA.Z1 = LU.Code
        where InstitutionNumber = @InstCode
            and A.A1 between @date_fr and @date_to
            and ((R.IsSubmited = 2 and R.IsValidated in (3, 4) and IsDeleted = 2)
                or (R.IsSubmited = 1 and ((R.IsValidated in (3, 4) and isnull(R.IsCorrected, 1) = 2) or @CoderNumber <= 2) and IsDeleted = 2))
            and LU.CIHIValue = '6'
        order by AA.ChartNumber, AA.AdmitDate, A.A1, LU.CIHIValue  

    -- Discharge Assessment
    if @SU_Const in ('OMH_ASSESS_DSCH')
        insert @Records ( AbstractID ) 
        select AA.AbstractID
        from dbo.OMHRS_SecAA AA
            inner join dbo.OMHRS_SecA A on AA.AbstractID = A.AbstractID
            inner join dbo.OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
            inner join lu_codefile LU on AA.Z1 = LU.Code
            left  join OMHRS_SecS s on aa.AbstractID = s.AbstractID
        where InstitutionNumber = @InstCode
            and A.A1 between @date_fr and @date_to
            and ((R.IsSubmited = 2 and R.IsValidated in (3, 4) and IsDeleted = 2)
                or (R.IsSubmited = 1 and ((R.IsValidated in (3, 4) and isnull(R.IsCorrected, 1) = 2) or @CoderNumber <= 2) and IsDeleted = 2))
            and LU.CIHIValue = '5'
        order by AA.ChartNumber, AA.AdmitDate, A.A1, LU.CIHIValue  

    -- Medicine Assessment
    if @SU_Const in ('OMH_ASSESS_MED')
        insert @Records ( AbstractID ) 
        select Distinct AA.AbstractID
        from dbo.OMHRS_SecAA AA
            inner join dbo.OMHRS_SecA A on AA.AbstractID = A.AbstractID
            inner join dbo.OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
            inner join lu_codefile LU on AA.Z1 = LU.Code
            inner join OMHRS_Medication M on AA.AbstractID = M.AbstractID
            left  join OMHRS_SecS s on aa.AbstractID = s.AbstractID
        where InstitutionNumber = @InstCode
            and A.A1 between @date_fr and @date_to
            and ((R.IsSubmited = 2 and R.IsValidated in (3, 4) and IsDeleted = 2)
                or (R.IsSubmited = 1 and ((R.IsValidated in (3, 4) and isnull(R.IsCorrected, 1) = 2) or @CoderNumber <= 2) and IsDeleted = 2))
    --    order by AA.ChartNumber, AA.AdmitDate, A.A1, LU.CIHIValue  

    -- Deletion Assessment
    if @SU_Const in ('OMH_ASSESS_DEL')
        insert @Records ( AbstractID ) 
        select AA.AbstractID
        from dbo.OMHRS_SecAA AA
            inner join dbo.OMHRS_SecA A on AA.AbstractID = A.AbstractID
            inner join dbo.OMHRS_RecInfo R on AA.AbstractID = R.AbstractID
            inner join lu_codefile LU on AA.Z1 = LU.Code
            left  join OMHRS_SecS s on aa.AbstractID = s.AbstractID
        where InstitutionNumber = @InstCode
            and A.A1 between @date_fr and @date_to
            and (R.IsSubmited = 1 and isnull(R.IsCorrected, 1) = 2 and IsDeleted in (1, 3))
        order by AA.ChartNumber, AA.AdmitDate, A.A1, LU.CIHIValue Desc
end

insert SU_RecordSelect ( 
    ExecutionID  , 
    AbstractID   ,     OrderBy      , 
    IsSubmited   , 
    IsCorrected  , 
    IsValidated  , 
    IsCompleted  , 
    IsDeleted    , 
    CIHIDateSent , 
    BatchYear    ,
    BatchPeriod  )
select 
    @ExecutionID  , 
    r.AbstractID  , 
    r.OrderBy, --min(r.OrderBy),
	1             ,
    (case when isnull(a.IsCorrected, 1) = 1 then 1 else 3 end),
	a.IsValidated ,
	4 ,
	a.IsDeleted   ,
	@DateSent     ,
	@FiscalYr     ,
    BatchPeriod = (case @FiscalQt when 1 then 15401
                                  when 2 then 15402
                                  when 3 then 15403
                                  when 4 then 15404
                                  else @FiscalQt
                   end)
from @Records r 
join dbo.OMHRS_RecInfo a on r.AbstractID = a.AbstractID 
--group by r.AbstractID, a.IsCorrected, a.IsValidated, a.IsDeleted
order by r.OrderBy  --min(r.OrderBy)

if @SU_Const in ('OMH_ASSESS_MAST')
begin
    insert SU_Record_Submited_OMH_Order(ExecutionID, AbstractID, OrderBy)
    select ExecutionID, AbstractID, OrderBy from SU_RecordSelect
    where ExecutionID = @ExecutionID
end


-- set the total number of records: 
set @RecCount = (select count(*) from @Records) -- @@rowcount

delete from @Records

DBCC DBREINDEX (SU_RecordSelect)

select @RecWidth = sum(TextLength) 
from SU_StructureFile 
where GroupID = @GroupID


set @NameOfFile = dbo.SU_FILENAME_OMHRS( @ExecutionID, @SU_Const )

-----------------------------------------------------------------------------------
-- UPDATE THE EXECUTION PROPERTIES TABLE WITH THE VARIOUS VALUES
update SU_ExecProperties
set RecordCount = @RecCount,
    RecordWidth = @RecWidth,
    NameOfFile  = @NameOfFile,
    InstNoCIHI  = @InstCIHI --(select CIHIValue from H_InstitutionProfile where Code = @InstCode)
where ExecutionID = @ExecutionID

EXIT_PROCEDURE_NORMAL:
    return 0
ERROR___INVALID_SUBMISSION_NUMBER:
    return 1

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create procedure [SU_OMHRS_MED_Correct]
    @ExecutionID int,
	@AbstractID [int]  
as    
    select SubmitedRecord  
    from SU_Record_Submited_OMH_MED S
    where S.AbstractID = @AbstractID and S.IsDeleted <> 1 and
        S.ExecutionID = @ExecutionID



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE  procedure [SU_OMHRS_MED_Delete]
	@AbstractID [int]  ,
	@IsDeleted [int]       
as    
    select '8 ' + substring(S.SubmitedRecord, 3, 10) + 'D' +
        substring(S.SubmitedRecord, 14, 32)  
    from SU_Record_Submited_OMH_MED S
        left join OMHRS_Medication M 
        on S.X1 = M.X1 and S.AbstractID = M.AbstractID
    where S.AbstractID = @AbstractID and S.IsDeleted <> 1 and
        (@IsDeleted = 1 or (  @IsDeleted = 0 and M.X1 is null))





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create Procedure [SU_OMHRS_MergeRecord]
	@ExecutionID  int
as    

    declare @AbstractID  int
    declare @X1          int
    declare @IsCorrected int
    declare @IsDeleted   int
    declare @RecordType  varchar(2)
    declare @Sub_Type    varchar(1)
    declare @CIHIDateSent datetime

    select S.AbstractID, S.IsCorrected, S.IsDeleted, S.SubmitedRecord
    from SU_Record_Submited S 
        inner join SU_Record_Submited_OMH_Order R 
        on S.AbstractID = R.AbstractID and S.ExecutionID = R.ExecutionID
    where S.ExecutionID = @ExecutionID
    order by R.OrderBy



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE Procedure [SU_OMHRS_SaveMED_Deletion]
	@ExecutionID  int
as    
    update SU_Record_Submited_OMH_MED
    set IsCorrected = 3,
        IsDeleted   = 1,
	    CIHIDateSent = (select top 1 ExecutionDate from dbo.SU_ExecProperties where ExecutionID = @ExecutionID),
        ExecutionID = @ExecutionID
    from SU_Record_Submited_OMH_MED S
        inner join dbo.SU_Record_Submited R 
            on R.AbstractID = S.AbstractID
        left join OMHRS_Medication M 
        on S.X1 = M.X1 and S.AbstractID = M.AbstractID
    where R.ExecutionID = @ExecutionID and
        (R.IsDeleted = 1 or M.X1 is null) 


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [SU_OMHRS_SaveRecord]
	@ExecutionID  int, 
    @SubData      varchar(4000)
as    

    declare @AbstractID  int
    declare @X1          int
    declare @IsCorrected int
    declare @IsDeleted   int
    declare @RecordType  varchar(2)
    declare @Sub_Type    varchar(1)
    declare @CIHIDateSent datetime

    set @AbstractID = left(@SubData, 10)
    set @RecordType = ltrim(rtrim(substring(@SubData, 11, 2)))
    set @X1 = cast(ltrim(rtrim(substring(@SubData, 13, 10))) as int)
    set @Sub_Type = ltrim(rtrim(substring(@SubData, 23, 1)))

    if @Sub_Type = 'N'
    begin
        set @IsCorrected = 0
        set @IsDeleted = 0
    end
    else if @Sub_Type = 'C'
    begin
        set @IsCorrected = 1
        set @IsDeleted = 0
    end
    else
    begin
        set @IsCorrected = 1
        set @IsDeleted = 1
    end

    set @CIHIDateSent = (select ExecutionDate from SU_ExecProperties where ExecutionID = @ExecutionID)

    if @RecordType = '8 '    --'08'  --PR - 02985
    begin
        if exists (select * from SU_Record_Submited_OMH_MED where 
            abstractID = @AbstractID and X1 = @X1)
            update SU_Record_Submited_OMH_MED
            set IsCorrected = 1,
        	    CIHIDateSent = @CIHIDateSent,
                SubmitedRecord = substring(@SubData, 11, 4000),
                ExecutionID = @ExecutionID
            where AbstractID = @AbstractID and X1 = @X1
        else
        begin
            set @SubData = (case when @Sub_Type = 'N' then substring(@SubData, 11, 4000)
                                 else substring(@SubData, 11, 12) + 'N' + substring(@SubData, 24, 4000)
                                 end)
            insert into SU_Record_Submited_OMH_MED(ExecutionID, AbstractID,
    	        X1, IsCorrected, IsDeleted, CIHIDateSent, SubmitedRecord)
            values(@ExecutionID, @AbstractID,
    	        @X1, @IsCorrected, @IsDeleted, @CIHIDateSent, @SubData)
        end
    end
    else
        insert SU_Record_Submited (ExecutionID, AbstractID, X1, IsCorrected, 
            IsDeleted, CIHIDateSent, SubmitedRecord) 
        values(@ExecutionID, @AbstractID, @X1, @IsCorrected, @IsDeleted, 
            @CIHIDateSent, substring(@SubData, 11, 4000)) 

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE procedure [SU_Prep_AmCare9cm_Alberta]
    @ExecutionID  int
as


    -- Resequence Providers based on Doctors/Providers
    -- Occurrence 1 to 5  will be Doctors
    -- Occurrence 6 to 10 will be Provider Specialties

    declare @SQL as varchar(800)
    declare @tbl varchar(50)

    declare @IsCorrection int

    select 
        @IsCorrection = IsCorrection 
    from SU_ExecProperties 
    where ExecutionID = @ExecutionID

   

    if ((select object_id('tempdb..#SU_ReSequence')) is not null) drop table #SU_ReSequence
    create table #SU_ReSequence (
        AbstractID         int null,
        ProviderOccurrence int null,
        NewOccurrence      int null,
        IsDoctor           bit null,
        OrderBy            int identity(1,1)
    )


    set @tbl = dbo.SUF_GetTempTable ( @ExecutionID, 'AB_Provider' )

    -- select Doctors only
    set @SQL = 
        'select AbstractID, ProviderOccurrence, IsDoctor = 1 ' +
        'from ' + @tbl + ' ' +
        'where (ProviderNumber is not null and ProviderSpecialty is not null) or (ProviderType = 3112) ' +
        'order by AbstractID, ProviderOccurrence '

    insert into #SU_ReSequence ( AbstractID, ProviderOccurrence, IsDoctor ) exec ( @SQL )

    -- select Providers only
    set @SQL = 
        'select AbstractID, ProviderOccurrence, IsDoctor = 0 ' +
        'from ' + @tbl + ' ' +
        'where not ((ProviderNumber is not null and ProviderSpecialty is not null) or (ProviderType = 3112)) ' +
        'order by AbstractID, ProviderOccurrence '

    insert into #SU_ReSequence ( AbstractID, ProviderOccurrence, IsDoctor ) exec ( @SQL )


    -- resequence Doctors Occurrence numbers
    update #SU_ReSequence
    set NewOccurrence = ((r.OrderBy - minSeed.minOcc) + 1)
    from #SU_ReSequence r 
    join (
        select AbstractID, IsDoctor, minOcc = min(OrderBy) 
        from #SU_ReSequence
        group by AbstractID, IsDoctor
        having IsDoctor = 1
    ) minSeed on r.AbstractID = minSeed.AbstractID and r.IsDoctor = 1

    -- resequence Providers Occurrence numbers
    update #SU_ReSequence
    set NewOccurrence = ((r.OrderBy - minSeed.minOcc) + 5)
    from #SU_ReSequence r 
    join (
        select AbstractID, IsDoctor, minOcc = min(OrderBy) 
        from #SU_ReSequence
        group by AbstractID, IsDoctor
        having IsDoctor = 0
    ) minSeed on r.AbstractID = minSeed.AbstractID and r.IsDoctor = 0

    -- delete any unnecessary Doctors and/or Providers
    delete #SU_ReSequence where NewOccurrence > 5  and IsDoctor = 1
    delete #SU_ReSequence where NewOccurrence > 10 and IsDoctor = 0

    -- remove any Doctors/Provider that are no longer necessary

    set @SQL = 
        'delete ' + @tbl + ' ' + 
        'from ' + @tbl + ' s left join #SU_ReSequence r ' +
        'on s.AbstractID = r.AbstractID and s.ProviderOccurrence = r.ProviderOccurrence ' +
        'where r.ProviderOccurrence is null '
    exec( @SQL )

    -- update the old Ocurrence Number to the new one
    set @SQL = 
        'update ' + @tbl + ' ' + 
        'set ProviderOccurrence = r.NewOccurrence ' + 
        'from ' + @tbl + ' s join #SU_ReSequence r ' +
        'on s.AbstractID = r.AbstractID and s.ProviderOccurrence = r.ProviderOccurrence '
    exec( @SQL )

    if ((select object_id('tempdb..#SU_ReSequence')) is not null) drop table #SU_ReSequence


    delete SU_Defaults where GroupID = 9 and ExecutionID = @ExecutionID 

    declare @DefaultVal varchar(255)

    set @DefaultVal = case @IsCorrection 
        when 1 then 
            '(case AB_Abstract.CIHIReturnStatus ' + 
            'when 1 then ''A'' ' +  -- add rec for correction
            'when 2 then ''D'' ' +  -- delete rec for correction
            'when 3 then ''A'' ' +  -- add rec for correction
            'when 4 then ''C'' ' +  -- change rec for correction
            'end)'
        when 0 then
            'A'  -- add rec for regular submission
    end

    insert SU_Defaults (GroupID, SubGroupID, FieldName, DefaultVal)
    values ( 9, 0, 'SubmissionType', @DefaultVal )

    return 0




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [SU_Prep_AmcareDeletes]
    @ExecutionID  int
AS
    declare @SQL as varchar(800)
    declare @tbl varchar(50)

    declare @IsCorrection int

    select 
        @IsCorrection = IsCorrection
    from SU_ExecProperties
    where ExecutionID = @ExecutionID

-- IF THE RECORD IS FLAGGED AS DELETE THEN PROCESS IT SO THAT ONLY THE KEY FIELDS REMAIN.
    
    if (@IsCorrection = 1) begin
    
        if ((select object_id('tempdb..#ProcessDeletes')) is not null) drop table #ProcessDeletes
        create table #ProcessDeletes 
        (
            AbstractID        int null,
            CIHIReturnStatus  int null,
            ProvinceNumber    int null,
            InstitutionNumber int null,
            HealthCareNumber  varchar(12) null,
            ChartNumber       varchar(10) null,
            EncounterNumber   varchar(20) null,
            EncounterSequence int null
        )
    
        set @tbl = dbo.SUF_GetTempTable ( @ExecutionID, 'AB_Abstract' )
    
        set @SQL = 
            'select AbstractID, CIHIReturnStatus, ProvinceNumber, InstitutionNumber, HealthCareNumber, ChartNumber, EncounterNumber, EncounterSequence ' +
            'from ' + @tbl + ' where CIHIReturnStatus = 2 '

        insert #ProcessDeletes ( AbstractID, CIHIReturnStatus, ProvinceNumber, InstitutionNumber, HealthCareNumber, ChartNumber, EncounterNumber, EncounterSequence )
        exec ( @SQL )

        if (@@rowcount > 0) begin    

            declare cur cursor local fast_forward for 
                select distinct 
                    SQL = 
                        'delete ' + dbo.SUF_GetTempTable ( @ExecutionID, TableName ) + 
                        ' where AbstractID in (select AbstractID from #ProcessDeletes)'
                from SU_StructureFile where GroupID in (7, 8) and TableName is not null
            
            open cur 

            while (1=1) begin
                fetch next from cur into @SQL
                if (@@fetch_status <> 0) break
                exec( @SQL )
            end

            close cur
            deallocate cur

            set @SQL = 
                'insert ' + @tbl + ' ( AbstractID, CIHIReturnStatus, ProvinceNumber, InstitutionNumber, HealthCareNumber, ChartNumber, EncounterNumber, EncounterSequence ) ' +
                'select AbstractID, CIHIReturnStatus, ProvinceNumber, InstitutionNumber, HealthCareNumber, ChartNumber, EncounterNumber, EncounterSequence ' +
                'from #ProcessDeletes '
            exec( @SQL )
        end

        if ((select object_id('tempdb..#ProcessDeletes')) is not null) drop table #ProcessDeletes
        
    end

    return 0
----------------------------------------------------------------------------------------------




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [SU_Prep_AmcareECodes]
    @ExecutionID  int
AS
    declare @SQL varchar(800)
    declare @tbl varchar(50)

    declare @ICDType char(1)

    select 
        @ICDType = ICDType
    from SU_ExecProperties
    where ExecutionID = @ExecutionID

----------------------------------------------------------------------------------------------
    -- ReSequence the Diagnosis Occurrences based on non E codes and E Codes
    -- Occurrence 1 to 6  will be NON-E-Codes
    -- Occurrence 7 to 10 will be E-Codes
    if ((select object_id('tempdb..#SU_ReSequence')) is not null) drop table #SU_ReSequence
    create table #SU_ReSequence 
    (
        AbstractID int null,
        DiagnosisOccurrence int null,
        NewOccurrence int null,
        IsECode bit null,
        OrderBy int identity(1,1)
    )


    set @tbl = dbo.SUF_GetTempTable ( @ExecutionID, 'AB_Diagnosis' )

    set @SQL = 
        'select AbstractID, DiagnosisOccurrence, IsECode = (case left(d.CIHIValue, 1) when ''E'' then 1 else 0 end) ' +
        'from ' + @tbl + ' s ' +
        'join ' + 
            case  @ICDType 
                when '9' then 'ICD_DiagFile9'
                when 'C' then 'ICD_DiagFile9cm'
                when 'T' then 'ICD_DiagFile10'
            end + 
        ' d on s.DiagnosisCode = d.Code ' +
        'order by AbstractID, DiagnosisOccurrence '
        
    -- select Doctors only
    insert into #SU_ReSequence ( AbstractID, DiagnosisOccurrence, IsECode ) exec ( @SQL )


    update #SU_ReSequence
    set NewOccurrence = ((r.OrderBy - minSeed.minOcc) + 1)
    from #SU_ReSequence r 
    join (
        select AbstractID, IsECode, minOcc = min(OrderBy) 
        from #SU_ReSequence
        group by AbstractID, IsECode
        having IsECode = 0
    ) minSeed on r.AbstractID = minSeed.AbstractID and r.IsECode = 0

    update #SU_ReSequence
    set NewOccurrence = ((r.OrderBy - minSeed.minOcc) + 7)
    from #SU_ReSequence r 
    join (
        select AbstractID, IsECode, minOcc = min(OrderBy) 
        from #SU_ReSequence
        group by AbstractID, IsECode
        having IsECode = 1
    ) minSeed on r.AbstractID = minSeed.AbstractID and r.IsECode = 1

    delete #SU_ReSequence where NewOccurrence > 6  and IsECode = 0
    delete #SU_ReSequence where NewOccurrence > 10 and IsECode = 1


    set @SQL = 
        'delete ' + @tbl + ' ' + 
        'from ' + @tbl + ' s left join #SU_ReSequence r ' +
        'on s.AbstractID = r.AbstractID and s.DiagnosisOccurrence = r.DiagnosisOccurrence ' +
        'where r.DiagnosisOccurrence is null '
    exec( @SQL )
    
    set @SQL = 
        'update ' + @tbl + ' ' + 
        'set DiagnosisOccurrence = r.NewOccurrence ' + 
        'from ' + @tbl + ' s join #SU_ReSequence r ' +
        'on s.AbstractID = r.AbstractID and s.DiagnosisOccurrence = r.DiagnosisOccurrence '
    exec( @SQL )

    if ((select object_id('tempdb..#SU_ReSequence')) is not null) drop table #SU_ReSequence


    return 0
----------------------------------------------------------------------------------------------




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [SU_Prep_DAD_9andCM_DiagnosisTransfers]
    @ExecutionID int
AS 

    declare @sql           nvarchar(800)
    declare @table_name    nvarchar(50)

----------------------------------------------------------------------------------------------
    -- ReSequence the Diagnosis Occurrences based transfers

    set @table_name = dbo.SUF_GetTempTable ( @ExecutionID, 'AB_Diagnosis' )

    ---------------------------------------------------------------------------------
    -- THE-trasfer select -----------------------------------------------------------
    if ((select object_id('tempdb..#THE_Xfers')) is not null) drop table #THE_Xfers
    create table #THE_Xfers (AbstractID int, OldOcc int, NewOcc int null)
    
    print 'hard-code new occurrence values for transfers.'
    -- hard-code new occurrence values for transfers.
    set @sql = 
        'select AbstractID, DiagnosisOccurrence, ' +
            'NewOcc = case l.CIHIValue ' +
                    'when ''W'' then 14 ' +
                    'when ''X'' then 15 ' +
                    'when ''Y'' then 16 ' +
                    'else null ' +
                'end ' +
        'from ' + @table_name + ' d ' +
        'join LU_DiagnosisType l on d.DiagnosisType = l.Code ' +
        'where l.CIHIValue in (''W'', ''X'', ''Y'') ' 
    
    insert #THE_Xfers (AbstractID, OldOcc, NewOcc) exec ( @sql )



    ---------------------------------------------------------------------------------
    -- NON-trasfer select -----------------------------------------------------------
    if ((select object_id('tempdb..#NON_Xfers')) is not null) drop table #NON_Xfers
    create table #NON_Xfers (AbstractID int, OldOcc int, NewOcc int null, OccSeed int identity(1,1))

    set @sql = 
        'select AbstractID, DiagnosisOccurrence ' +
        'from ' + @table_name + ' d ' +
        'join LU_DiagnosisType l on d.DiagnosisType = l.Code ' +
        'where l.CIHIValue not in (''W'', ''X'', ''Y'') ' +
        'order by AbstractID, DiagnosisOccurrence '
    
    insert #NON_Xfers (AbstractID, OldOcc) exec ( @sql )

    print 'calculate and update new occurrence field for non-xfers'
    -- calculate and update new occurrence field for non-xfers
    update #NON_Xfers
    set NewOcc = OccSeed - minSeed.val + 1
    from #NON_Xfers 
    join (
        select AbstractID, val = min(OccSeed)
        from #NON_Xfers
        group by AbstractID
    ) minSeed on #NON_Xfers.AbstractID = minSeed.AbstractID
    

    print 'delete any non-transfers that overlap a transfer'
    -- delete any non-transfers that overlap a transfer
    delete #NON_Xfers
    from #NON_Xfers n join #THE_Xfers x 
      on n.AbstractID = x.AbstractID and n.NewOcc = x.NewOcc
        
    print 'remove the overlaps from the original table'
    -- remove the overlaps from the original table
    set @sql = 
        'delete ' + @table_name + ' ' +
        'from ' + @table_name + ' o ' +
        'left join ( ' +

            'select AbstractID, NewOcc, OldOcc from #THE_Xfers ' +
            'union all ' +
            'select AbstractID, NewOcc, OldOcc from #NON_Xfers ' +

        ') n on o.AbstractID = n.AbstractID and o.DiagnosisOccurrence = n.OldOcc  ' +
        'where n.AbstractID is null '
    exec( @sql )
    
    print 'update the occurrence number for all remaining records'
    -- update the occurrence number for all remaining records
    set @sql = 
        'update ' + @table_name + ' ' +
        'set DiagnosisOccurrence = n.NewOcc ' +
        'from ' + @table_name + ' o ' +
        'join ( ' +

            'select AbstractID, NewOcc, OldOcc from #THE_Xfers ' +
            'union all ' +
            'select AbstractID, NewOcc, OldOcc from #NON_Xfers ' +

        ') n on o.AbstractID = n.AbstractID and o.DiagnosisOccurrence = n.OldOcc  ' 
    exec( @sql )

    if ((select object_id('tempdb..#THE_Xfers')) is not null) drop table #THE_Xfers
    if ((select object_id('tempdb..#NON_Xfers')) is not null) drop table #NON_Xfers

    return 0
----------------------------------------------------------------------------------------------
exit_procedure_with___error:
    return 1




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [SU_Prep_DAD_9andCM_DiagnosisTransfers_new]
    @ExecutionID int
AS 

    declare @sql           nvarchar(800)
    declare @table_name    nvarchar(50)

----------------------------------------------------------------------------------------------
    -- ReSequence the Diagnosis Occurrences based transfers

    set @table_name = dbo.SUF_GetTempTable ( @ExecutionID, 'AB_Diagnosis' )

    ---------------------------------------------------------------------------------
    -- THE-trasfer select -----------------------------------------------------------
    if ((select object_id('tempdb..#THE_Xfers')) is not null) drop table #THE_Xfers
    create table #THE_Xfers (AbstractID int, OldOcc int, NewOcc int null)
    
    print 'hard-code new occurrence values for transfers.'
    -- hard-code new occurrence values for transfers.
    set @sql = 
        'select AbstractID, DiagnosisOccurrence, ' +
            'NewOcc = case l.CIHIValue ' +
                    'when ''W'' then 14 ' +
                    'when ''X'' then 15 ' +
                    'when ''Y'' then 16 ' +
                    'else null ' +
                'end ' +
        'from ' + @table_name + ' d ' +
        'join LU_DiagnosisType l on d.DiagnosisType = l.Code ' +
        'where l.CIHIValue in (''W'', ''X'', ''Y'') ' 
    
    insert #THE_Xfers (AbstractID, OldOcc, NewOcc) exec ( @sql )



    ---------------------------------------------------------------------------------
    -- NON-trasfer select -----------------------------------------------------------
    if ((select object_id('tempdb..#NON_Xfers')) is not null) drop table #NON_Xfers
    create table #NON_Xfers (AbstractID int, OldOcc int, NewOcc int null, OccSeed int identity(1,1))

    set @sql = 
        'select AbstractID, DiagnosisOccurrence ' +
        'from ' + @table_name + ' d ' +
        'join LU_DiagnosisType l on d.DiagnosisType = l.Code ' +
        'where l.CIHIValue not in (''W'', ''X'', ''Y'') ' +
        'order by AbstractID, DiagnosisOccurrence '
    
    insert #NON_Xfers (AbstractID, OldOcc) exec ( @sql )

    print 'calculate and update new occurrence field for non-xfers'
    -- calculate and update new occurrence field for non-xfers
    update #NON_Xfers
    set NewOcc = OccSeed - minSeed.val + 1
    from #NON_Xfers 
    join (
        select AbstractID, val = min(OccSeed)
        from #NON_Xfers
        group by AbstractID
    ) minSeed on #NON_Xfers.AbstractID = minSeed.AbstractID
    

    print 'delete any non-transfers that overlap a transfer'
    -- delete any non-transfers that overlap a transfer
    delete #NON_Xfers
    from #NON_Xfers n join #THE_Xfers x 
      on n.AbstractID = x.AbstractID and n.NewOcc = x.NewOcc
        
    print 'remove the overlaps from the original table'
    -- remove the overlaps from the original table
    set @sql = 
        'delete ' + @table_name + ' ' +
        'from ' + @table_name + ' o ' +
        'left join ( ' +

            'select AbstractID, NewOcc, OldOcc from #THE_Xfers ' +
            'union all ' +
            'select AbstractID, NewOcc, OldOcc from #NON_Xfers ' +

        ') n on o.AbstractID = n.AbstractID and o.DiagnosisOccurrence = n.OldOcc  ' +
        'where n.AbstractID is null '
    exec( @sql )
    
    print 'update the occurrence number for all remaining records'
    -- update the occurrence number for all remaining records
    set @sql = 
        'update ' + @table_name + ' ' +
        'set DiagnosisOccurrence = n.NewOcc ' +
        'from ' + @table_name + ' o ' +
        'join ( ' +

            'select AbstractID, NewOcc, OldOcc from #THE_Xfers ' +
            'union all ' +
            'select AbstractID, NewOcc, OldOcc from #NON_Xfers ' +

        ') n on o.AbstractID = n.AbstractID and o.DiagnosisOccurrence = n.OldOcc  ' 
    exec( @sql )

    if ((select object_id('tempdb..#THE_Xfers')) is not null) drop table #THE_Xfers
    if ((select object_id('tempdb..#NON_Xfers')) is not null) drop table #NON_Xfers

    return 0
----------------------------------------------------------------------------------------------
exit_procedure_with___error:
    return 1




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [SU_Prep_DAD_9andCM_DoctorTransfers]
    @ExecutionID int
AS 

    declare @sql           nvarchar(800)
    declare @table_name    nvarchar(50)

----------------------------------------------------------------------------------------------
    -- ReSequence the Provider Occurrences based transfers

    set @table_name = dbo.SUF_GetTempTable ( @ExecutionID, 'AB_Provider' )

    ---------------------------------------------------------------------------------
    -- THE-trasfer select -----------------------------------------------------------
    if ((select object_id('tempdb..#THE_Xfers')) is not null) drop table #THE_Xfers
    create table #THE_Xfers (AbstractID int, OldOcc int, NewOcc int null)
    
    print 'hard-code new occurrence values for transfers.'
    -- hard-code new occurrence values for transfers.
    set @sql = 
        'select AbstractID, ProviderOccurrence, ' +
            'NewOcc = case l.CIHIValue ' +
                    'when ''W'' then 6 ' +
                    'when ''X'' then 7 ' +
                    'when ''Y'' then 8 ' +
                    'else null ' +
                'end ' +
        'from ' + @table_name + ' d ' +
        'join LU_ProviderType l on d.ProviderType = l.Code ' +
        'where l.CIHIValue in (''W'', ''X'', ''Y'') ' 
    
    insert #THE_Xfers (AbstractID, OldOcc, NewOcc) exec ( @sql )



    ---------------------------------------------------------------------------------
    -- NON-trasfer select -----------------------------------------------------------
    if ((select object_id('tempdb..#NON_Xfers')) is not null) drop table #NON_Xfers
    create table #NON_Xfers (AbstractID int, OldOcc int, NewOcc int null, OccSeed int identity(1,1))

    set @sql = 
        'select AbstractID, ProviderOccurrence ' +
        'from ' + @table_name + ' d ' +
        'join LU_ProviderType l on d.ProviderType = l.Code ' +
        'where l.CIHIValue not in (''W'', ''X'', ''Y'') ' +
        'order by AbstractID, ProviderOccurrence '
    
    insert #NON_Xfers (AbstractID, OldOcc) exec ( @sql )

    print 'calculate and update new occurrence field for non-xfers'
    -- calculate and update new occurrence field for non-xfers
    update #NON_Xfers
    set NewOcc = OccSeed - minSeed.val + 1
    from #NON_Xfers 
    join (
        select AbstractID, val = min(OccSeed)
        from #NON_Xfers
        group by AbstractID
    ) minSeed on #NON_Xfers.AbstractID = minSeed.AbstractID
    

    print 'delete any non-transfers that overlap a transfer'
    -- delete any non-transfers that overlap a transfer
    delete #NON_Xfers
    from #NON_Xfers n join #THE_Xfers x 
      on n.AbstractID = x.AbstractID and n.NewOcc = x.NewOcc
        
    print 'remove the overlaps from the original table'
    -- remove the overlaps from the original table
    set @sql = 
        'delete ' + @table_name + ' ' +
        'from ' + @table_name + ' o ' +
        'left join ( ' +

            'select AbstractID, NewOcc, OldOcc from #THE_Xfers ' +
            'union all ' +
            'select AbstractID, NewOcc, OldOcc from #NON_Xfers ' +

        ') n on o.AbstractID = n.AbstractID and o.ProviderOccurrence = n.OldOcc  ' +
        'where n.AbstractID is null '
    exec( @sql )
    
    print 'update the occurrence number for all remaining records'
    -- update the occurrence number for all remaining records
    set @sql = 
        'update ' + @table_name + ' ' +
        'set ProviderOccurrence = n.NewOcc ' +
        'from ' + @table_name + ' o ' +
        'join ( ' +

            'select AbstractID, NewOcc, OldOcc from #THE_Xfers ' +
            'union all ' +
            'select AbstractID, NewOcc, OldOcc from #NON_Xfers ' +

        ') n on o.AbstractID = n.AbstractID and o.ProviderOccurrence = n.OldOcc  ' 
    exec( @sql )

    if ((select object_id('tempdb..#THE_Xfers')) is not null) drop table #THE_Xfers
    if ((select object_id('tempdb..#NON_Xfers')) is not null) drop table #NON_Xfers

    return 0
----------------------------------------------------------------------------------------------
exit_procedure_with___error:
    return 1




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE PROCEDURE [SU_Prep_DAD_Rehab_TransferDeath]
    @ExecutionID int
AS 

    declare @sql           nvarchar(800)
    declare @table_name    nvarchar(50)

    --
    -- RESEQUENCE THE DIAGNOSIS OCCURRENCES BASED TRANSFERS
    --
    set @table_name = dbo.SUF_GetTempTable ( @ExecutionID, 'RH_Diagnosis' )

    --
    -- SELECT THE-TRASFER DIAGNOSIS INTO A TEMP TABLE
    --
    if ((select object_id('tempdb..#THE_Xfers')) is not null) drop table #THE_Xfers
    create table #THE_Xfers (AbstractID int, OldOcc int, NewOcc int null)
    

    --
    -- HARD-CODE NEW OCCURRENCE VALUES FOR TRANSFERS AND DEATHS.
    --    TYPE W (TRANS) = OCCURRENCE 12
    --
    -- IF THERE IS A DEATH, IT TAKES PRECEDENCE OVER A TRANSFER. 
    --
    set @sql = 
        'select AbstractID, DiagnosisOccurrence, ' +
            'NewOcc = case l.CIHIValue when ''W'' then 12 end ' +
        'from ' + @table_name + ' d ' +
        'join LU_DiagnosisType l on d.DiagnosisType = l.Code ' +
        'where l.CIHIValue = ''W'' '
    insert #THE_Xfers (AbstractID, OldOcc, NewOcc) exec ( @sql )


    --
    -- SELECT NON-TRASFER DIAGNOSIS INTO A TEMP TABLE
    --
    if ((select object_id('tempdb..#NON_Xfers')) is not null) drop table #NON_Xfers
    create table #NON_Xfers (AbstractID int, OldOcc int, NewOcc int null, OccSeed int identity(1,1))

    set @sql = 
        'select AbstractID, DiagnosisOccurrence ' +
        'from ' + @table_name + ' d ' +
        'left join LU_DiagnosisType l on d.DiagnosisType = l.Code ' +
        'where isnull(l.CIHIValue, '''') not in (''W'') ' +
        'order by AbstractID, DiagnosisOccurrence '
    
    insert #NON_Xfers (AbstractID, OldOcc) exec ( @sql )

    --
    -- CALCULATE AND UPDATE NEW OCCURRENCE FIELD FOR NON-XFERS
    --
    update #NON_Xfers
    set NewOcc = OccSeed - minSeed.val + 1
    from #NON_Xfers 
    join (
        select AbstractID, val = min(OccSeed)
        from #NON_Xfers
        group by AbstractID
    ) minSeed on #NON_Xfers.AbstractID = minSeed.AbstractID
    
    --
    -- DELETE ANY NON-TRANSFERS THAT OVERLAP A TRANSFER
    --
    delete #NON_Xfers
    from #NON_Xfers n join #THE_Xfers x 
      on n.AbstractID = x.AbstractID and n.NewOcc = x.NewOcc

    -- Ticket 11925, DELETE ANY NON-TRANSFERS THAT Occurrence more than 11
    --
    delete #NON_Xfers
    from #NON_Xfers 
    where NewOcc > 11

    --        
    -- REMOVE THE OVERLAPS FROM THE ORIGINAL TABLE
    --
    set @sql = 
        'delete ' + @table_name + ' ' +
        'from ' + @table_name + ' o ' +
        'left join ( ' +

            'select AbstractID, NewOcc, OldOcc from #THE_Xfers ' +
            'union all ' +
            'select AbstractID, NewOcc, OldOcc from #NON_Xfers ' +

        ') n on o.AbstractID = n.AbstractID and o.DiagnosisOccurrence = n.OldOcc  ' +
        'where n.AbstractID is null '
    exec( @sql )

    --    
    -- UPDATE THE OCCURRENCE NUMBER FOR ALL REMAINING RECORDS
    --
    set @sql = 
        'update ' + @table_name + ' ' +
        'set DiagnosisOccurrence = n.NewOcc ' +
        'from ' + @table_name + ' o ' +
        'join ( ' +

            'select AbstractID, NewOcc, OldOcc from #THE_Xfers ' +
            'union all ' +
            'select AbstractID, NewOcc, OldOcc from #NON_Xfers ' +

        ') n on o.AbstractID = n.AbstractID and o.DiagnosisOccurrence = n.OldOcc  ' 
    exec( @sql )

    if ((select object_id('tempdb..#THE_Xfers')) is not null) drop table #THE_Xfers
    if ((select object_id('tempdb..#NON_Xfers')) is not null) drop table #NON_Xfers

    return 0
----------------------------------------------------------------------------------------------
exit_procedure_with___error:
    return 1


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [SU_Prep_Rehab_TransferDeath_ICD10]
    @ExecutionID int
AS 

    declare @sql           nvarchar(800)
    declare @table_name    nvarchar(50)

    --
    -- RESEQUENCE THE DIAGNOSIS OCCURRENCES BASED TRANSFERS
    --
    set @table_name = dbo.SUF_GetTempTable ( @ExecutionID, 'RH_Diagnosis' )

    --
    -- SELECT THE-TRASFER DIAGNOSIS INTO A TEMP TABLE
    --
    if ((select object_id('tempdb..#THE_Xfers')) is not null) drop table #THE_Xfers
    create table #THE_Xfers (AbstractID int, OldOcc int, NewOcc int null)
    

    --
    -- HARD-CODE NEW OCCURRENCE VALUES FOR TRANSFERS AND DEATHS.
    --    TYPE W (TRANS) = OCCURRENCE 17
    --
    -- IF THERE IS A DEATH, IT TAKES PRECEDENCE OVER A TRANSFER. 
    --
    set @sql = 
        'select AbstractID, DiagnosisOccurrence, ' +
            'NewOcc = case l.CIHIValue when ''W'' then 17 end ' +
        'from ' + @table_name + ' d ' +
        'join LU_DiagnosisType l on d.DiagnosisType = l.Code ' +
        'where l.CIHIValue = ''W'' ' + 
        'order by AbstractID, DiagnosisOccurrence '
    insert #THE_Xfers (AbstractID, OldOcc, NewOcc) exec ( @sql )

    --PR - 04471 has 3 transder/death condition
    Delete from #THE_Xfers
    from #THE_Xfers z inner join
        (select AbstractID, min(OldOcc) minOcc
         from #THE_Xfers
         group by AbstractID
         having count(*) > 1) d on z.AbstractID = d.AbstractID
    where z.OldOcc <> d.minOcc

    --
    -- SELECT NON-TRASFER DIAGNOSIS INTO A TEMP TABLE
    --
    if ((select object_id('tempdb..#NON_Xfers')) is not null) drop table #NON_Xfers
    create table #NON_Xfers (AbstractID int, OldOcc int, NewOcc int null, OccSeed int identity(1,1))

    set @sql = 
        'select AbstractID, DiagnosisOccurrence ' +
        'from ' + @table_name + ' d ' +
        'left join LU_DiagnosisType l on d.DiagnosisType = l.Code ' +
        'where isnull(l.CIHIValue, '''') not in (''W'') ' +
        'order by AbstractID, DiagnosisOccurrence '
    
    insert #NON_Xfers (AbstractID, OldOcc) exec ( @sql )

    --
    -- CALCULATE AND UPDATE NEW OCCURRENCE FIELD FOR NON-XFERS
    --
    update #NON_Xfers
    set NewOcc = OccSeed - minSeed.val + 1
    from #NON_Xfers 
    join (
        select AbstractID, val = min(OccSeed)
        from #NON_Xfers
        group by AbstractID
    ) minSeed on #NON_Xfers.AbstractID = minSeed.AbstractID
    
    --
    -- DELETE ANY NON-TRANSFERS THAT OVERLAP A TRANSFER
    --
    delete #NON_Xfers
    from #NON_Xfers n join #THE_Xfers x 
      on n.AbstractID = x.AbstractID and n.NewOcc = x.NewOcc

    -- Ticket 11925, DELETE ANY NON-TRANSFERS THAT Occurrence more than 11
    --
    delete #NON_Xfers
    from #NON_Xfers 
    where NewOcc > 16

    --        
    -- REMOVE THE OVERLAPS FROM THE ORIGINAL TABLE
    --
    set @sql = 
        'delete ' + @table_name + ' ' +
        'from ' + @table_name + ' o ' +
        'left join ( ' +

            'select AbstractID, NewOcc, OldOcc from #THE_Xfers ' +
            'union all ' +
            'select AbstractID, NewOcc, OldOcc from #NON_Xfers ' +

        ') n on o.AbstractID = n.AbstractID and o.DiagnosisOccurrence = n.OldOcc  ' +
        'where n.AbstractID is null '
    exec( @sql )

    --    
    -- UPDATE THE OCCURRENCE NUMBER FOR ALL REMAINING RECORDS
    --
    set @sql = 
        'update ' + @table_name + ' ' +
        'set DiagnosisOccurrence = n.NewOcc ' +
        'from ' + @table_name + ' o ' +
        'join ( ' +

            'select AbstractID, NewOcc, OldOcc from #THE_Xfers ' +
            'union all ' +
            'select AbstractID, NewOcc, OldOcc from #NON_Xfers ' +

        ') n on o.AbstractID = n.AbstractID and o.DiagnosisOccurrence = n.OldOcc  ' 
    exec( @sql )

    if ((select object_id('tempdb..#THE_Xfers')) is not null) drop table #THE_Xfers
    if ((select object_id('tempdb..#NON_Xfers')) is not null) drop table #NON_Xfers

    return 0
----------------------------------------------------------------------------------------------
exit_procedure_with___error:
    return 1

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [SU_PurgeDeletes]
    @ExecutionID int
as

declare 
  @sql nvarchar(500)
, @GroupID int
, @AppID int
, @AbstractID int
, @IsCorrection int

declare
	 @CareType    	[varchar](50),
	 @ICDType     	[varchar](50),
	 @InstNumber 	[varchar](50),
	 @ChartNumber 	[varchar](50),
	 @FullName     	[varchar](100),
	 @EncounterNumber 	    [varchar](50),
	 @EncounterSequence 	[varchar](50),
	 @VisitDate    	[datetime],
	 @VisitTime    	[datetime],
	 @CIHIDateSent  [datetime], 
	 @BatchYear 		[varchar](50), 
	 @BatchPeriod 		[varchar](50), 
	 @BatchNumber 	[varchar](50), 
	 @AbstNumber 		[varchar](50), 
	 @IsCompleted 		[varchar](50), 
	 @IsValidated 		[varchar](50), 
	 @IsSubmitted 		[varchar](50), 
	 @IsCorrected 		[varchar](50),
	 @DeleteCoder   [varchar](50),
	 @DeleteDate 	[datetime],
	 @DeleteTime 	[datetime],
	 @PurgeCoder 	[varchar](50),
	 @PurgeDate 	[datetime],
	 @PurgeTime 	[datetime]
--     @FileName      varchar(250)

select @AppID = AppID
, @GroupID = GroupID
, @IsCorrection = IsCorrection 
, @InstNumber = InstNoCIHI
, @ICDType = ICDType
, @PurgeCoder = (select top 1 DisplayCode from U_Users where code = CoderNumber)
, @PurgeDate = convert(varchar(10), ExecutionDate, 111)
, @PurgeTime = '1900/01/01 ' + convert(varchar(10), ExecutionDate, 108)
--, @FileName = NameOfFile
from SU_ExecProperties 
where ExecutionID = @ExecutionID

if (@IsCorrection = 1) and (@GroupID in (4, 6, 7, 8, 9, 13, 14, 15, 16, 18, 51, 17, 19, 26, 27, 28, 30, 31, 32, 33, 34, 35, 36, 37, 38, 40, 41, 43, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 83)) begin

    declare cur cursor local fast_forward for
        select r.AbstractID,  
	         CareType = (case a.CareType when 1 then 'A' when 2 then 'D' when 5 then 'B' else 'O' end),
	         a.ChartNumber,
	         FullName = left(isnull(a.LastName, '') + ', ' + isnull(a.FirstName, '') + ' ' + isnull(a.MiddleName, ''), 100),
        	 a.EncounterNumber, 
             a.EncounterSequence,
	         VisitDate = (case when a.CareType = 5 then a.AdmitDate else isnull(a.DischargeDate, a.AdmitDate) end),
	         VisitTime = (case when a.CareType = 5 then a.AdmitTime else (case when a.DischargeDate is null then a.AdmitTime else a.DischargeTime end) end),
	         a.CIHIDateSent, a.BatchYear, 
             BatchPeriod = (select top 1 DisplayCode from Lu_BatchPeriod where code = a.BatchPeriod), 
             a.BatchNumber, a.AbstractNumber, 
	         IsCompleted  = (case a.IsCompleted when 1 then 'N' when 2 then 'E' when 3 then 'W' when 4 then 'Y' end), 
             IsValidated  = (case a.IsValidated when 1 then 'N' when 2 then 'E' when 3 then 'W' when 4 then 'Y' end),  
             IsSubmited   = (case a.IsSubmited when 1 then 'Y' when 2 then 'N' end), 
             IsCorrected  = (case a.IsCorrected when 1 then 'N' when 2 then 'P' when 3 then 'C' end) 
        from SU_RecordHistory r 
        join AB_Abstract a on r.AbstractID = a.AbstractID
        where a.IsDeleted in (1, 3)
            and r.ExecutionID = @ExecutionID
            and 1= (case when a.CareType = 5 
                         then (case when a.IsCorrectLevel1 = 3 and a.IsCorrected = 3 then 1
                                    when a.BatchYear > 2009 and a.IsCorrected = 3 then 1	--2010 CIHI will have one set database.
                                    when a.IsCorrectLevel1 = 3 and isnull(a.IsCorrected, 1) in (0, 1) then 1
                                    when isnull(a.IsCorrectLevel1, 1) in (0, 1) and a.IsCorrected = 3 then 1
                                    else 0
                               end)
                         else 1 
                    end)
    
    set @sql = N'exec D_AB_Abstract @AbstractID, @AppID'

    open cur

    while (1=1) begin
        fetch next from cur into @AbstractID, @CareType, 
            @ChartNumber, @FullName, @EncounterNumber, @EncounterSequence,
            @VisitDate, @VisitTime, @CIHIDateSent, @BatchYear, @BatchPeriod, 
            @BatchNumber, @AbstNumber, @IsCompleted, @IsValidated, 
            @IsSubmitted, @IsCorrected

        if (@@fetch_status <> 0) break
        
        select top 1
            @DeleteCoder = (select top 1 DisplayCode from U_Users where code = Coder),
            @DeleteDate  = 	convert(varchar(10), Updated, 111),
            @DeleteTime  = '1900/01/01 ' + convert(varchar(10), Updated, 108)
        from AB_UpdateHistory
        where AbstractID = @AbstractID and UpdateType = 'Saved'
        order by Updated desc

        exec sp_executesql @sql, N'@AbstractID int, @AppID int', @AbstractID, @AppID

        exec I_REC_Purge @AppID, @AbstractID, @CareType, @ICDType, @InstNumber,
            @ChartNumber, @FullName, @EncounterNumber, @EncounterSequence,
            @VisitDate, @VisitTime, @CIHIDateSent, @BatchYear, @BatchPeriod, 
            @BatchNumber, @AbstNumber, @IsCompleted, @IsValidated, 
            @IsSubmitted, @IsCorrected, @DeleteCoder, @DeleteDate, @DeleteTime, 
            @PurgeCoder, @PurgeDate, @PurgeTime
    end 

    close cur
    deallocate cur
end
else 
if (@GroupID in (20)) begin --13242

    --PR - 04347
    delete from REC_RH_KeyUpdate
    from SU_RecordHistory r 
        join RH_ClientInfo a on r.AbstractID = a.AbstractID
        join REC_RH_KeyUpdate z on a.AbstractID = z.OriginalID
    where r.ExecutionID = @ExecutionID and a.IsDeleted in (1, 3)

    declare cur cursor local fast_forward for
        select r.AbstractID,  
	         CareType = (case a.CareType when 3 then 'R' else 'O' end) + isnull('-' + lu.DisplayCode + '(' + UserDescription + ')', ''),
	         a.ChartNumber,
	         FullName = left(isnull(demo.LastName, '') + ', ' + isnull(demo.FirstName, '') + ' ' + isnull(demo.MiddleName, ''), 100),
        	 a.EncounterNumber, 
             EncounterSequence = null,
	         VisitDate = a.AdmitDate,
	         VisitTime = (case when lu.CIHIValue = '2' then a.DischargeDate when lu.CIHIValue = '3' then a.followupdate else null end),
	         a.CIHIDateSent, a.BatchYear, 
             BatchPeriod = (select top 1 DisplayCode from Lu_CodeFile where code = a.BatchPeriod), 
             BatchNumber = null, 
             a.AbstractNumber, 
	         IsCompleted  = (case a.IsCompleted when 1 then 'N' when 2 then 'E' when 3 then 'W' when 4 then 'Y' end), 
             IsValidated  = (case a.IsValidated when 1 then 'N' when 2 then 'E' when 3 then 'W' when 4 then 'Y' end),  
             IsSubmited   = (case a.IsSubmited when 1 then 'Y' when 2 then 'N' end), 
             IsCorrected  = (case a.IsCorrected when 1 then 'N' when 2 then 'P' when 3 then 'C' end) 
        from SU_RecordHistory r 
            join RH_ClientInfo a on r.AbstractID = a.AbstractID
            join RH_Demographic demo on a.AbstractID = demo.AbstractID
            left join lu_codefile lu on a.AssessmentType = lu.code
        where a.IsDeleted in (1, 3) and r.ExecutionID = @ExecutionID
    
    set @sql = N'exec D_RH_ClientInfo @AbstractID'

    open cur

    while (1=1) begin
        fetch next from cur into @AbstractID, @CareType, 
            @ChartNumber, @FullName, @EncounterNumber, @EncounterSequence,
            @VisitDate, @VisitTime, @CIHIDateSent, @BatchYear, @BatchPeriod, 
            @BatchNumber, @AbstNumber, @IsCompleted, @IsValidated, 
            @IsSubmitted, @IsCorrected

        if (@@fetch_status <> 0) break
        
        select top 1
            @DeleteCoder = (select top 1 DisplayCode from U_Users where code = Coder),
            @DeleteDate  = 	convert(varchar(10), Updated, 111),
            @DeleteTime  = '1900/01/01 ' + convert(varchar(10), Updated, 108)
        from RH_UpdateHistory
        where AbstractID = @AbstractID and UpdateType = 'Saved'
        order by Updated desc

        exec sp_executesql @sql, N'@AbstractID int', @AbstractID

        exec I_REC_Purge @AppID, @AbstractID, @CareType, @ICDType, @InstNumber,
            @ChartNumber, @FullName, @EncounterNumber, @EncounterSequence,
            @VisitDate, @VisitTime, @CIHIDateSent, @BatchYear, @BatchPeriod, 
            @BatchNumber, @AbstNumber, @IsCompleted, @IsValidated, 
            @IsSubmitted, @IsCorrected, @DeleteCoder, @DeleteDate, @DeleteTime, 
            @PurgeCoder, @PurgeDate, @PurgeTime
    end 

    close cur
    deallocate cur

end
else 
if (@GroupID in (9999650)) begin --13242 )) --2.x-0794 656

    declare cur cursor local fast_forward for
        select r.AbstractID,  
	         CareType = (case a.CareType when 7 then 'M' else 'N' end) + isnull('-' + lu.DisplayCode + '(' + UserDescription + ')', ''),
	         a.ChartNumber,
	         FullName = left(isnull(a.LastName, '') + ', ' + isnull(a.FirstName, '') + ' ' + isnull(a.MiddleName, ''), 100),
        	 EncounterNumber = a.AA3, 
             EncounterSequence = null,
	         VisitDate = a.AdmitDate,
	         VisitTime = a.AdmitTime,
	         info.CIHIDateSent, info.BatchYear, 
             BatchPeriod = (select top 1 DisplayCode from Lu_CodeFile where code = info.BatchPeriod), 
             BatchNumber = null, 
             AbstractNumber = a.X1, 
	         IsCompleted  = (case info.IsCompleted when 1 then 'N' when 2 then 'E' when 3 then 'W' when 4 then 'Y' end), 
             IsValidated  = (case info.IsValidated when 1 then 'N' when 2 then 'E' when 3 then 'W' when 4 then 'Y' end),  
             IsSubmited   = (case info.IsSubmited when 1 then 'Y' when 2 then 'N' end), 
             IsCorrected  = (case info.IsCorrected when 1 then 'N' when 2 then 'P' when 3 then 'C' end) 
        from SU_RecordHistory r 
            join OMHRS_SecAA a on r.AbstractID = a.AbstractID
            join OMHRS_SecA sa on a.AbstractID = sa.AbstractID
            join OMHRS_RecInfo info on a.AbstractID = info.AbstractID
            left join lu_codefile lu on a.Z1 = lu.code
        where info.IsDeleted in (1, 3) and r.ExecutionID = @ExecutionID
    
    set @sql = N'exec D_OMHRS_SecAA @AbstractID'

    open cur

    while (1=1) begin
        fetch next from cur into @AbstractID, @CareType, 
            @ChartNumber, @FullName, @EncounterNumber, @EncounterSequence,
            @VisitDate, @VisitTime, @CIHIDateSent, @BatchYear, @BatchPeriod, 
            @BatchNumber, @AbstNumber, @IsCompleted, @IsValidated, 
            @IsSubmitted, @IsCorrected

        if (@@fetch_status <> 0) break
        
        select top 1
            @DeleteCoder = (select top 1 DisplayCode from U_Users where code = Coder),
            @DeleteDate  = 	convert(varchar(10), Updated, 111),
            @DeleteTime  = '1900/01/01 ' + convert(varchar(10), Updated, 108)
        from RH_UpdateHistory
        where AbstractID = @AbstractID and UpdateType = 'Saved'
        order by Updated desc

        exec sp_executesql @sql, N'@AbstractID int', @AbstractID
		--print @abstractid

        exec I_REC_Purge @AppID, @AbstractID, @CareType, @ICDType, @InstNumber,
            @ChartNumber, @FullName, @EncounterNumber, @EncounterSequence,
            @VisitDate, @VisitTime, @CIHIDateSent, @BatchYear, @BatchPeriod, 
            @BatchNumber, @AbstNumber, @IsCompleted, @IsValidated, 
            @IsSubmitted, @IsCorrected, @DeleteCoder, @DeleteDate, @DeleteTime, 
            @PurgeCoder, @PurgeDate, @PurgeTime
    end 

    close cur
    deallocate cur
end
else 
if (@GroupID in (99990470)) begin --PR - 05788

    --PR - 04347
    --delete from REC_RH_KeyUpdate
    --from SU_RecordHistory r 
    --    join dbo.CRS_Demographic a on r.AbstractID = a.AbstractID
    --    join REC_RH_KeyUpdate z on a.AbstractID = z.OriginalID
    --where r.ExecutionID = @ExecutionID and a.IsDeleted in (1, 3)

    declare cur cursor local fast_forward for
        select r.AbstractID,  
	         CareType = 'L ' + isnull('-' + lu.DisplayCode + '(' + UserDescription + ')', ''),
	         demo.ChartNumber,
	         FullName = left(isnull(demo.LastName, '') + ', ' + isnull(demo.FirstName, '') + ' ' + isnull(demo.MiddleName, ''), 100),
        	 demo.EncounterNumber, 
             EncounterSequence = null,
	         VisitDate = demo.AdmitDate,
	         VisitTime = null,
	         demo.CIHIDateSent, demo.BatchYear, 
             BatchPeriod = (select top 1 DisplayCode from Lu_CodeFile where code = demo.BatchPeriod), 
             BatchNumber = null, 
             AbstractNumber = null, 
	         IsCompleted  = (case demo.IsCompleted when 1 then 'N' when 2 then 'E' when 3 then 'W' when 4 then 'Y' end), 
             IsValidated  = (case demo.IsValidated when 1 then 'N' when 2 then 'E' when 3 then 'W' when 4 then 'Y' end),  
             IsSubmited   = (case demo.IsSubmited when 1 then 'Y' when 2 then 'N' end), 
             IsCorrected  = (case demo.IsCorrected when 1 then 'N' when 2 then 'P' when 3 then 'C' end) 
        from SU_RecordHistory r 
            join CRS_Demographic demo on r.AbstractID = demo.AbstractID
            left join lu_codefile lu on demo.AA8 = lu.code
        where demo.IsDeleted in (1, 3) and r.ExecutionID = @ExecutionID
    
    set @sql = N'exec D_CRS_Demographic @AbstractID, @AppID'

    open cur

    while (1=1) begin
        fetch next from cur into @AbstractID, @CareType, 
            @ChartNumber, @FullName, @EncounterNumber, @EncounterSequence,
            @VisitDate, @VisitTime, @CIHIDateSent, @BatchYear, @BatchPeriod, 
            @BatchNumber, @AbstNumber, @IsCompleted, @IsValidated, 
            @IsSubmitted, @IsCorrected

        if (@@fetch_status <> 0) break
        
        select top 1
            @DeleteCoder = (select top 1 DisplayCode from U_Users where code = Coder),
            @DeleteDate  = 	convert(varchar(10), Updated, 111),
            @DeleteTime  = '1900/01/01 ' + convert(varchar(10), Updated, 108)
        from CRS_UpdateHistory
        where AbstractID = @AbstractID and UpdateType = 'Saved'
        order by Updated desc
        
        set @AppID = (select top 1 AppID from AB_Main where AbstractID = @AbstractID and AppType = 4)
        
        exec sp_executesql @sql, N'@AbstractID int, @AppID int', @AbstractID, @AppID

        exec I_REC_Purge @AppID, @AbstractID, @CareType, @ICDType, @InstNumber,
            @ChartNumber, @FullName, @EncounterNumber, @EncounterSequence,
            @VisitDate, @VisitTime, @CIHIDateSent, @BatchYear, @BatchPeriod, 
            @BatchNumber, @AbstNumber, @IsCompleted, @IsValidated, 
            @IsSubmitted, @IsCorrected, @DeleteCoder, @DeleteDate, @DeleteTime, 
            @PurgeCoder, @PurgeDate, @PurgeTime
    end 

    close cur
    deallocate cur

end


return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [SU_Rehab_Checking_Period]
    @InstNoCode   int,
    @DateFr varchar(10),
    @DateTo varchar(10),
    @SubmissionStartDate varchar(10), --EN - 00458
    @SubmissionEndDate varchar(10),   --EN - 00458
    @IsResubmit   int,
    @RecordCount  int output
as

declare @Records table ( AbstractID int, OrderBy int identity(1,1) )
declare @MultiSubmission int
select @MultiSubmission = isnull(IsMultiSubmission, 0)
from H_InstitutionProfile 
where Code = @InstNoCode

-- Deletion
insert @Records( AbstractID )
select AbstractID 
from RH_ClientInfo r
where (( AdmitDate between @DateFr and @DateTo and AssessmentType = 134 )
   or ( DischargeDate between @DateFr and @DateTo and AssessmentType = 135 )
   or ( FollowUpDate between @DateFr and @DateTo and AssessmentType = 136 ))
  and ( InstitutionNumber = @InstNoCode )
  and ( IsSubmited = 1 )
  and ( IsCorrected = 2)
  and ( IsDeleted in (1, 3) )

-- NRS_ADMISSION

insert @Records( AbstractID )
select AbstractID 
from RH_ClientInfo 
where ( AdmitDate between @DateFr and @DateTo )
  and ( InstitutionNumber = @InstNoCode )
  and ( 1 = case 
        when (@IsResubmit = 0 and ( IsSubmited = 2 or IsCorrected = 2 )) then 1 
        when (@IsResubmit = 1) then 1
        else 0 
        end )
  and ( IsDeleted = 2 )           
  and ( AssessmentType = 134 )
  --EN - 00458
  --and (@MultiSubmission <> 1 or Iscorrected = 2 or DischargeDate is not null or AbstractID in (select distinct rh.LinkID from RH_ClientInfo rh 
  and (((@MultiSubmission <> 1 or Iscorrected = 2 or DischargeDate is not null) and AdmitDate between @SubmissionStartDate and @SubmissionEndDate) 
	or AbstractID in (select distinct rh.LinkID from RH_ClientInfo rh 
                where rh.AssessmentType = 135 and rh.DischargeDate between @SubmissionStartDate and @SubmissionEndDate))   ----EN - 00458 -- PR - 03931/03930 
  --and (@MultiSubmission = 0 or Iscorrected = 2 or DischargeDate is not null or AbstractID in (select distinct rh.LinkID from RH_ClientInfo rh 
  --              where rh.AssessmentType = 135 and rh.DischargeDate is not null and rh.admitdate between @DateFr and @DateTo))   -- PR - 03931/03930 
  
-- NRS_DISCHARGE

insert @Records( AbstractID )
select AbstractID 
from RH_ClientInfo 
where ( DischargeDate between @DateFr and @DateTo ) 
  and ( DischargeDate between @SubmissionStartDate and @SubmissionEndDate )  --EN - 00458
  and ( InstitutionNumber = @InstNoCode )
  and ( 1 = case 
        when (@IsResubmit = 0 and ( IsSubmited = 2 or IsCorrected = 2 )) then 1 
        when (@IsResubmit = 1) then 1
        else 0 
        end )
  and ( IsDeleted = 2 )
  and ( AssessmentType = 135 )

-- NRS_FOLLOW_UP

insert @Records( AbstractID )
select AbstractID 
from RH_ClientInfo 
where ( FollowUpDate between @DateFr and @DateTo )
  and ( FollowUpDate between @SubmissionStartDate and @SubmissionEndDate )  --EN - 00458
  and ( InstitutionNumber = @InstNoCode )
  and ( 1 = case 
        when (@IsResubmit = 0 and ( IsSubmited = 2 or IsCorrected = 2 )) then 1 
        when (@IsResubmit = 1) then 1
        else 0 
        end )
  and ( IsDeleted = 2 )
  and ( AssessmentType = 136 )


set @RecordCount = isnull((select count(*) from @Records), 0)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [SU_Rehab_InitializeSubmission]
    @SU_Type      int,
    @InstNoCode   int,
    @BatchYear    int,
    @BatchPeriod  int,
    @IsCorrection int,
    @IsResubmit   int,
    @UseCareType  int,
    @BatchStart   int output,
    @BatchCount   int output,
    @RecordCount  int output,
    @RecordWidth  int output,
    @ExecutionID  int output,
    @ProvNoCIHI   varchar(1)   output,
    @InstNoCIHI   varchar(5)   output,
    @BatPerCIHI   varchar(2)   output,
    @CoderNumber  int = 999999 ,
    @DateFromMulti  datetime,	--EN - 00458
    @DateToMulti  datetime
as

-- eSU_DAD_I10_SUBMIT = 1  
-- eSU_DAD_I10_DELETE = 2  
-- eSU_DAD_I9C_SUBMIT = 3  
-- eSU_NAC_I10_SUBMIT = 4  
-- eSU_NAC_I9C_SUBMIT = 5  
-- eSU_NRS_DELETIONS  = 6  
-- eSU_NRS_ADMISSION  = 7  
-- eSU_NRS_DISCHARGE  = 8  
-- eSU_NRS_FOLLOW_UP  = 9  


declare 
    @DateFr varchar(10),
    @DateTo varchar(10)
declare @SubFiscalYear int
declare @RehabSubDate datetime

select 
    @DateFr = dbo.SUF_GetPeriodDateFr( @BatchYear, @BatchPeriod ), 
    @DateTo = dbo.SUF_GetPeriodDateTo( @BatchYear, @BatchPeriod )

declare @IsUseMentalHealth int

----EN - 00458
--declare @DateFromMulti datetime
--set @DateFromMulti = dateadd(month, -2, @DateToMulti)
--set @DateFromMulti = dateadd(day, 1 - datepart(day, @DateFromMulti), @DateFromMulti)


declare 
    @SU_Const varchar(20),
    @GroupID  int,
    @ProvCode int,
    @DateSent datetime,
    @ICDType  char(1),
    @AppID    int,
    @CareType int

declare @MaxCIHI_AbstractID int
declare @MaxSubmit_ID int
declare @MultiSubmission int

select @SU_Const = su_const from SU_StructureType where su_id = @SU_Type
select top 1 @ProvCode = ProvinceNumber from H_HospitalProfile
select @ProvNoCIHI = CIHIValue from LU_Province where Code = @ProvCode
select @CareType = AssociationID, @IsUseMentalHealth = UseMentalHealthData, @InstNoCIHI = CIHIValue,
    @RehabSubDate = RehabSubDate,  @MultiSubmission = isnull(IsMultiSubmission, 0)
from H_InstitutionProfile 
where Code = @InstNoCode

--EN - 00458
--PR - 04587
--if @MultiSubmission > 0 and @DateTo > @DateToMulti
--	set  @DateTo = convert(varchar(10), @DateToMulti, 111) 

set @AppID = 
    case @SU_Const
        when 'NRS_DELETIONS'  then 250
        when 'NRS_ADMISSION'  then 250
        when 'NRS_DISCHARGE'  then 251
        when 'NRS_FOLLOW_UP'  then 252
    end

set @DateSent = GetDate()
if @RehabSubDate is null 
    set @SubFiscalYear = @BatchYear
else 
begin
    set @SubFiscalYear = datepart(year, @DateSent) - (case when datepart(month, @DateSent) in (1, 2, 3) then 1 else 0 end)
    if @RehabSubDate >= @DateSent 
    begin
        if @BatchYear < @SubFiscalYear and @DateSent >= cast(cast(datepart(year, @RehabSubDate) as varchar(10)) + '/04/01' as datetime)
            set @SubFiscalYear = @SubFiscalYear - 1
        else if @BatchYear > @SubFiscalYear
            set @SubFiscalYear = @BatchYear

    end    
    else if @RehabSubDate < @DateSent 
    begin
        set @SubFiscalYear = datepart(year, @RehabSubDate) - (case when datepart(month, @RehabSubDate) in (1, 2, 3) then 1 else 0 end)
        if @BatchYear > @SubFiscalYear
            set @SubFiscalYear = @BatchYear

    end    
end

set @GroupID = dbo.SUF_GET_GroupID(@SU_Type, @AppID, @SubFiscalYear, 0, 0)

if @GroupID is null
    set @GroupID = (select top 1 GroupID from dbo.SU_StructureList where SU_type = @SU_type and @AppID = @AppID order by BatchYear desc)

set @ICDType = 'T'

declare @Records table ( AbstractID int, OrderBy int identity(1,1) )

--
-- IF THE HOSPITAL IS ALBERTA THEN THE BATCH YEAR NEEDS TO BE INCREMENTED BY ONE.
--
if exists (select * from H_HospitalProfile where ProvinceNumber = 13) begin
    set @BatchYear = str( cast(@BatchYear as int) + 1, 4 )
end



-- get a list of AbstractID's that will be used to creat the submission file

------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-- REHAB SUBMISSION, Admission, Discharge, FollowUp
if (@SU_Const in ('NRS_DELETIONS', 'NRS_ADMISSION', 'NRS_DISCHARGE', 'NRS_FOLLOW_UP')) begin


    if (@SU_Const = 'NRS_DELETIONS')
        --13242
        insert @Records( AbstractID )
        select AbstractID 
        from RH_ClientInfo r
--PR - 04320 do not check date
-- Beth give a point. All assessment deletion of a visit should be together.
--        where (( AdmitDate between @DateFr and @DateTo and AssessmentType = 134 )
--           or ( DischargeDate between @DateFr and @DateTo and AssessmentType = 135 )
--           or ( FollowUpDate between @DateFr and @DateTo and AssessmentType = 136 ))
--        where ( AdmitDate between @DateFr and @DateTo)
        where ( InstitutionNumber = @InstNoCode )
          and ( IsSubmited = 1 )
          and ( IsCorrected = 2)
          and ( IsDeleted in (1, 3) )
        order by AssessmentType desc, AdmitDate

    else
    if (@SU_Const = 'NRS_ADMISSION')

        insert @Records( AbstractID )
        select AbstractID 
        from RH_ClientInfo 
        where (AdmitDate between @DateFr and @DateTo)
		  and ( InstitutionNumber = @InstNoCode )
          and ( 1 = case 
                when (@IsResubmit = 0 and ( IsSubmited = 2 or IsCorrected = 2 )) then 1 
                when (@IsResubmit = 1) then 1
                else 0 
                end )
          and ( IsDeleted = 2 )           
          and ( AssessmentType = 134 )
          and  (((isnull(@MultiSubmission, 0) <> 1 or IsCorrected = 2 or DischargeDate is not null) and admitdate between @DateFromMulti and @DateToMulti) --EN - 00458 
          
          --and (@MultiSubmission = 0 or Iscorrected = 2 or DischargeDate is not null --EN - 00458
                or AbstractID in (select distinct rh.LinkID from RH_ClientInfo rh 
                        where rh.AssessmentType = 135 and rh.DischargeDate between @DateFromMulti and @DateToMulti and IsDeleted = 2 ))   --EN - 00458 
                        --where rh.AssessmentType = 135 and rh.DischargeDate between @DateFr and @DateToMulti and IsDeleted = 2 )) --EN - 00458  -- PR - 03931/03930 
        order by IsCorrected, AdmitDate, ChartNumber
        --                where rh.AssessmentType = 135 and rh.DischargeDate is not null and rh.admitdate between @DateFr and @DateTo))   -- PR - 03931/03930 

    else
    if (@SU_Const = 'NRS_DISCHARGE') 

        insert @Records( AbstractID )
        select AbstractID 
        from RH_ClientInfo 
        where ( DischargeDate between @DateFr and @DateTo )
		  and ( DischargeDate between @DateFromMulti and @DateToMulti) --EN - 00458 
          and ( InstitutionNumber = @InstNoCode )
          and ( 1 = case 
                when (@IsResubmit = 0 and ( IsSubmited = 2 or IsCorrected = 2 )) then 1 
                when (@IsResubmit = 1) then 1
                else 0 
                end )
          and ( IsDeleted = 2 )
          and ( AssessmentType = 135 )
        order by IsCorrected, AdmitDate, ChartNumber

    else
    if (@SU_Const = 'NRS_FOLLOW_UP') 

        insert @Records( AbstractID )
        select AbstractID 
        from RH_ClientInfo 
        where ( FollowUpDate between @DateFr and @DateTo )
          and ( FollowUpDate between @DateFromMulti and @DateToMulti) --EN - 00458
          and ( InstitutionNumber = @InstNoCode )
          and ( 1 = case 
                when (@IsResubmit = 0 and ( IsSubmited = 2 or IsCorrected = 2 )) then 1 
                when (@IsResubmit = 1) then 1
                else 0 
                end )
          and ( IsDeleted = 2 )
          and ( AssessmentType = 136 )
        order by IsCorrected, AdmitDate, ChartNumber

end

insert SU_ExecProperties 
       ( ExecutionDate, GroupID,  CoderNumber,  DateStart, DateEnd, InstNoCode,  BatchYear,  BatchPeriod,  IsCorrection,  IsResubmit,  SubFiscalYear ) 
values ( @DateSent,     @GroupID, @CoderNumber, @DateFr,   @DateTo, @InstNoCode, @BatchYear, @BatchPeriod, @IsCorrection, @IsResubmit, @SubFiscalYear )

set @ExecutionID = @@identity

delete SU_RecordSelect where ExecutionID = @ExecutionID

-- REHAB
if (@SU_Const in ('NRS_DELETIONS', 'NRS_ADMISSION', 'NRS_DISCHARGE', 'NRS_FOLLOW_UP')) begin

    insert SU_RecordSelect ( 
        ExecutionID  , 
        AbstractID   , 
        OrderBy      , 
        IsCorrected  , 
        IsSubmited   , 
        IsValidated  , 
        IsCompleted  , 
        IsDeleted    , 
        CIHIDateSent , 
        BatchYear    , 
        BatchPeriod  , 
        AbstractNumber )
    select 
        @ExecutionID   , 
        r.AbstractID   , 
        r.OrderBy      ,
        a.IsCorrected  ,
        a.IsSubmited   ,
        a.IsValidated  ,
        a.IsCompleted  ,
        a.IsDeleted    ,
        @DateSent      ,
        a.BatchYear    ,
        a.BatchPeriod  ,
        a.AbstractNumber
    from @Records r join RH_ClientInfo a on r.AbstractID = a.AbstractID 
    order by OrderBy

end

-- set the total number of records: 
set @RecordCount = @@rowcount

delete from @Records

DBCC DBREINDEX (SU_RecordSelect)


-- If this is a normal submission, the Batch Number must 
set @BatchStart = 1

------------------------------------------------------------------------------------

------------------------------------------------------------------------------------
-- for REHAB
if (@SU_Const in ('NRS_DELETIONS', 'NRS_ADMISSION', 'NRS_DISCHARGE', 'NRS_FOLLOW_UP')) begin 

    update SU_RecordSelect 
    set IsSubmited     = 1, 
        IsCorrected    = 1, 
        IsCompleted    = 4,
        BatchYear      = @BatchYear, 
        BatchPeriod    = @BatchPeriod, 
        AbstractNumber = r.AbstractID
    from RH_ClientInfo r 
    join SU_RecordSelect s on r.AbstractID = s.AbstractID and s.ExecutionID = @ExecutionID
    where r.IsSubmited = 2 

    update SU_RecordSelect 
    set IsSubmited   = 1, 
        IsCorrected  = 3, 
        IsCompleted  = 4
    from RH_ClientInfo r 
    join SU_RecordSelect s on r.AbstractID = s.AbstractID and s.ExecutionID = @ExecutionID
    where r.IsCorrected = 2

end



------------------------------------------------------------------------------------
-- CALCULATE VARIOUS RUNTIME PROPERTIES NEEDED TO RUN THE SUBMISSION PROGRAM.

if (0 < (select count(*) from SU_RecordSelect)) 
    select @BatchCount = ((count(*) - 1) / 100) + 1 from SU_RecordSelect where ExecutionID = @ExecutionID
else 
    set @BatchCount = 0

select @RecordWidth = sum( TextLength ) from SU_StructureFile where GroupID = @GroupID
--Hack, How about for BC: Rehab and CCRS
--if exists ( select * from H_HospitalProfile where ProvinceNumber <> 14 ) and 
if    @BatchPeriod in (15401,15402,15403,15404,15405,15651,15652,15653,
        15654,15655,15656,15657,15658,15659,15660,15661,15662)
    select @BatPerCIHI = CIHIValue from LU_CodeFile where Code = @BatchPeriod
else
    select @BatPerCIHI = CIHIValue from LU_BatchPeriod where Code = @BatchPeriod


-- UPDATE THE EXECUTION PROPERTIES TABLE WITH THE VARIOUS VALUES
update SU_ExecProperties
set ICDType     = @ICDType    ,
    AppID       = @AppID      ,
    BatchStart  = @BatchStart ,
    BatchCount  = @BatchCount ,
    RecordCount = @RecordCount,
    RecordWidth = @RecordWidth,
    ProvNoCIHI  = @ProvNoCIHI ,
    InstNoCIHI  = @InstNoCIHI ,     
    BatPerCIHI  = @BatPerCIHI ,
    IsUseMentalHealth = @IsUseMentalHealth
where ExecutionID = @ExecutionID

EXIT_PROCEDURE_NORMAL:
    return 0

ERROR___:
    return 1
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [SU_RPC_Billing_GetBatchHeader]
    @ExecutionID int,
    @BatchHeader varchar(4000) = '' output
as 

declare @SU_const varchar(20)

declare @ExecutionDate datetime
declare @GroupID       int
declare @BatchYear     varchar(4)
declare @BatchPeriod   varchar(10)
declare @RecCount_INT  int
declare @RecCount_CHR  varchar(10)
declare @InstNoCIHI    varchar(5)
declare @CIHIDateSent  varchar(8)

-- Carriage Return & Line Feed
declare @CrLf varchar(2)
set @CrLf = char(13) + char(10)

-- retrieve various common properties used 
-- throughout the submission program.
select 
    @ExecutionDate = ExecutionDate, 
    @GroupID       = GroupID, 
    @BatchYear     = cast( 0- BatchYear as varchar(10)), 
    @BatchPeriod   = cast(BatchPeriod as varchar(10)), 
    @RecCount_INT  = RecordCount, 
    @RecCount_CHR  = RecordCount, 
    @InstNoCIHI    = InstNoCIHI
from SU_ExecProperties 
where ExecutionID = @ExecutionID

set @CIHIDateSent = convert(varchar(8), @ExecutionDate, 112)
set @BatchPeriod = replicate('0', 2-len(@BatchPeriod)) + @BatchPeriod

/** SUBMISSION CONSTANTS/ENUMS
    1	DAD_I10_SUBMIT
    4	NAC_I10_SUBMIT
  **/
select @SU_const = SU_Const 
from SU_StructureType 
where su_id in (
    select distinct SU_Type 
    from SU_StructureList 
    where GroupID = @GroupID and BatchYear = @BatchYear and SU_Type in (38, 39))

-- branch off to the section which 
-- corresponds to the GroupID
if (@SU_const in ('DAD_I10_Billing')) 
begin
    set @RecCount_CHR  = replicate('0', 5-len(@RecCount_CHR)) + @RecCount_CHR

    set @BatchHeader = @InstNoCIHI + @BatchYear + @BatchPeriod

    -- Submission specific info
    set @BatchHeader = @BatchHeader + @RecCount_CHR + 'L000' 

    set @BatchHeader = @BatchHeader + 'A' + @CIHIDateSent --+ space(2471)

    if @BatchYear < 2007
        set @BatchHeader = @BatchHeader + space(2471)
    else 
        set @BatchHeader = @BatchHeader + space(2771)
end
else if (@SU_const in ('NAC_I10_Billing')) 
begin
    set @RecCount_CHR = replicate('0', 6 - len(@RecCount_CHR)) + @RecCount_CHR

    set @BatchHeader = '0' + @InstNoCIHI + 'M0004' + @BatchPeriod + '0' + @RecCount_CHR + @CIHIDateSent + space(72)
end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [SU_RPC_Billing_Initialize]
    @SU_Type      int,
    @DateFr       varchar(10),
    @DateTo       varchar(10),
    @InstNoCode   int,
    @BatchYear    int,
    @BatchPeriod  int,

    @IsCorrection int,
    @IsResubmit   int,
    @IsCompletedOnly int,

    @RecordCount  int output,
    @RecordWidth  int output,
    @ExecutionID  int output,
    @NameOfFile   varchar(50)   output,
    @CoderNumber  int = 999999,
    @ProjectNumber varchar(50),
    @ProjectQuestion int,
    @Answer        varchar(50)
as

-- eSU_MOHLTC_RPC_BILLING_DAD   = 38  
-- eSU_MOHLTC_RPC_BILLING_NACRS = 39

declare @AbstractNumber int

declare 
    @SU_Const varchar(20),
    @GroupID  int,
    @ProvCode int,
    @DateSent datetime,
    @ICDType  char(1),
    @AppID    int,
    @CareType int,
    @SequenceNumber int

declare @InstNoCIHI varchar(10)
declare @BatPerCIHI varchar(10)
declare @ProvNoCIHI varchar(10)
declare @IsUseMentalHealth int

declare @MaxSubmit_ID int

declare @Sql varchar(2000)
declare @where varchar(2000)

select @SU_Const = su_const from SU_StructureType where su_id = @SU_Type
select top 1 @ProvCode = ProvinceNumber from H_HospitalProfile
select @ProvNoCIHI = CIHIValue from LU_Province where Code = @ProvCode
select @CareType = AssociationID from H_InstitutionProfile where Code = @InstNoCode


set @AppID = 
    case @SU_Const
        when 'DAD_I10_Billing' then case @CareType when 1 then 201 else 202 end
        when 'NAC_I10_Billing' then 401
    end

set @GroupID = dbo.SUF_GET_GroupID(@SU_Type, @AppID, @BatchYear, @ProvCode, 3)

set @ICDType = 'T'

--declare @Records table ( AbstractID int, OrderBy int identity(1,1) )

Create table #Records( AbstractID int, VisitDate datetime, ChartNumber varchar(20), OrderBy int identity(1,1) )

--
-- IF THE HOSPITAL IS ALBERTA THEN THE BATCH YEAR NEEDS TO BE INCREMENTED BY ONE.
--
if exists (select * from H_HospitalProfile where ProvinceNumber = 13) begin
    set @BatchYear = str( cast(@BatchYear as int) + 1, 4 )
end

set @DateSent = GetDate()

-- get a list of AbstractID's that will be used to creat the submission file

------------------------------------------------------------------------------------


set @Sql = 'select distinct ab.AbstractID, isnull(DischargeDate, AdmitDate), ChartNumber from dbo.AB_Abstract ab '

if @SU_Const = ('DAD_I10_Billing') -- INPATIENT/SDS ICD 10
     set @where = 'where (isnull(DischargeDate, AdmitDate) between ''' + @DateFr + ''' and ''' + @DateTo + ''') and (InstitutionNumber = ' + cast(@InstNoCode as varchar(10)) + ') '
else if @SU_Const = ('NAC_I10_Billing') -- AMCARE INSTITUTIONS, ICD 10
     set @where = 'where (AdmitDate between ''' + @DateFr + ''' and ''' + @DateTo + ''') and (InstitutionNumber = ' + cast(@InstNoCode as varchar(10)) + ') '
-- Project
if  isnull(@ProjectNumber, '') <> '' 
begin
    set @sql = @sql + 'inner join dbo.AB_Project p on ab.AbstractID = p.AbstractID ' + 
                      'inner join dbo.LU_Project lp on p.ProjectNumber = lp.code '
    set @where = @where + 'and (lp.CIHIValue = ''' + replace(@ProjectNumber, '''', '''''') + ''') '
    if isnull(@ProjectQuestion, 0) between 1 and 13 and @Answer <> ''
    begin
        set @sql = @sql + 'inner join dbo.LU_ProjectQuestion' + cast(@ProjectQuestion as varchar(10)) + 
            ' q on p.Question' + cast(@ProjectQuestion as varchar(10)) + ' = q.code and q.AssociationID = lp.code '
        set @where = @where + 'and (q.CIHIValue = ''' + replace(@Answer, '''', '''''') + ''') '
    end
    else if isnull(@ProjectQuestion, 0) between 1 and 13 and isnull(@Answer, '') = ''
        set @Where = @where + 'and (p.Question' + cast(@ProjectQuestion as varchar(10)) + ' > 0) '
    else if @ProjectQuestion > 14 and isnull(@Answer, '') = ''
        set @Where = @where + 'and (isnull(p.Question' + cast(@ProjectQuestion as varchar(10)) + ', '''') <> '''') '
    else if @ProjectQuestion > 14 and isnull(@Answer, '') <> ''
        set @Where = @where + 'and (isnull(p.Question' + cast(@ProjectQuestion as varchar(10)) + ', '''') = ''' +  + ''') '
end
if @IsCorrection = 1
    set @Where = @where + ' and IsReciprocalBilling = 3 '
else if @IsResubmit = 0
    set @Where = @where + ' and isnull(IsReciprocalBilling, 2) in (2, 0) '

if @IsCompletedOnly = 1 and @IsResubmit = 0
    set @Where = @where + ' and IsValidated in (3, 4) '


set @sql = @sql + @where + ' order by isnull(DischargeDate, AdmitDate), ChartNumber ' 

--print @sql
insert #Records( AbstractID, VisitDate, ChartNumber )
exec (@sql)        
--            select AbstractID
--            from dbo.AB_Abstract
--            where (isnull(DischargeDate, AdmitDate) between @DateFr and @DateTo) 
--              and (InstitutionNumber = @InstNoCode) 
--            order by isnull(DischargeDate, AdmitDate, ChartNumber  


------------------------------------------------------------------------------------
set @SequenceNumber = isnull((select count(*) from dbo.SU_ExecProperties where GroupID = @GroupID 
                    and InstNoCode = @InstNoCode and BatchYear = (0 - @BatchYear) and BatchPeriod = @BatchPeriod
                    and TerminateSuccess = 1), 0)
set @SequenceNumber = @SequenceNumber + 1
if @SU_Const = ('DAD_I10_Billing')
    set @NameOfFile = replace(dbo.SU_FILENAME_DAD_ICD10 ( @InstNoCode, @BatchYear, @BatchPeriod, 0, 0, @SequenceNumber), '.txt', '.rcb')
else
    set @NameOfFile = replace(dbo.SU_FILENAME_NACRS (@InstNoCode, @BatchYear, @BatchPeriod, @SequenceNumber, 3), '.txt', '.rcb')

insert SU_ExecProperties 
       ( ExecutionDate, GroupID,  CoderNumber,  DateStart, DateEnd, InstNoCode,  BatchYear,  BatchPeriod,  IsCorrection,  IsResubmit, BatchStart, BatchCount) 
values ( @DateSent,     @GroupID, @CoderNumber, @DateFr,   @DateTo, @InstNoCode, 0 - @BatchYear, @BatchPeriod, @IsCorrection, @IsResubmit, 0, 0 )

set @ExecutionID = @@identity

delete SU_RecordSelect where ExecutionID = @ExecutionID

insert SU_RecordSelect (          ExecutionID  , 
    AbstractID   , 
    OrderBy      , 
    IsCorrected  , 
    IsSubmited   , 
    IsValidated  , 
    IsCompleted  , 
    IsDeleted    , 
    CIHIDateSent , 
    BatchYear    , 
    BatchPeriod  , 
    BatchNumber  , 
    AbstractNumber )
select 
    @ExecutionID   , 
    r.AbstractID   , 
    r.OrderBy      ,
    a.IsReciprocalBilling,
    a.IsReciprocalBilling,
    a.IsValidated  ,
    a.IsCompleted  ,
    a.IsDeleted    ,
    @DateSent      ,
    a.BatchYear    ,
    a.BatchPeriod  ,
    b.RPB_BatchNumber  ,
    b.RPB_AbstractNumber
from #Records r 
    join AB_Abstract a on r.AbstractID = a.AbstractID
    left join dbo.AB_ReciprocalBilling b on a.AbstractID = b.AbstractID
order by OrderBy
    
-- set the total number of records: 
set @RecordCount = @@rowcount
drop table #Records

declare @BatchStart int

if (@IsCorrection = 0 and @IsResubmit = 0) 
begin
    set @BatchStart = 1 + isnull( 
        (
            select max(RPB_BatchNumber)
            from AB_Abstract a
                inner join AB_ReciprocalBilling b on a.AbstractID = b.AbstractID
            where InstitutionNumber = @InstNoCode
            and BatchPeriod = @BatchPeriod
            and BatchYear = @BatchYear
            and isnull(IsReciprocalBilling, 1) in (1, 0)
        ), 0)
end
else
    set @BatchStart = 1

-- for Amcare 10
if @SU_Const = 'NAC_I10_Billing' begin

    if (@IsCorrection = 0 or @IsResubmit = 1) 
    begin
        update SU_RecordSelect 
        set IsSubmited     = 1, 
            BatchYear      = @BatchYear, 
            BatchPeriod    = @BatchPeriod, 
            BatchNumber    = 0, 
       	    --PR-01550
            AbstractNumber = (case when @ProvNoCIHI = '8' then a.AbstractID  --Ticket PR-00915
                              when isnull(a.CIHI_AbstractID, 0) > 0 then a.CIHI_AbstractID                                    
                              else a.AbstractID end) 
        from AB_Abstract a 
        join SU_RecordSelect s on a.AbstractID = s.AbstractID and s.ExecutionID = @ExecutionID
    end
    else if (@IsCorrection = 1)

        update SU_RecordSelect 
        set IsSubmited   = 4
        from AB_Abstract a 
        join SU_RecordSelect s on a.AbstractID = s.AbstractID and s.ExecutionID = @ExecutionID
end
-- for InPatient
else if (@SU_Const  = 'DAD_I10_Billing') begin 

    if (@IsCorrection = 0 or @IsResubmit = 1) 
    
        update SU_RecordSelect 
        set IsSubmited     = 1, 
            BatchYear      = @BatchYear, 
            BatchPeriod    = @BatchPeriod, 
            BatchNumber    = (((s.OrderBy - 1) / 100) + @BatchStart), 
            AbstractNumber = (((s.OrderBy - 1) % 100) + 1)
        from AB_Abstract a 
        join SU_RecordSelect s on a.AbstractID = s.AbstractID and s.ExecutionID = @ExecutionID
    
    else if (@IsCorrection = 1)

        update SU_RecordSelect 
        set IsSubmited   = 4
        from AB_Abstract a 
        join SU_RecordSelect s on a.AbstractID = s.AbstractID and s.ExecutionID = @ExecutionID
end
DBCC DBREINDEX (SU_RecordSelect)

select @RecordWidth = sum( TextLength ) from SU_StructureFile where GroupID = @GroupID
select @InstNoCIHI = CIHIValue from H_InstitutionProfile where Code = @InstNoCode

--Hack, How about for BC: Rehab and CCRS
if exists ( select * from H_HospitalProfile where ProvinceNumber <> 14 ) and 
    @BatchPeriod in (15401,15402,15403,15404,15405,15651,15652,15653,
        15654,15655,15656,15657,15658,15659,15660,15661,15662)
    select @BatPerCIHI = CIHIValue from LU_CodeFile where Code = @BatchPeriod
else
    select @BatPerCIHI = CIHIValue from LU_BatchPeriod where Code = @BatchPeriod

select @IsUseMentalHealth = UseMentalHealthData from H_InstitutionProfile where Code = @InstNoCode

-- UPDATE THE EXECUTION PROPERTIES TABLE WITH THE VARIOUS VALUES
update SU_ExecProperties
set ICDType     = @ICDType    ,
    AppID       = @AppID      ,
    RecordCount = @RecordCount,
    BatchStart  = @BatchStart,
    RecordWidth = @RecordWidth,
    ProvNoCIHI  = @ProvNoCIHI ,
    InstNoCIHI  = @InstNoCIHI ,     
    BatPerCIHI  = @BatPerCIHI,
    IsUseMentalHealth = @IsUseMentalHealth,
    NameOfFile  = @NameOfFile,
    SU_Type = @SU_Type
where ExecutionID = @ExecutionID

EXIT_PROCEDURE_NORMAL:
    return 0

ERROR___:
    return 1













GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [SU_RPC_Billing_Terminate]
    @ExecutionID int,
    @IsTerminateWithError int
as
declare @cur cursor 
declare @sql nvarchar(200)

declare @coder int

-- update the Execution Properties table with the completion status.
update SU_ExecProperties 
set TerminateSuccess = case @IsTerminateWithError when 0 then 1 else 0 end
where ExecutionID = @ExecutionID

select @coder = CoderNumber from SU_ExecProperties where ExecutionID = @ExecutionID

--PR - 04063
update AB_Abstract 
--set TSIDate = getdate()
--  , TSITime = getdate()
--  , TSICoder = @coder
set  IsReciprocalBilling = s.IsSubmited
from AB_Abstract a join SU_RecordSelect s on a.AbstractID = s.AbstractID 
where s.ExecutionID = @ExecutionID

Update dbo.AB_ReciprocalBilling
set RPB_BatchNumber    = s.BatchNumber,
    RPB_AbstractNumber = s.AbstractNumber,
    RPB_DateSent = getdate()
from  dbo.AB_ReciprocalBilling b
    inner join SU_RecordSelect s on b.AbstractID = s.AbstractID 
where s.ExecutionID = @ExecutionID


insert into dbo.AB_ReciprocalBilling(AbstractID, RPB_BatchNumber, RPB_AbstractNumber, RPB_DateSent)
select s.AbstractID, RPB_BatchNumber = s.BatchNumber, 
    RPB_AbstractNumber = s.AbstractNumber,  RPB_DateSent = getdate()
from  dbo.AB_ReciprocalBilling b
    right join SU_RecordSelect s on b.AbstractID = s.AbstractID 
where s.ExecutionID = @ExecutionID and b.AbstractID is null

-- After all is said and done, do some basic clean up.
delete from SU_RecordSelect   where ExecutionID = @ExecutionID
delete from SU_QueryStatement where ExecutionID = @ExecutionID


declare @oldExecIDs table ( ExecutionID int )

insert @oldExecIDs ( ExecutionID ) 
select ExecutionID 
from SU_ExecProperties
where datediff( day, ExecutionDate, getdate() ) > 1


delete SU_RecordSelect
from SU_RecordSelect r 
join @oldExecIDs x on r.ExecutionID = x.ExecutionID

delete SU_QueryStatement
from SU_QueryStatement r 
join @oldExecIDs x on r.ExecutionID = x.ExecutionID

delete SU_Record_Submited_OMH_Order
from SU_Record_Submited_OMH_Order r 
join @oldExecIDs x on r.ExecutionID = x.ExecutionID

-- add code for temp table clean up.
-- drops any submission table greater than 1 hour old

set @cur = cursor local fast_forward for
    select sql = N'drop table ' + i.table_name
    from SU_ExecProperties t join (

        select table_name, ExecutionID = cast(substring(table_name, 3, patindex('%[0-9][A-Z]%', table_name)-2) as int)
        from information_schema.tables 
        where table_name like 'SU[0-9]%'
        and isnumeric(substring(table_name, 3, patindex('%[0-9][A-Z]%', table_name)-2)) = 1

    ) i on  t.ExecutionID = i.ExecutionID
    where datediff( hour, ExecutionDate, getdate() ) > 1

open @cur

while (1=1) begin

    fetch next from @cur into @sql
    if (@@fetch_status <> 0) break

    exec sp_executesql @sql
end

close @cur
deallocate @cur


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [SU_TerminateSubmission]
    @ExecutionID int,
    @IsTerminateWithError int
as
declare @cur cursor 
declare @AbstractID int
declare @sql nvarchar(200)
declare @NacrsLevelCode int --NP - 00125
declare @SU_type int --EN -00530
-- purge records flagged as delete and that have been submitted.
declare @AppID int, @GroupID int

-- update the Execution Properties table with the completion status.
update SU_ExecProperties 
set TerminateSuccess = case @IsTerminateWithError when 0 then 1 else 0 end
where ExecutionID = @ExecutionID

select @GroupID = GroupID, @AppID = AppID, @NacrsLevelCode = NacrsLevelCode, @SU_type = SU_type
from SU_ExecProperties 
where ExecutionID = @ExecutionID

-- upon a successful submission file creation, this will 
-- update the appropriate fields in the AB_Abstract table.
if (@IsTerminateWithError = 0) begin

    -- REHAB SUBMISSION
    if exists(select * from SU_ExecProperties where ExecutionID = @ExecutionID and @AppID IN (250, 251, 252)) --GroupID in (20, 21, 22, 23, 121, 122, 123, 221, 222, 223)) 
    begin

        update RH_ClientInfo
        set CIHIDateSent   = s.CIHIDateSent   
          , IsSubmited     = s.IsSubmited     
          , IsCorrected    = s.IsCorrected    
          , IsCompleted    = s.IsCompleted    
          , BatchYear      = s.BatchYear      
          , BatchPeriod    = s.BatchPeriod    
          , AbstractNumber = s.AbstractNumber 
        from RH_ClientInfo a join SU_RecordSelect s on a.AbstractID = s.AbstractID 
        where s.ExecutionID = @ExecutionID


--Change it to 
        if (@GroupID = 20) begin
        
            set @cur = cursor local fast_forward for
                select r.AbstractID 
                from SU_RecordSelect r join RH_ClientInfo a on r.AbstractID = a.AbstractID
                where a.IsDeleted = 1
            
            set @sql = N'exec D_RH_ClientInfo @AbstractID '

            open @cur

            while (1=1) begin
                fetch next from @cur into @AbstractID    
                if (@@fetch_status <> 0) break
                
                exec sp_executesql @sql, N'@AbstractID int', @AbstractID
            end 

            close @cur
            deallocate @cur
        end
        -- PR - 03061
        update ab_main
        set IsCompleted  = s.IsCompleted,
            IsValidated  = s.IsValidated   
        from ab_main a join SU_RecordSelect s on a.AbstractID = s.AbstractID 
        where a.AppID in (250, 251, 252) and s.ExecutionID = @ExecutionID
        
    end -- REHAB

    -- CCRS SUBMISSION
    -- OMIT Group Number 99990470 because it is the master file.  The other Groups will set flags accordingly.
    else 
    -- PR - 01564
    -- if exists(select * from SU_ExecProperties where ExecutionID = @ExecutionID and GroupID in (470, 471, 472, 473, 474, 475, 99990473)) begin 
    --ED - 02710 change to use master ID
    if exists(select * from SU_ExecProperties where ExecutionID = @ExecutionID and GroupID = 99990470)  -- in (470, 471, 472, 473, 474, 475, 476, 477, 1470, 2470, 1472, 1473, 1474, 1476, 1477)) begin --ED - 02385 Exclude, 477 
    begin
        update CRS_Demographic
        set IsSubmited   = s.IsSubmited  
          , IsValidated  = s.IsValidated 
          , IsCompleted  = s.IsCompleted
          , CIHIDateSent = s.CIHIDateSent
          , BatchYear    = s.BatchYear
          , BatchPeriod  = s.BatchPeriod
          , Iscorrected  = (case when a.Iscorrected = 1 then 1 else 3 end)  --ED - 02710
        from CRS_Demographic a join SU_RecordSelect s on a.AbstractID = s.AbstractID 
        where s.ExecutionID = @ExecutionID

        -- PR - 03061
        update ab_main
        set IsCompleted  = s.IsCompleted, 
            IsValidated  = s.IsValidated   
        from ab_main a join SU_RecordSelect s on a.AbstractID = s.AbstractID 
        where a.AppID in (470, 471, 472, 473, 474, 475, 476, 477) and s.ExecutionID = @ExecutionID
        
        --ED - 02990
        Insert into [dbo].[SU_SubmittedHCN](LinkID, AbstractID, HealthCareNumber, AdmitDate)
        select distinct a.linkid, a.AbstractID, a.HealthCareNumber, (case when aa8 = 203626 then a.Z12 else a.AdmitDate end)
        from CRS_Demographic a
            inner join SU_RecordSelect s on a.AbstractID = s.AbstractID 
            left join SU_SubmittedHCN b on a.LinkID = b.LinkID and a.AbstractID = b.AbstractID and a.HealthCareNumber = b.HealthCareNumber
        where s.ExecutionID = @ExecutionID  and isnull(a.HealthCareNumber, '') <> '' and b.LinkID is null and aa8 in (14501, 14510, 203626)

    end -- CCRS SUBMISSION

    -- OMHRS SUBMISSION
    -- OMIT Group Number 99990470 because it is the master file.  The other Groups will set flags accordingly.
    else 
    if exists(select * from SU_ExecProperties where ExecutionID = @ExecutionID and GroupID in (9999650)) begin 
    
        update dbo.OMHRS_RecInfo
        set IsSubmited   = s.IsSubmited  
          , IsValidated  = s.IsValidated 
          , IsCorrected  = (case when a.IsCorrected = 1 then a.IsCorrected else 3 end)
          , IsCompleted  = s.IsCompleted
          , IsDeleted    = s.IsDeleted
          , CIHIDateSent = s.CIHIDateSent
          , BatchYear    = s.BatchYear
          , BatchPeriod  = s.BatchPeriod
        from OMHRS_RecInfo a 
            join SU_RecordSelect s on a.AbstractID = s.AbstractID 
        where s.ExecutionID = @ExecutionID 
    
        -- PR - 03061
        update ab_main
        set IsCompleted    = s.IsCompleted,
            IsValidated    = s.IsValidated   
        from ab_main a join SU_RecordSelect s on a.AbstractID = s.AbstractID 
        where a.AppID in (650, 651, 652, 653, 654) and s.ExecutionID = @ExecutionID
    end -- OMHRS SUBMISSION

    -- IAR OMHRS: Su_Type = 51
    else 
    if @Su_Type = 51 begin 
    
        update dbo.OMHRS_IAR_CCIM
        set IAR_CCIM_IsSubmitted = s.IsSubmited  
          , DateSubmittedToCCIM = (case when a.DateSubmittedToCCIM is null then s.CIHIDateSent else a.DateSubmittedToCCIM end)  
          , IAR_CCIM_IsCorrected  = s.IsCorrected
          , DateCorrectedToCCIM  = (case when s.IsCorrected <> 302161 then s.CIHIDateSent else null end)
        from OMHRS_IAR_CCIM a 
            join SU_RecordSelect s on a.AbstractID = s.AbstractID 
        where s.ExecutionID = @ExecutionID 
    
        
    end -- IAR OMHRS SUBMISSION
    
    -- CJRR 
    else 
    if @AppID in (40000, 40001) begin 
    
        update dbo.CJRR_Abstract
        set IsSubmited   = s.IsSubmited  
          , IsValidated  = s.IsValidated 
          , IsCorrected  = (case when a.IsCorrected = 1 then a.IsCorrected else 3 end)
          , IsCompleted  = s.IsCompleted
          , IsDeleted    = s.IsDeleted
          , CIHIDateSent = s.CIHIDateSent
          --, BatchYear    = s.BatchYear
          --, BatchPeriod  = s.BatchPeriod
        from CJRR_Abstract a 
            join SU_RecordSelect s on a.RecordID = s.AbstractID 
        where s.ExecutionID = @ExecutionID 
    
        update ab_main
        set IsCompleted    = s.IsCompleted,
            IsValidated    = s.IsValidated   
        from ab_main a join SU_RecordSelect s on a.AbstractID = s.AbstractID 
        where a.AppID in (40000, 40001) and s.ExecutionID = @ExecutionID
    end -- CJRR SUBMISSION


    -- NACRS Level 1 --NP - 00125
    else if @AppID = 401 and isnull(@NacrsLevelCode, 3) in (0, 1, 2) begin
        update AB_Abstract 
        set CIHIDateSentLevel1 = s.CIHIDateSent
          , IsSubmitLevel1     = s.IsSubmited
          , IsCorrectLevel1    = s.IsCorrected
          , IsCompleteLevel1   = s.IsCompleted
          --, IsCompleted    = s.IsCompleted
          , BatchYear      = s.BatchYear
          , BatchPeriod    = s.BatchPeriod
          , BatchNumber    = s.BatchNumber
          , AbstractNumber = s.AbstractNumber
          , SubmissionLevel = (case when isnull(a.SubmissionLevel, 0) <> 3 then @NacrsLevelCode else a.SubmissionLevel end)
        from AB_Abstract a join SU_RecordSelect s on a.AbstractID = s.AbstractID 
        where s.ExecutionID = @ExecutionID

	--PR-01550
        update AB_Abstract 
        set CIHI_AbstractID = s.AbstractNumber 
        from AB_Abstract a join SU_RecordSelect s on a.AbstractID = s.AbstractID 
        where s.ExecutionID = @ExecutionID
	        and a.CareType = 5
    	    and isnull(a.CIHI_AbstractID, 0) <= 0 

        -- PR - 06138
        update ab_main
        set IsCompleteLevel1   = s.IsCompleted,
            IsValidLevel1      = s.IsValidated   
        from ab_main a join SU_RecordSelect s on a.AbstractID = s.AbstractID 
        where a.AppType in (1, 2, 5) and s.ExecutionID = @ExecutionID

    end -- NACRS Level 3
    -- REGULAR SUBMISSION
    else if @AppID in (201, 202) or (@AppID = 401 and isnull(@NacrsLevelCode, 3) = 3 and @SU_type <> 22) begin	--Exclude NACRS CJRR
        update AB_Abstract 
        set CIHIDateSent   = s.CIHIDateSent
          , IsSubmited     = s.IsSubmited
          , IsCorrected    = s.IsCorrected
          , IsCompleteLevel1 = s.IsCompleted
          , IsCompleted    = s.IsCompleted
          , BatchYear      = s.BatchYear
          , BatchPeriod    = s.BatchPeriod
          , BatchNumber    = s.BatchNumber
          , AbstractNumber = s.AbstractNumber
          , SubmissionLevel = (case when @AppID = 401 then 3 else 0 end)
        from AB_Abstract a join SU_RecordSelect s on a.AbstractID = s.AbstractID 
        where s.ExecutionID = @ExecutionID

	--PR-01550
        update AB_Abstract 
        set CIHI_AbstractID = s.AbstractNumber 
        from AB_Abstract a join SU_RecordSelect s on a.AbstractID = s.AbstractID 
        where s.ExecutionID = @ExecutionID
	        and a.CareType = 5
	        and s.AbstractNumber < 9000000  --PR - 05128
    	    and (isnull(a.CIHI_AbstractID, 0) <> s.AbstractNumber) --PR - 05128
    	    --and isnull(a.CIHI_AbstractID, 0) <= 0 PR - 05128

        -- PR - 03061
        update ab_main
        set IsCompleted    = s.IsCompleted,
            IsValidated    = s.IsValidated
        from ab_main a join SU_RecordSelect s on a.AbstractID = s.AbstractID 
        where a.AppType in (1, 2, 5) and s.ExecutionID = @ExecutionID

    end -- REGULAR SUBMISSION

end

-- Store history of all records that were processed.
if @GroupID not in (650, 651, 652, 653, 654, 655, 656, 1650, 1651, 1652, 1653, 1654, 2650, 2651, 2652, 2653, 2654, 3650, 3651, 3652, 3653, 3654, 4650, 4651, 4652, 4653, 4654, 5650, 5651, 5652, 5653, 5654)
    insert SU_RecordHistory ([ExecutionID], [AbstractID], [OrderBy], [IsCorrected], [IsSubmited], [IsValidated], [IsCompleted], [IsDeleted], [CIHIDateSent], [BatchYear], [BatchPeriod], [BatchNumber], [AbstractNumber])
	select [ExecutionID], [AbstractID], [OrderBy], [IsCorrected], [IsSubmited], [IsValidated], [IsCompleted], [IsDeleted], [CIHIDateSent], [BatchYear], [BatchPeriod], [BatchNumber], [AbstractNumber]
	from SU_RecordSelect 
	where ExecutionID = @ExecutionID

-- After all is said and done, do some basic clean up.
delete from SU_RecordSelect   where ExecutionID = @ExecutionID
delete from SU_QueryStatement where ExecutionID = @ExecutionID
delete from SU_Record_Submited_OMH_Order where ExecutionID = @ExecutionID


declare @oldExecIDs table ( ExecutionID int )

insert @oldExecIDs ( ExecutionID ) 
select ExecutionID 
from SU_ExecProperties
where datediff( day, ExecutionDate, getdate() ) > 1


delete SU_RecordSelect
from SU_RecordSelect r 
join @oldExecIDs x on r.ExecutionID = x.ExecutionID

delete SU_QueryStatement
from SU_QueryStatement r 
join @oldExecIDs x on r.ExecutionID = x.ExecutionID

delete SU_Record_Submited_OMH_Order
from SU_Record_Submited_OMH_Order r 
join @oldExecIDs x on r.ExecutionID = x.ExecutionID

-- add code for temp table clean up.
-- drops any submission table greater than 1 hour old

set @cur = cursor local fast_forward for
    select sql = N'drop table ' + i.table_name
    from SU_ExecProperties t join (

        select table_name, ExecutionID = cast(substring(table_name, 3, patindex('%[0-9][A-Z]%', table_name)-2) as int)
        from information_schema.tables 
        where table_name like 'SU[0-9]%'
        and isnumeric(substring(table_name, 3, patindex('%[0-9][A-Z]%', table_name)-2)) = 1

    ) i on  t.ExecutionID = i.ExecutionID
    where datediff( hour, ExecutionDate, getdate() ) > 1

open @cur

while (1=1) begin

    fetch next from @cur into @sql
    if (@@fetch_status <> 0) break

    exec sp_executesql @sql
end

close @cur
deallocate @cur


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE  procedure [TEST_ParentChildRelation]
as

declare @selected int
set @selected = 8

declare @searchid int
set @searchid = @selected


declare @tbl table 
(
    patientid int,
    childid int
)

set nocount on

insert @tbl values (01, 02)
insert @tbl values (01, 03)
insert @tbl values (01, 04)

insert @tbl values (02, 05)
insert @tbl values (02, 06)
insert @tbl values (02, 07)

insert @tbl values (03, 08)
insert @tbl values (03, 09)
insert @tbl values (03, 10)
insert @tbl values (03, 20)

insert @tbl values (08, 25)
insert @tbl values (08, 26)
insert @tbl values (08, 27)
insert @tbl values (08, 28)

insert @tbl values (15, 16)

insert @tbl values (16, 17)

insert @tbl values (17, 18)

insert @tbl values (18, 21)
insert @tbl values (18, 22)
insert @tbl values (18, 23)
insert @tbl values (18, 24)

insert @tbl values (19, 14)
insert @tbl values (19, 15)

insert @tbl values (20, 11)
insert @tbl values (20, 12)
insert @tbl values (20, 13)
insert @tbl values (20, 19)


declare @results table 
( 
    orderby int identity(1,1),
    patientid int,
    childid int,
    relation varchar(10)
)

-- find top most ancestor
while exists (select * from @tbl where childid = @searchid) begin
    select @searchid = patientid from @tbl where childid = @searchid
end


insert @results ( patientid, childid, relation )
select 0, @searchid, 'ancestor'

-- insert @results ( patientid, childid )
-- select patientid, childid
-- from @tbl 
-- where patientid = @searchid

-- select descendants
while exists (
    select * 
    from @tbl search
    where exists (
        select * from @results children 
        where childid = search.patientid 
        and not exists (
            select * from @results where patientid = children.childid))
) begin
    insert @results ( patientid, childid )
    select patientid, childid
    from @tbl search
    where exists (
        select * from @results children 
        where childid = search.patientid 
        and not exists (
            select * from @results where patientid = children.childid))
end

-- identify the relationships to the selected patient

-- if exists(select * from @results where childid = @selected) begin

    update @results 
    set relation = 'selected' 
    where childid = @selected

    update @results 
    set relation = 'ancestor' 
    where orderby < (
        select orderby 
        from @results 
        where childid = @selected)
    and orderby <> 1
    
    update @results 
    set relation = 'descendant' 
    where orderby > (
        select orderby
        from @results 
        where childid = @selected)
    
-- end
-- else begin
-- 
--     update @results set relation = 'selected' where orderby = 1
--     update @results set relation = 'descendant' where orderby > 1
-- end


set nocount off

select patientid, childid, relation, orderby
from @results 
order by orderby





GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE     PROCEDURE [TMP_CreatePrototypeDrugsEnglish] AS

-- Author: Brenda Vargas : Jan 24, 2007
-- Latest Change: 	   Feb 1, 2007
-- Creates new table  NU_DrugsLast  to be used by Drugs Prototype 
-- Pending:
	-- Change Name of tmp_DrugsLast Table when definitive
	-- Change it in TMP_LookUpDrugs_B as well 

-- Update:
	--- Changed tmp_DrugsLast Table for NU_DrugsLast 
	
--NU_Drugs /  tmp_Drugs
declare @autoid as integer
declare @headerid integer
declare @SubHeaderId integer
declare	@SubHeaderId1 integer
declare	@SubHeaderId2 integer
declare	@SubHeaderId3 integer
declare @headerdesc varchar(255)
declare @headersearch varchar(255)
declare	@Chapter_XIX varchar (15)
declare	@Accidental varchar (15)
declare	@Intentional_Self_Harm varchar (15)
declare @Undetermined_Intent varchar (15)
declare	@Adverse_effect_in_therapeutic_use varchar (15)


declare @pt int
declare @strtmp  varchar(500)

declare @counter integer
declare @id integer
declare @itmp int

declare @tmplink1 varchar (15)
declare @tmplink2 varchar (15)
declare @tmplink3 varchar (15)
declare @tmplink4 varchar (15)

declare @tempoautoid as integer
declare @tempoheaderid integer
declare @tempoSubHeaderId integer
declare @tempoSubHeaderId1 integer
declare @tempoSubHeaderId2 integer
declare @tempoSubHeaderId3 integer
declare	@tempoChapter_XIX varchar (15)
declare	@tempoAccidental varchar (15)


CREATE TABLE tmp_Drugs (
	[AutoId] [int] NOT NULL ,
	[HeaderId] [int] NULL ,
	[SubHeaderId] [int] NULL ,
	[SubHeaderId1] [int] NULL ,
	[SubHeaderId2] [int] NULL ,
	[SubHeaderId3] [int] NULL ,
	[HeaderDesc] [varchar] (255)COLLATE Latin1_General_CI_AS NULL,
	[HeaderSearch] [varchar] (255) COLLATE Latin1_General_CI_AS NULL ,
	[Chapter_XIX] [varchar] (15) COLLATE Latin1_General_CI_AS NULL,
	[Accidental] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Intentional_Self_Harm] [varchar] (15) COLLATE Latin1_General_CI_AS NULL,
        [Undetermined_Intent] [varchar] (15) COLLATE Latin1_General_CI_AS NULL,
	[Adverse_effect_in_therapeutic_use] [varchar] (15) COLLATE Latin1_General_CI_AS NULL
	
) ON [PRIMARY]

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Nu_DrugsLast]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Nu_DrugsLast]


CREATE TABLE NU_DrugsLast (
	[AutoId] [int] NOT NULL ,
	[HeaderId] [int] NULL ,
	[SubHeaderId] [int] NULL ,
	[SubHeaderId1] [int] NULL ,
	[SubHeaderId2] [int] NULL ,
	[SubHeaderId3] [int] NULL ,
	[HeaderDesc] [varchar] (255) COLLATE Latin1_General_CI_AS NULL,
	[HeaderSearch] [varchar] (255) COLLATE Latin1_General_CI_AS NULL ,
	[Chapter_XIX] [varchar] (15) COLLATE Latin1_General_CI_AS NULL,
	[Accidental] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Intentional_Self_Harm] [varchar] (15) COLLATE Latin1_General_CI_AS NULL,
        [Undetermined_Intent] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Adverse_effect_in_therapeutic_use] [varchar] (15)COLLATE Latin1_General_CI_AS NULL
	
) ON [PRIMARY]


-- COLUMN Chapter XIX
INSERT INTO tmp_Drugs (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Chapter_XIX )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, codelink 
from NU_Drugs  where headerdesc like '%Chapter XIX%' 

-- COLUMN Accidental
INSERT INTO tmp_Drugs (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Accidental )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, codelink 
from NU_Drugs  where headerdesc like '%Accidental%'

-- COLUMN Intentional 
INSERT INTO tmp_Drugs (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Intentional_Self_Harm )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, codelink 
from NU_Drugs  where headerdesc like '%Intentional%'

-- COLUMN Undetermined 
INSERT INTO tmp_Drugs (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Undetermined_Intent )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, codelink 
from NU_Drugs  where headerdesc like '%Undetermined%'

-- COLUMN Adverse effect 
INSERT INTO tmp_Drugs (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Adverse_effect_in_therapeutic_use )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, codelink 
from NU_Drugs  where headerdesc like '%Adverse effect%'

------------------------------------- LEAVING JUST ONE ROW FOR HEADER IN NU_DrugsLast 
-- COLUMN Charter XIX
INSERT INTO NU_DrugsLast  (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Chapter_XIX )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Chapter_XIX from tmp_drugs  where Chapter_XIX is not null 

-- OTHERS COLUMNS 
declare cursor_NU_DrugsLast CURSOR FOR
select * from NU_DrugsLast  
open cursor_Nu_DrugsLast

FETCH NEXT FROM cursor_NU_DrugsLast 
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @HeaderDesc, @HeaderSearch, @Chapter_XIX, @Accidental, @Intentional_Self_Harm, @Undetermined_Intent, @Adverse_effect_in_therapeutic_use


-- LEAVING JUST ONE ROW FOR HEADER
WHILE @@FETCH_STATUS = 0
BEGIN
	set @tmplink1 = null
	set @tmplink2 = null
	set @tmplink3 = null
	set @tmplink4 = null

       	select @tmplink1= Accidental from tmp_drugs 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and Accidental is not null
	select @tmplink2= Intentional_Self_Harm from tmp_drugs 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and Intentional_Self_Harm is not null
	select @tmplink3= Undetermined_Intent from tmp_drugs 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and Undetermined_Intent is not null
	select @tmplink4= Adverse_effect_in_therapeutic_use from tmp_drugs 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and Adverse_effect_in_therapeutic_use is not null


	UPDATE Nu_DrugsLast
		SET Accidental = @tmplink1,
		Intentional_Self_Harm = @tmplink2,
		Undetermined_Intent = @tmplink3,
		Adverse_effect_in_therapeutic_use = @tmplink4
		WHERE   headerid     =  @headerid and 
			subheaderid  = @subheaderid and  
			subheaderid1 = @Subheaderid1 and
			subheaderid2 = @Subheaderid2 and
			subheaderid3 = @Subheaderid3
	
FETCH NEXT FROM cursor_Nu_DrugsLast
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @HeaderDesc, @HeaderSearch, @Chapter_XIX, @Accidental, @Intentional_Self_Harm, @Undetermined_Intent, @Adverse_effect_in_therapeutic_use

END


CLOSE cursor_Nu_DrugsLast
DEALLOCATE cursor_Nu_DrugsLast


-- FIXING DUPLICATE ROWS 
select * into tempo_drugslast from NU_DrugsLast --: created backup table 

--INSERT INTO NU_DrugsLast select *  from tempo_drugslast  

declare @count as integer

declare cur_NU_DrugsLast CURSOR FOR
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, Chapter_XIX, Accidental
	 from NU_DrugsLast order by autoid
open cur_Nu_DrugsLast

FETCH NEXT FROM cur_NU_DrugsLast 
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @Chapter_XIX, @Accidental

WHILE @@FETCH_STATUS = 0
BEGIN
	-- Inner cursor
	declare cur_tempo CURSOR FOR
	select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, Chapter_XIX, Accidental from tempo_drugslast   
	WHERE 	headerid = @headerid and subheaderid = @subheaderid and SubHeaderId1 = @SubHeaderId1 and SubHeaderId2 = @SubHeaderId2 
		and  SubHeaderId3 = @SubHeaderId3

	open cur_tempo

	set @count = 0 
	
	FETCH NEXT FROM cur_tempo 
	INTO @tempoautoid, @tempoheaderid, @tempoSubHeaderId, @tempoSubHeaderId1, @tempoSubHeaderId2, @tempoSubHeaderId3, @tempoChapter_XIX, @tempoAccidental
	
	WHILE @@FETCH_STATUS = 0
	BEGIN
		--PRINT @COUNT 
		set @count = @count + 1
	 
		if @count = 2  
		begin 
			-- Update first row of the Nu_DrugsLast
			
			UPDATE NU_DrugsLast SET Accidental = @tempoChapter_XIX
			WHERE   headerid = @headerid and 
				subheaderid = @subheaderid and 
				SubHeaderId1 = @SubHeaderId1 and 
				SubHeaderId2 = @SubHeaderId2 and
				SubHeaderId3 = @SubHeaderId3 and 
				autoid = @autoid

			-- Delete second row of the Nu_DrugsLast
			
			DELETE NU_DrugsLast 
			WHERE 	headerid = @headerid and 
				subheaderid  = @subheaderid anD 
				subheaderid1 = @Subheaderid1 and 
				SubHeaderId2 = @SubHeaderId2 and
				SubHeaderId3 = @SubHeaderId3 and 
				autoid = @tempoautoid 
                   
		end

	        FETCH NEXT FROM cur_tempo
	INTO @tempoautoid, @tempoheaderid, @tempoSubHeaderId, @tempoSubHeaderId1, @tempoSubHeaderId2, @tempoSubHeaderId3, @tempoChapter_XIX, @tempoAccidental	

			
	END
	CLOSE cur_tempo
	DEALLOCATE cur_tempo
	
FETCH NEXT FROM cur_Nu_DrugsLast
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @Chapter_XIX, @Accidental

END


CLOSE cur_Nu_DrugsLast
DEALLOCATE cur_Nu_DrugsLast

-- Remove words "Chapter XIX" at the end --

--select ltrim(rtrim(substring(headersearch,1,len(headersearch)- 21))), headersearch, headerdesc
-- from NU_DrugsLast where headersearch like '%Chapter XIX%' 


UPDATE Nu_DrugsLast
		SET headerdesc = rtrim(substring(headerdesc,1,len(headerdesc)- 21)),
		  headersearch = rtrim(substring(headersearch,1,len(headersearch)- 21))
		WHERE  headerdesc like '%Chapter XIX%' 



-- CODELINK = ''  dejar de ultimo
INSERT INTO NU_DrugsLast (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch)
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch 
from NU_Drugs  where codelink = ''


drop table tmp_Drugs
drop table tempo_drugslast




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE    PROCEDURE [TMP_CreatePrototypeDrugsFrench] AS

-- Author: Brenda Vargas : Jan 24, 2007
-- Latest change:	   Feb 1, 2007
-- Creates new table  Nu_DrugsFrLast  to be used by Drugs Prototype 
-- Pending:
	-- Change Name of tmp_DrugsFrLast Table when definitive
	-- Change it on TMP_LookUpDrugs_B
-- Modified Aug 22, 2007
	-- Changed tmp_DrugsFrLast Table to Nu_DrugsFrLast
	

--NU_DrugsFr /  tmp_DrugsFr / Nu_DrugsFrLast

declare @autoid as integer
declare @headerid integer
declare @SubHeaderId integer
declare	@SubHeaderId1 integer
declare	@SubHeaderId2 integer
declare	@SubHeaderId3 integer
declare @headerdesc varchar(255)
declare @headersearch varchar(255)
declare	@Chapter_XIX varchar (15)
declare	@Accidental varchar (15)
declare	@Intentional_Self_Harm varchar (15)
declare @Undetermined_Intent varchar (15)
declare	@Adverse_effect_in_therapeutic_use varchar (15)

declare @pt int
declare @strtmp  varchar(500)

declare @counter integer
declare @id integer
declare @itmp int

declare @tmplink1 varchar (15)
declare @tmplink2 varchar (15)
declare @tmplink3 varchar (15)
declare @tmplink4 varchar (15)

declare @tempoautoid as integer
declare @tempoheaderid integer
declare @tempoSubHeaderId integer
declare @tempoSubHeaderId1 integer
declare @tempoSubHeaderId2 integer
declare @tempoSubHeaderId3 integer
declare	@tempoChapter_XIX varchar (15)
declare	@tempoAccidental varchar (15)


CREATE TABLE tmp_DrugsFr (
	[AutoId] [int] NOT NULL ,
	[HeaderId] [int] NULL ,
	[SubHeaderId] [int] NULL ,
	[SubHeaderId1] [int] NULL ,
	[SubHeaderId2] [int] NULL ,
	[SubHeaderId3] [int] NULL ,
	[HeaderDesc] [varchar] (255)COLLATE Latin1_General_CI_AS NULL,
	[HeaderSearch] [varchar] (255) COLLATE Latin1_General_CI_AS NULL ,
	[Chapter_XIX] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Accidental] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Intentional_Self_Harm] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
        [Undetermined_Intent] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Adverse_effect_in_therapeutic_use] [varchar] (15) COLLATE Latin1_General_CI_AS NULL
	
) ON [PRIMARY]

drop table Nu_DrugsFrLast 

CREATE TABLE Nu_DrugsFrLast (
	[AutoId] [int] NOT NULL ,
	[HeaderId] [int] NULL ,
	[SubHeaderId] [int] NULL ,
	[SubHeaderId1] [int] NULL ,
	[SubHeaderId2] [int] NULL ,
	[SubHeaderId3] [int] NULL ,
	[HeaderDesc] [varchar] (255) COLLATE Latin1_General_CI_AS NULL,
	[HeaderSearch] [varchar] (255)COLLATE Latin1_General_CI_AS NULL ,
	[Chapter_XIX] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Accidental] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Intentional_Self_Harm] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
        [Undetermined_Intent] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Adverse_effect_in_therapeutic_use] [varchar] (15)COLLATE Latin1_General_CI_AS NULL
	
) ON [PRIMARY]

-- IMPORTANT!!!!!!         For FRENCH I'LL USE HEADERSEARCH INSTEAD OF HEADERDESC (Because of accent) 

-- COLUMN Chapitre XIX
INSERT INTO tmp_DrugsFr (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Chapter_XIX )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, codelink 
from NU_DrugsFr  where headersearch like '%Chapitre XIX%' 

-- COLUMN Accidentel
INSERT INTO tmp_DrugsFr (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Accidental )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, codelink 
from NU_DrugsFr  where headersearch like '%Accidentel%'

-- COLUMN Intentionnel auto-induit
INSERT INTO tmp_DrugsFr (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Intentional_Self_Harm )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, codelink 
from NU_DrugsFr  where headersearch like '%Intentionnel auto-induit%'

-- COLUMN Intention non-determinee
INSERT INTO tmp_DrugsFr (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Undetermined_Intent )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, codelink 
from NU_DrugsFr  where  headersearch like  '%Intention non-determinee%'

-- COLUMN Effet indesirable en usage therapeutique
INSERT INTO tmp_DrugsFr (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Adverse_effect_in_therapeutic_use )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, codelink 
from NU_DrugsFr  where headersearch like '%indesirable en usage therapeutique%'

------------------------------------- LEAVING JUST ONE ROW FOR HEADER IN Nu_DrugsFrLast 
-- COLUMN Charter XIX
INSERT INTO Nu_DrugsFrLast  (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Chapter_XIX )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Chapter_XIX from tmp_DrugsFr  where Chapter_XIX is not null 

-- OTHERS COLUMNS 
declare cursor_Nu_DrugsFrLast CURSOR FOR
select * from Nu_DrugsFrLast  
open cursor_Nu_DrugsFrLast

FETCH NEXT FROM cursor_Nu_DrugsFrLast 
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @HeaderDesc, @HeaderSearch, @Chapter_XIX, @Accidental, @Intentional_Self_Harm, @Undetermined_Intent, @Adverse_effect_in_therapeutic_use


-- LEAVING JUST ONE ROW FOR HEADER
WHILE @@FETCH_STATUS = 0
BEGIN
	set @tmplink1 = null
	set @tmplink2 = null
	set @tmplink3 = null
	set @tmplink4 = null

       	select @tmplink1= Accidental from tmp_DrugsFr 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and Accidental is not null
	select @tmplink2= Intentional_Self_Harm from tmp_DrugsFr 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and Intentional_Self_Harm is not null
	select @tmplink3= Undetermined_Intent from tmp_DrugsFr 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and Undetermined_Intent is not null
	select @tmplink4= Adverse_effect_in_therapeutic_use from tmp_DrugsFr 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and Adverse_effect_in_therapeutic_use is not null


	UPDATE Nu_DrugsFrLast
		SET Accidental = @tmplink1,
		Intentional_Self_Harm = @tmplink2,
		Undetermined_Intent = @tmplink3,
		Adverse_effect_in_therapeutic_use = @tmplink4
		WHERE   headerid     =  @headerid and 
			subheaderid  = @subheaderid and  -- Jan 22
			subheaderid1 = @Subheaderid1 and
			subheaderid2 = @Subheaderid2 and
			subheaderid3 = @Subheaderid3
	
FETCH NEXT FROM cursor_Nu_DrugsFrLast
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @HeaderDesc, @HeaderSearch, @Chapter_XIX, @Accidental, @Intentional_Self_Harm, @Undetermined_Intent, @Adverse_effect_in_therapeutic_use

END


CLOSE cursor_Nu_DrugsFrLast
DEALLOCATE cursor_Nu_DrugsFrLast


-- CODELINK = ''  dejar de ultimo
INSERT INTO Nu_DrugsFrLast (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch)
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch 
from NU_DrugsFr  where codelink = ''

  
-- FIXING DUPLICATE ROWS 
select * into tempo_drugsFrlast from Nu_DrugsFrLast --: created backup table 

--INSERT INTO Nu_DrugsFrLast select *  from tempo_drugsfrlast  
--Drop table tempo_drugsFrlast

delete Nu_DrugsFrLast

declare @myAutoid as integer

declare cur_tempo_DrugsFrlast CURSOR FOR
select *  from tempo_DrugsFrlast order by autoid
open cur_tempo_DrugsFrlast


FETCH NEXT FROM cur_tempo_DrugsFrlast 
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @HeaderDesc, @HeaderSearch, @Chapter_XIX, @Accidental,  @Intentional_Self_Harm, @Undetermined_Intent, @Adverse_effect_in_therapeutic_use

set @myAutoid = 0

WHILE @@FETCH_STATUS = 0
BEGIN
	
	if @myAutoid <> @Autoid
	begin 
	  -- Insert only the first row found
	  INSERT INTO Nu_DrugsFrLast  (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, HeaderDesc, HeaderSearch, Chapter_XIX, Accidental,  Intentional_Self_Harm, Undetermined_Intent, Adverse_effect_in_therapeutic_use )
	  VALUES  (@Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @HeaderDesc, @HeaderSearch, @Chapter_XIX, @Accidental,  @Intentional_Self_Harm, @Undetermined_Intent, @Adverse_effect_in_therapeutic_use )
	
	  set @myAutoid = @Autoid
	          
	end
	        
	FETCH NEXT FROM cur_tempo_DrugsFrlast
        INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @HeaderDesc, @HeaderSearch, @Chapter_XIX, @Accidental,  @Intentional_Self_Harm, @Undetermined_Intent, @Adverse_effect_in_therapeutic_use


END

CLOSE cur_tempo_DrugsFrlast
DEALLOCATE cur_tempo_DrugsFrlast

-- Remove words "Empoisonnement Chapitre XIX codelink" at the end --

--select ltrim(rtrim(substring(headersearch,1,len(headersearch)- 21))), headersearch, headerdesc
-- from Nu_DrugsFrLast where headersearch like '%Poisoning Chapter XIX' 


UPDATE Nu_DrugsFrLast
		SET headerdesc = rtrim(substring(headerdesc,1,len(headerdesc)- (Len(Chapter_XiX)+29))),
		  headersearch = rtrim(substring(headersearch,1,len(headersearch)- (Len(Chapter_XiX)+29)))
		WHERE  headerdesc like '%Empoisonnement Chapitre XIX%' 



drop table tmp_DrugsFr
drop table tempo_DrugsFrLast



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE                                           PROCEDURE [TMP_CreatePrototypeNeoplasmEnglish] AS

-- Author: Brenda Vargas : Jan 26, 2007
-- Latest change: 	   Feb 1, 2007
-- Creates new table  tmp_NeoplasmLast  to be used by Neoplasm Prototype 
-- Pending:
	-- Change Name of tmp_NeoplasmLast Table when definitive
	-- Change it on TMP_LookUpNeoplasm_B

-- Important !!!!! Jan 31:   
-- This sp will run taking WR284_NU_Neoplasm table from WinRecs 2.8.4 - The current NU_Neoplasm is out of alignment 
-- I will replace NU_Neoplasm for WR284_NU_Neoplasm

-- Important !!!!  Feb 12:
-- I'm using NU_NeoplasmTmp table :this is New Simon parsed table from NFO
-- I'll replace WR284_NU_Neoplasm for NU_NeoplasmTmp

-- Important !!!!  Feb 13:
-- I'm using NU_NeoplasmNewEn table :this is New Simon parsed table from NFO
-- I'll replace NU_NeoplasmTmp for NU_NeoplasmNewEn
-- Namiul August 03:
-- The NU_NeoplasmNewEn no longer exists with new Parse of English Tables [August 03, 2007] Replacing NU_NeoplasmNewEn with NU_Neoplasm
-- Add subheader4 in NU_Neoplasm if it does not exists

-- bv Aug 21, 2007:
-- Changed tmp_NeoplasmLast Table to Nu_NeoplasmLast


-- NU_Neoplasm/  tmp_Neoplasm /NU_NeoplasmLast
declare @autoid as integer
declare @headerid integer
declare @SubHeaderId integer
declare	@SubHeaderId1 integer
declare	@SubHeaderId2 integer
declare	@SubHeaderId3 integer
declare	@SubHeaderId4 integer
declare @headerdesc varchar(255)
declare @headersearch varchar(255)
declare	@Malignant_Primary varchar (15)
declare	@Malignant_Secondary varchar (15)
declare	@In_Situ varchar (15)
declare @Benign varchar (15)
declare	@Uncertain_or_Unknown_Behaviour varchar (15)

declare @pt int
declare @strtmp  varchar(500)

declare @counter integer
declare @id integer
declare @itmp int

declare @tmplink1 varchar (15)
declare @tmplink2 varchar (15)
declare @tmplink3 varchar (15)
declare @tmplink4 varchar (15)

declare @tempoautoid as integer
declare @tempoheaderid integer
declare @tempoSubHeaderId integer
declare @tempoSubHeaderId1 integer
declare @tempoSubHeaderId2 integer
declare @tempoSubHeaderId3 integer
declare	@tempoMalignant_Primary varchar (15)
declare	@tempoMalignant_Secondary varchar (15)


CREATE TABLE tmp_Neoplasm (
	[AutoId] [int] NOT NULL ,
	[HeaderId] [int] NULL ,
	[SubHeaderId] [int] NULL ,
	[SubHeaderId1] [int] NULL ,
	[SubHeaderId2] [int] NULL ,
	[SubHeaderId3] [int] NULL ,
	[SubHeaderId4] [int] NULL ,
	[HeaderDesc] [varchar] (255) COLLATE Latin1_General_CI_AS NULL,
	[HeaderSearch] [varchar] (255)COLLATE Latin1_General_CI_AS NULL ,
	[Malignant_Primary] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Malignant_Secondary] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[In_Situ] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
        [Benign] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Uncertain_or_Unknown_Behaviour] [varchar] (15)COLLATE Latin1_General_CI_AS NULL
	
) ON [Primary]

---Namiul
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[NU_NeoplasmLast]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[NU_NeoplasmLast]

----Namiul
if not exists (select * from dbo.syscolumns where [name] like 'SubHeaderId4' AND  id = object_id(N'[dbo].[NU_Neoplasm]') and OBJECTPROPERTY(id, N'IsUserTable') = 1 ) AND 
(exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[NU_Neoplasm]') and OBJECTPROPERTY(id, N'IsUserTable') = 1))  
	ALTER TABLE NU_Neoplasm ADD  [SubHeaderId4] [int] NOT NULL  DEFAULT (0)



CREATE TABLE NU_NeoplasmLast (
	[AutoId] [int] NOT NULL ,
	[HeaderId] [int] NULL ,
	[SubHeaderId] [int] NULL ,
	[SubHeaderId1] [int] NULL ,
	[SubHeaderId2] [int] NULL ,
	[SubHeaderId3] [int] NULL ,
	[SubHeaderId4] [int] NULL ,
	[HeaderDesc] [varchar] (255) COLLATE Latin1_General_CI_AS NULL,
	[HeaderSearch] [varchar] (255)COLLATE Latin1_General_CI_AS NULL ,
	[Malignant_Primary] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Malignant_Secondary] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[In_Situ] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
        [Benign] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Uncertain_or_Unknown_Behaviour] [varchar] (15)COLLATE Latin1_General_CI_AS NULL
	
) ON [Primary]


-- COLUMN Malignant_Primary
INSERT INTO tmp_Neoplasm (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Malignant_Primary )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, codelink 
from NU_Neoplasm where headerdesc like '%Primary%' 

-- COLUMN Malignant_Secondary
INSERT INTO tmp_Neoplasm (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Malignant_Secondary )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, codelink 
from NU_Neoplasm where headerdesc like '%Secondary%'

-- COLUMN In situ
INSERT INTO tmp_Neoplasm (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, In_Situ )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, codelink 
from NU_Neoplasm where headerdesc like '%In situ%'

-- COLUMN Benign
INSERT INTO tmp_Neoplasm (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Benign )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, codelink 
from NU_Neoplasm where headerdesc like '%Benign%'

-- COLUMN Uncertain or unknown behaviour
INSERT INTO tmp_Neoplasm (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Uncertain_or_Unknown_Behaviour )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, codelink 
from NU_Neoplasm where headerdesc like '%Uncertain Or Unknown%'

------------------------------------- LEAVING JUST ONE ROW FOR HEADER IN NU_NeoplasmLast 
-- COLUMN Malignant_Primary
INSERT INTO NU_NeoplasmLast  (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Malignant_Primary )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Malignant_Primary from tmp_Neoplasm  where Malignant_Primary is not null 

-- OTHERS COLUMNS 
declare cursor_NU_NeoplasmLast CURSOR FOR
select * from NU_NeoplasmLast  
open cursor_NU_NeoplasmLast

FETCH NEXT FROM cursor_NU_NeoplasmLast 
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @SubHeaderId4, @HeaderDesc, @HeaderSearch, @Malignant_Primary, @Malignant_Secondary, @In_Situ, @Benign, @Uncertain_or_Unknown_Behaviour


-- LEAVING JUST ONE ROW FOR HEADER
WHILE @@FETCH_STATUS = 0
BEGIN
	set @tmplink1 = null
	set @tmplink2 = null
	set @tmplink3 = null
	set @tmplink4 = null

       	select @tmplink1= Malignant_Secondary from tmp_Neoplasm 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and subheaderid4 = @subheaderid4
				and Malignant_Secondary is not null
	select @tmplink2= In_Situ from tmp_Neoplasm 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and subheaderid4 = @subheaderid4
				and In_Situ is not null
	select @tmplink3= Benign from tmp_Neoplasm 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and subheaderid4 = @subheaderid4
				and Benign is not null
	select @tmplink4= Uncertain_or_Unknown_Behaviour from tmp_Neoplasm 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and subheaderid4 = @subheaderid4
				and Uncertain_or_Unknown_Behaviour is not null


	UPDATE NU_NeoplasmLast
		SET Malignant_Secondary = @tmplink1,
		In_Situ = @tmplink2,
		Benign = @tmplink3,
		Uncertain_or_Unknown_Behaviour = @tmplink4
		WHERE   Autoid 	     = @Autoid and 
			headerid     = @headerid and 
			subheaderid  = @subheaderid and
			subheaderid1 = @Subheaderid1 and
			subheaderid2 = @Subheaderid2 and
			subheaderid3 = @Subheaderid3 and
			subheaderid4 = @subheaderid4
	
FETCH NEXT FROM cursor_NU_NeoplasmLast
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @SubHeaderId4, @HeaderDesc, @HeaderSearch, @Malignant_Primary, @Malignant_Secondary, @In_Situ, @Benign, @Uncertain_or_Unknown_Behaviour

END

CLOSE cursor_NU_NeoplasmLast
DEALLOCATE cursor_NU_NeoplasmLast


-- Remove words "Malignes Primitives codelinks" at the end --

UPDATE NU_NeoplasmLast
		SET headerdesc = rtrim(substring(Headerdesc,1,CHARINDEX('Malignant Primary', headerdesc, 1)-1 )),
		    headersearch = rtrim(substring(headerSearch,1,CHARINDEX('Malignant Primary', headerSearch, 1)-1 ))		WHERE  headerdesc like '%Malignant Primary%' 


-- Do not execute this part.  It's not necesary after latest Simon parse 
-- CODELINK = ''  leave at the end
--INSERT INTO tmp_NeoplasmFrLAST (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4,
--HeaderDesc, HeaderSearch)
--select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch 
--from NU_NeoplasmLastFr  where codelink = ''


UPDATE NU_NeoplasmLast SET  Malignant_Primary = null  WHERE Malignant_Primary = ''  


-- Replace character "|" for "-" resolve problem in VB
UPDATE NU_NeoplasmLast SET headerdesc=replace(headerdesc,char(150),char(45)) 



-- Original when use NU_Neoplam
--UPDATE NU_NeoplasmLast
--		SET headerdesc = rtrim(substring(headerdesc,1,len(headerdesc)- (Len(Malignant_Primary)+18))), 
--		    headersearch =' ' +  rtrim(substring(headersearch,1,len(headersearch)- (Len(Malignant_Primary)+19)))
--		WHERE  headerdesc like '%Malignant Primary%' 


-- To run with WR284 table 
------------------- Commented for now. Feb 12, 2007
--UPDATE NU_NeoplasmLast
--		SET headerdesc = rtrim(substring(headerdesc,1,len(headerdesc)- (Len(Malignant_Primary)+19))), 
--		    headersearch = rtrim(substring(headersearch,1,len(headersearch)- (Len(Malignant_Primary)+21)))
--		WHERE  headerdesc like '%Malignant Primary%' 


-- add space to last codes inserted  Important!!!! Not necessary when run with WinRecs284 Table 
--UPDATE NU_NeoplasmLast
--SET   headersearch= ' ' +  headersearch
-- where malignant_Primary is null


-- Drop tables
drop table tmp_Neoplasm






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO










CREATE                                             PROCEDURE [TMP_CreatePrototypeNeoplasmFrench] AS

-- Author: Brenda Vargas : Jan 29, 2007
-- Latest change: 	 : Feb 1, 2007
-- Creates new table  tmp_NeoplasmFrLast  to be used by Neoplasm Prototype 
-- Pending:
	-- Change Name of tmp_NeoplasmFrLast Table when definitive
	-- Change it on TMP_LookUpNeoplasm_B as well
-- Important I'm using NU_NeoplasmLastFr table :this is New Simon parsed table
-- (ORIGINAL TABLE IS NU_NeoplasmFrTmp Feb 8, 2007). I replace NU_NeoplasmFr for 
-- NU_NeoplasmLastFr
	

-- NU_NeoplasmLastFr /  tmp_NeoplasmFr /tmp_NeoplasmFrLast
declare @autoid as integer
declare @headerid integer
declare @SubHeaderId integer
declare	@SubHeaderId1 integer
declare	@SubHeaderId2 integer
declare	@SubHeaderId3 integer
declare	@SubHeaderId4 integer
declare @headerdesc varchar(255)
declare @headersearch varchar(255)
declare	@Malignant_Primary varchar (15)
declare	@Malignant_Secondary varchar (15)
declare	@In_Situ varchar (15)
declare @Benign varchar (15)
declare	@Uncertain_or_Unknown_Behaviour varchar (15)

declare @pt int
declare @strtmp  varchar(500)

declare @counter integer
declare @id integer
declare @itmp int

declare @tmplink1 varchar (15)
declare @tmplink2 varchar (15)
declare @tmplink3 varchar (15)
declare @tmplink4 varchar (15)

declare @tempoautoid as integer
declare @tempoheaderid integer
declare @tempoSubHeaderId integer
declare @tempoSubHeaderId1 integer
declare @tempoSubHeaderId2 integer
declare @tempoSubHeaderId3 integer
declare	@tempoMalignant_Primary varchar (15)
declare	@tempoMalignant_Secondary varchar (15)


CREATE TABLE tmp_NeoplasmFr (
	[AutoId] [int] NOT NULL ,
	[HeaderId] [int] NULL ,
	[SubHeaderId] [int] NULL ,
	[SubHeaderId1] [int] NULL ,
	[SubHeaderId2] [int] NULL ,
	[SubHeaderId3] [int] NULL ,
        [SubHeaderId4] [int] NULL ,
	[HeaderDesc] [varchar] (255) COLLATE Latin1_General_CI_AS NULL,
	[HeaderSearch] [varchar] (255)COLLATE Latin1_General_CI_AS NULL ,
	[Malignant_Primary] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Malignant_Secondary] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[In_Situ] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
        [Benign] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Uncertain_or_Unknown_Behaviour] [varchar] (15)COLLATE Latin1_General_CI_AS NULL
) ON [Primary]

drop table tmp_NeoplasmFrLast

CREATE TABLE tmp_NeoplasmFrLast (
	[AutoId] [int] NOT NULL ,
	[HeaderId] [int] NULL ,
	[SubHeaderId] [int] NULL ,
	[SubHeaderId1] [int] NULL ,
	[SubHeaderId2] [int] NULL ,
	[SubHeaderId3] [int] NULL ,
	[SubHeaderId4] [int] NULL ,
        [HeaderDesc] [varchar] (255) COLLATE Latin1_General_CI_AS NULL,
	[HeaderSearch] [varchar] (255)COLLATE Latin1_General_CI_AS NULL ,
	[Malignant_Primary] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Malignant_Secondary] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[In_Situ] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
        [Benign] [varchar] (15)COLLATE Latin1_General_CI_AS NULL,
	[Uncertain_or_Unknown_Behaviour] [varchar] (15)COLLATE Latin1_General_CI_AS NULL
) ON [Primary]

-- IMPORTANT!!!!!!         For FRENCH I'LL BE USING HEADERSEARCH INSTEAD OF HEADERDESC (Because of accent) 

-- COLUMN Malignant_Primary
INSERT INTO tmp_NeoplasmFr (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Malignant_Primary )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3,SubHeaderId4,  HeaderDesc, HeaderSearch, codelink 
from NU_NeoplasmLastFr  where headersearch like '%Primitives%' 

-- COLUMN Malignant_Secondary
INSERT INTO tmp_NeoplasmFr (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Malignant_Secondary )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, codelink 
from NU_NeoplasmLastFr  where headersearch like '%Secondaires%'

-- COLUMN In situ
INSERT INTO tmp_NeoplasmFr (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, In_Situ )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3,SubHeaderId4,  HeaderDesc, HeaderSearch, codelink 
from NU_NeoplasmLastFr  where headersearch like '%In situ%'

-- COLUMN Benign
INSERT INTO tmp_NeoplasmFr (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Benign )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, codelink 
from NU_NeoplasmLastFr  where headersearch like '%Benignes%'

-- COLUMN Uncertain or unknown behaviour
INSERT INTO tmp_NeoplasmFr (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Uncertain_or_Unknown_Behaviour )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, codelink 
from NU_NeoplasmLastFr  where headersearch like '%evolution imprevisible ou inconnue%'

------------------------------------- LEAVING JUST ONE ROW FOR HEADER IN tmp_NeoplasmFrlast 
-- COLUMN Malignant_Primary
INSERT INTO tmp_NeoplasmFrlast  (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Malignant_Primary )
select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch, Malignant_Primary from tmp_NeoplasmFr  where Malignant_Primary is not null 

-- OTHERS COLUMNS 

declare cursor_tmp_NeoplasmFrlast CURSOR FOR
select * from tmp_NeoplasmFrlast  
open cursor_tmp_NeoplasmFrlast

FETCH NEXT FROM cursor_tmp_NeoplasmFrlast 
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @SubHeaderId4, @HeaderDesc, @HeaderSearch, @Malignant_Primary, @Malignant_Secondary, @In_Situ, @Benign, @Uncertain_or_Unknown_Behaviour


-- LEAVING JUST ONE ROW FOR HEADER
WHILE @@FETCH_STATUS = 0
BEGIN
	set @tmplink1 = null
	set @tmplink2 = null
	set @tmplink3 = null
	set @tmplink4 = null

       	select @tmplink1= Malignant_Secondary from tmp_NeoplasmFr 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and subheaderid4 = @subheaderid4
				and Malignant_Secondary is not null
	select @tmplink2= In_Situ from tmp_NeoplasmFr 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and subheaderid4 = @subheaderid4 
				and In_Situ is not null
	select @tmplink3= Benign from tmp_NeoplasmFr 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3 and subheaderid4 = @subheaderid4 
				and Benign is not null
	select @tmplink4= Uncertain_or_Unknown_Behaviour from tmp_NeoplasmFr 
		where headerid = @headerid and subheaderid = @subheaderid and subheaderid1 = @subheaderid1 and 
				subheaderid2 = @subheaderid2 and subheaderid3 = @subheaderid3  and subheaderid4 = @subheaderid4
				and Uncertain_or_Unknown_Behaviour is not null


	UPDATE tmp_NeoplasmFrLast
		SET Malignant_Secondary = @tmplink1,
		In_Situ = @tmplink2,
		Benign = @tmplink3,
		Uncertain_or_Unknown_Behaviour = @tmplink4
		WHERE   headerid     = @headerid and 
			subheaderid  = @subheaderid and
			subheaderid1 = @Subheaderid1 and
			subheaderid2 = @Subheaderid2 and
			subheaderid3 = @Subheaderid3 and
			subheaderid4 = @subheaderid4
	
FETCH NEXT FROM cursor_tmp_NeoplasmFrlast
INTO @Autoid, @headerid, @SubHeaderId, @SubHeaderId1, @SubHeaderId2, @SubHeaderId3, @SubHeaderId4, @HeaderDesc, @HeaderSearch, @Malignant_Primary, @Malignant_Secondary, @In_Situ, @Benign, @Uncertain_or_Unknown_Behaviour

END

CLOSE      cursor_tmp_NeoplasmFrlast
DEALLOCATE cursor_tmp_NeoplasmFrlast




-- Remove words "Malignes Primitives codelinks" at the end --


UPDATE tmp_NeoplasmFrlast
		SET headerdesc = rtrim(substring(Headerdesc,1,CHARINDEX('Malignes Primitives', headerdesc, 1)-1 )),
		    headersearch = rtrim(substring(headerSearch,1,CHARINDEX('Malignes Primitives', headerSearch, 1)-1 ))		WHERE  headerdesc like '%Malignes Primitives%' 


-- Do not execute this part.  It's not necesary after latest Simon parse 
-- CODELINK = ''  leave at the end
--INSERT INTO tmp_NeoplasmFrLAST (Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4,
--HeaderDesc, HeaderSearch)
--select Autoid, headerid, SubHeaderId, SubHeaderId1, SubHeaderId2, SubHeaderId3, SubHeaderId4, HeaderDesc, HeaderSearch 
--from NU_NeoplasmLastFr  where codelink = ''


UPDATE tmp_NeoplasmFrlast SET  Malignant_Primary = null  WHERE Malignant_Primary = ''  


-- Replace character "|" for "-" resolve problem in VB
UPDATE tmp_neoplasmfrlast SET headerdesc=replace(headerdesc,char(150),char(45)) 


-- Drop tables
drop table tmp_NeoplasmFr

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE                                        PROCEDURE [TMP_LookUpDrugs_B]
@SearchString  as varchar(800),
@OptionalStmt as varchar(10)
AS

-- Author: Brenda Vargas : Jan 24, 2007
-- Latest Change:     Feb 1, 2007
-- Prototype Drugs : It will replace the current Sp --> NU_LookUpDrugs_B 

--- Aug 21, 2007:
---             Sp renamed.  It was TMP_LookUpDrugs_B
---                renamed tmp_drugslast to Nu_DrugsLast
---                Renamed tmp_drugsFrlast to Nu_DrugsFrlast

-- Sep 14, 2007 sp renamed again as TMP_LookUpDrugs_B but look for the new tables

Create table #T (
Autoid integer, 
HeaderDesc VARCHAR(255),
Chapter_XIX VARCHAR (15),
Accidental VARCHAR (15),
Intentional_Self_Harm VARCHAR (15),
Undetermined_Intent VARCHAR (15),
Adverse_effect_in_therapeutic_use VARCHAR (15), 
HeaderId int,
SubHeaderId int,
SubHeaderId1 int, 
SubHeaderId2 int,
SubHeaderId3 int,
HeaderSearch VARCHAR(255), 
HitNumber int, 
)

Declare @SQL as varchar(5000)
Declare @Index as int
Declare @Flag as int                        -- use for first word   
Declare @WordToSearch as varchar(100) 

-- French 
if @OptionalStmt = '10000'
BEGIN
    set @Flag = 1 

    WHILE @SearchString <> ' ' 
    begin
   
   set nocount on
   
   set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
   set @Index = CHARINDEX (' ',  @SearchString  ,1 ) 
   set @WordToSearch =  rtrim(Left(@SearchString,@Index))

        if @WordToSearch = ''
   begin
      set @WordToSearch = @SearchString
   end
   
   set @SearchString = replace(@SearchString,@WordToSearch,'')

   if  @WordToSearch  <> '' 
   begin
           set @WordToSearch = replace(@WordToSearch, '  ', ' ')
           set @WordToSearch = replace(@WordToSearch, ' ', '%'' and [HeaderSearch]   like ''%')

           if @Flag = 1  -- begin procedure for First word
           begin

                   set @WordToSearch = '[HeaderSearch]    like '' ' + @WordToSearch + '%'''
                           
                   -- HitNumber = 1 : Means first work on the search  
                   set @SQL =      'INSERT INTO #T ' +
                   'SELECT top 1000 Autoid, HeaderDesc ,Chapter_XIX, Accidental, Intentional_Self_Harm, 
                   Undetermined_Intent, Adverse_effect_in_therapeutic_use, HeaderId ,SubheaderId,
                   SubHeaderId1, SubHeaderId2,SubHeaderId3, HeaderSearch, 1
                   FROM Nu_DrugsFrlast WHERE '
                   + @WordToSearch + '  and subheaderid = 0 order by autoid'
                   exec( @SQL)

                   -- Add ALL children RELATED to this headerid with HitNumber = 0 
                   
                   INSERT INTO #T 
                   SELECT top 1000 A.Autoid, A.HeaderDesc ,A.Chapter_XIX, A.Accidental, 
                   A.Intentional_Self_Harm, A.Undetermined_Intent, A.Adverse_effect_in_therapeutic_use, 
                   A.HeaderId ,A.SubheaderId, A.SubheaderId1, A.SubheaderId2, A.SubheaderId3, A.HeaderSearch, 0
                   FROM Nu_DrugsFrlast as A, #T  
                   WHERE  A.headerid = #T.headerid and A.subheaderid <> 0 order by A.autoid

                   set @Flag = @Flag + 1

           end -- end procedure for First word
           else 
             begin
                   -- Others Words procedure
                   set @WordToSearch = '[HeaderSearch]    like ''% ' + @WordToSearch + '%'''
                   
                   set @SQL = 'UPDATE #T SET HitNumber = ' + cast(@Flag as varchar)  + ' WHERE ' + @WordToSearch 
                   exec( @SQL)
           
                   set @Flag = @Flag + 1
             end
           
   end  -- ENDS IF 
   END  -- ENDS WHILE 
END  ---- ENDS FRENCH  


--English 
IF @OptionalStmt = '0' 
BEGIN
    set @Flag = 1 

    WHILE @SearchString <> ' ' 
    begin
   
   set nocount on
   
   set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
   set @Index = CHARINDEX (' ',  @SearchString  ,1 ) 
   set @WordToSearch =  rtrim(Left(@SearchString,@Index))

        if @WordToSearch = ''
   begin
      set @WordToSearch = @SearchString
   end
   
   set @SearchString = replace(@SearchString,@WordToSearch,'')

   if  @WordToSearch  <> '' 
   begin
           set @WordToSearch = replace(@WordToSearch, '  ', ' ')
           set @WordToSearch = replace(@WordToSearch, ' ', '%'' and [HeaderSearch]   like ''%')

           if @Flag = 1  -- begin procedure for First word
           begin

                   set @WordToSearch = '[HeaderSearch]    like '' ' + @WordToSearch + '%'''
                           
                   -- HitNumber = 1 : Means first work on the search  
                   set @SQL =      'INSERT INTO #T ' +
                   'SELECT top 1000 Autoid, HeaderDesc ,Chapter_XIX, Accidental, Intentional_Self_Harm, 
                   Undetermined_Intent, Adverse_effect_in_therapeutic_use, HeaderId ,SubheaderId,
                   SubHeaderId1, SubHeaderId2,SubHeaderId3, HeaderSearch, 1
                   FROM Nu_DrugsLast WHERE '
                   + @WordToSearch + '  and subheaderid = 0 order by autoid'
                   exec( @SQL)

                   -- Add ALL children RELATED to this headerid with HitNumber = 0 
                   
                   INSERT INTO #T 
                   SELECT top 1000 A.Autoid, A.HeaderDesc ,A.Chapter_XIX, A.Accidental, 
                   A.Intentional_Self_Harm, A.Undetermined_Intent, A.Adverse_effect_in_therapeutic_use, 
                   A.HeaderId ,A.SubheaderId, A.SubheaderId1, A.SubheaderId2, A.SubheaderId3, A.HeaderSearch, 0
                   FROM Nu_DrugsLast as A, #T  
                   WHERE  A.headerid = #T.headerid and A.subheaderid <> 0 order by A.autoid

                   set @Flag = @Flag + 1

           end -- end procedure for First word
           else 
             begin
                   -- Others Words procedure
                   set @WordToSearch = '[HeaderSearch]    like ''% ' + @WordToSearch + '%'''
                   
                   set @SQL = 'UPDATE #T SET HitNumber = ' + cast(@Flag as varchar)  + ' WHERE ' + @WordToSearch 
                   exec( @SQL)
           
                   set @Flag = @Flag + 1
             end
           
   end  -- ENDS IF 
   END  -- ENDS WHILE 
END


SELECT DISTINCT  HeaderDesc,Chapter_XIX, Accidental, Intentional_Self_Harm, 
   Undetermined_Intent, Adverse_effect_in_therapeutic_use,HeaderId ,
   SubheaderId, SubheaderId1, SubheaderId2, SubheaderId3, HitNumber, Autoid 
FROM #T order by Autoid









GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE                                            PROCEDURE [TMP_LookUpNeoplasm_B]
@SearchString  as varchar(800),
@OptionalStmt as varchar(10)
AS

-- Author: Brenda Vargas : Feb 7, 2007
-- Latest Change:     Feb 7, 2007
-- Prototype Neoplasm : It will replace the current Sp --> NU_LookUpNeoplasm_B 

--- Aug 21, 2007:
---             Sp renamed.  It was TMP_LookUpNeoplasm_B
---                renamed tmp_Neoplasmlast to NU_Neoplasmlast
---                Renamed tmp_NeoplasmFrlast to NU_NeoplasmFrlast 
-- Sep 14, 2007 sp renamed again as TMP_LookUpNeoplasm_B but look for the new tables

Create table #T (
Autoid integer, 
HeaderDesc VARCHAR(255),
Malignant_Primary VARCHAR (15),
Malignant_Secondary VARCHAR (15),
In_Situ VARCHAR (15),
Benign VARCHAR (15),
Uncertain_or_Unknown_Behaviour VARCHAR (15),
HeaderId int,
SubHeaderId int,
SubHeaderId1 int, 
SubHeaderId2 int,
SubHeaderId3 int,
SubHeaderId4 int, 
HeaderSearch VARCHAR(255), 
HitNumber int, 
)



Declare @SQL as varchar(5000)
Declare @Index as int
Declare @Flag as int                        -- use for first word   
Declare @WordToSearch as varchar(100) 

-- French 
if @OptionalStmt = '10000'
BEGIN
    set @Flag = 1 

    WHILE @SearchString <> ' ' 
    begin
   
   set nocount on
   
   set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
   set @Index = CHARINDEX (' ',  @SearchString  ,1 ) 
   set @WordToSearch =  rtrim(Left(@SearchString,@Index))

        if @WordToSearch = ''
   begin
      set @WordToSearch = @SearchString
   end
   
   set @SearchString = replace(@SearchString,@WordToSearch,'')

   if  @WordToSearch  <> '' 
   begin
           set @WordToSearch = replace(@WordToSearch, '  ', ' ')
           set @WordToSearch = replace(@WordToSearch, ' ', '%'' and [HeaderSearch]   like ''%')

           if @Flag = 1  -- begin procedure for First word
           begin

                   set @WordToSearch = '[HeaderSearch]    like '' ' + @WordToSearch + '%'''
                           
                   -- HitNumber = 1 : Means first work on the search  
                   set @SQL =      'INSERT INTO #T ' +
                   'SELECT top 1000 Autoid, HeaderDesc ,Malignant_Primary, Malignant_Secondary, 
                   In_Situ, Benign, Uncertain_or_Unknown_Behaviour, HeaderId ,SubheaderId,
                   SubHeaderId1, SubHeaderId2,SubHeaderId3, SubHeaderId4, HeaderSearch, 1
                   FROM NU_NeoplasmFrlast WHERE '
                   + @WordToSearch + '  and subheaderid1 = 0 order by autoid'
                   
                   print @sql

                   exec( @SQL)

                   -- Add ALL children RELATED to this headerid with HitNumber = 0 
                   INSERT INTO #T 
                   SELECT top 1000 A.Autoid, A.HeaderDesc ,A.Malignant_Primary, A.Malignant_Secondary, 
                   A.In_Situ, A.Benign, A.Uncertain_or_Unknown_Behaviour,
                   A.HeaderId ,A.SubheaderId, A.SubheaderId1, A.SubheaderId2, A.SubheaderId3, A.SubHeaderId4, A.HeaderSearch, 0
                   FROM NU_NeoplasmFrlast as A, #T  
                   WHERE  A.headerid = #T.headerid and 
                   A.subheaderid = #T.subheaderid and A.subheaderid1 <> 0 order by A.autoid

                   set @Flag = @Flag + 1

           end -- end procedure for First word
           else 
             begin
                   -- Others Words procedure
                   set @WordToSearch = '[HeaderSearch]    like ''% ' + @WordToSearch + '%'''
                   
                   set @SQL = 'UPDATE #T SET HitNumber = ' + cast(@Flag as varchar)  + ' WHERE ' + @WordToSearch 
                   exec( @SQL)
           
                   set @Flag = @Flag + 1
             end
           
   end  -- ENDS IF 
   END  -- ENDS WHILE 
END  ---- ENDS FRENCH 

--English 
IF @OptionalStmt = '0' 
BEGIN

    set @Flag = 1 

    WHILE @SearchString <> ' ' 
    begin
   
   set nocount on
   
   set @SearchString = LTRIM(RTRIM(@SearchString)) --clean leading and trailing
   set @Index = CHARINDEX (' ',  @SearchString  ,1 ) 
   set @WordToSearch =  rtrim(Left(@SearchString,@Index))

        if @WordToSearch = ''
   begin
      set @WordToSearch = @SearchString
   end
   
   set @SearchString = replace(@SearchString,@WordToSearch,'')

   if  @WordToSearch  <> '' 
   begin

           set @WordToSearch = replace(@WordToSearch, '  ', ' ')
           set @WordToSearch = replace(@WordToSearch, ' ', '%'' and [HeaderSearch]   like ''%')

           if @Flag = 1  -- begin procedure for First word
           begin

                   set @WordToSearch = '[HeaderSearch]    like ''%' + @WordToSearch + '%'''
                           
                   -- HitNumber = 1 : Means first work on the search  
                   set @SQL =      'INSERT INTO #T ' +
                   'SELECT top 1000 Autoid, HeaderDesc ,Malignant_Primary, Malignant_Secondary, 
                   In_Situ, Benign, Uncertain_or_Unknown_Behaviour, HeaderId ,SubheaderId,
                   SubHeaderId1, SubHeaderId2,SubHeaderId3, 0,  HeaderSearch, 1    
                   FROM NU_Neoplasmlast WHERE '
                   + @WordToSearch + '  and subheaderid1 = 0 order by autoid'   -- Ojo solo para English falta agregar SubHeaderId4
   
                   print @SQL

                   exec( @SQL)

                   -- Add ALL children RELATED to this headerid with HitNumber = 0 
                   INSERT INTO #T 
                   SELECT top 1000 A.Autoid, A.HeaderDesc ,A.Malignant_Primary, A.Malignant_Secondary, 
                   A.In_Situ, A.Benign, A.Uncertain_or_Unknown_Behaviour,
                   A.HeaderId ,A.SubheaderId, A.SubheaderId1, A.SubheaderId2, A.SubheaderId3,0, A.HeaderSearch, 0
                   FROM NU_Neoplasmlast as A, #T      -- Ojo solo para English falta agregar SubHeaderId4
                   WHERE  A.headerid = #T.headerid and 
                   A.subheaderid = #T.subheaderid and A.subheaderid1 <> 0 order by A.autoid

                   set @Flag = @Flag + 1

           end -- end procedure for First word
           else 
             begin
                   -- Others Words procedure
                   set @WordToSearch = '[HeaderSearch]    like ''% ' + @WordToSearch + '%'''
                   
                   set @SQL = 'UPDATE #T SET HitNumber = ' + cast(@Flag as varchar)  + ' WHERE ' + @WordToSearch 
                   exec( @SQL)
           
                   set @Flag = @Flag + 1
             end
           
   end  -- ENDS IF 
   END  -- ENDS WHILE 
END

SELECT DISTINCT  HeaderDesc,Malignant_Primary, Malignant_Secondary, 
   In_Situ, Benign, Uncertain_or_Unknown_Behaviour, HeaderId ,
   SubheaderId, SubheaderId1, SubheaderId2, SubheaderId3, SubheaderId4, HitNumber, Autoid
FROM #T order by Autoid












GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is called by the Save Method of the Abstract Controls
CREATE     PROCEDURE [U_AB_Abstract]
   (@IsMultiContact             [int],
    @ICDType                    [char](1),
    @CareType                   [int],
    @HospitalID			        [int],
    @AbstractID                 [int],
    @IsCorrected                [int],
    @IsSubmitted                [int],
    @IsValidated                [int],
    @IsCompleted                [int],
    @IsDeleted                  [int],
    @CIHIDateSent          	[datetime],
    @BatchYear                  [varchar](10),
    @BatchPeriod                [int],
    @BatchNumber                [varchar](10),
    @AbstractNumber             [varchar](10),
    @ProvinceNumber             [int],
    @InstitutionNumber          [int],
    @SiteNumber                 [int],
    @EncounterNumber            [varchar](20),
    @EncounterSequence          [int],
    @ChartNumber                [varchar](10),
    @CoderNumber           	    [int],
    @MaidenName            	    [varchar](35),
    @LastName                   [varchar](40),
    @MiddleName                 [varchar](15),
    @FirstName                  [varchar](35),
    @Gender                     [int],
    @BirthDate                  [datetime],
    @BirthDateEstimated         [int],
    @MaritalStatus              [int],
    @LanguageCode          	    [int],
    @PostalCode                 [varchar](6),
    @ResidenceCode              [int],
    @ResponsiblePayment         [int],
    @EducationLevel             [int],
    @Occupation                 [int],
    @LivingArrangement          [int],
    @ResidenceType              [int],
    @HCNProvince           	    [int],
    @HealthCareNumber           [varchar](12),
    @HCNVersion                 [varchar](2),
    @AdmitDate                  [datetime],
    @AdmitTime                  [datetime],
    @ArrivalMode                [int],
    @ArrivalDate                [datetime],
    @ArrivalTime                [datetime],
    @RegisterNumber             [varchar](8),
    @SecondChartRegNumber  	    [varchar](10),
    @AgeCode                    [int],
    @AgeNumber                  [varchar](10),
    @EntryCode                  [int],
    @DecisionAdmitDate          [datetime],
    @DecisionAdmitTime          [datetime],
    @DecisionAdmitDifference    [varchar](10),
    @TransferOverloadDate       [datetime],
    @TransferOverloadTime  	    [datetime],
    @TransferOverloadDifference [varchar](10),
    @NextSchedVisitDate         [datetime],
    @NextSchedVisitTime         [datetime],
    @WaitTimeER                 [varchar](10),
    @Weight                     [varchar](10),
    @AdmitCategory         	    [int],
    @AdmitAmbulance             [int],
    @AmbulanceReportNumber      [varchar](11),
    @InstitutionFrom            [int],
    @Program                    [int],
    @MISCode                    [int],
    @ContactMode                [int],
    @ReferredFrom               [int],
    @VisitType                  [int],
    @ReAdmitCode                [int],
    @UnplanReAdmit         	    [int],
    @AttendingPhysician         [int],
    @AdmittingDiagnosis         [int],
    @ChiefComplaint             [varchar](250),
    @Injury                     [int],
    @InjuryLocation             [int],
    @InjuryActivity             [int],
    @InjuryActivityDescription  [varchar](250),
    @TriageLevel                [int],
    @TriageDate                 [datetime],
    @TriageTime                 [datetime],
    @ArrivalTriageDifference    [varchar](10),
    @AssessmentDate             [datetime],
    @AssessmentTime             [datetime],
    @WaitAssessmentDifference   [varchar](10),
    @AdmittingNurseArea         [int],
    @PreAdmitWorkUp             [int],
    @DischargeDate         	[datetime],
    @DischargeTime         	[datetime],
    @EstimatedDischargeDate     [datetime],
    @DischargeNurseArea         [int],
    @LOSDays                    [varchar](10),
    @LOSTime                    [varchar](10),
    @LOSMinutes                 [varchar](10),
    @LOSTotal                   [varchar](10),
    @PhysicianEstimatedLOS      [varchar](10),
    @DischargeAge          	[varchar](10),
    @ExitCode                   [int],
    @DispositionCode            [int],
    @ReferredTo                 [int],
    @DischargePlanning          [int],
    @DateReadyDischarge         [datetime],
    @DateLeftER                 [datetime],
    @TimeLeftER                 [datetime],
    @InstitutionTo              [int],
    @SocialService              [int],
    @NewbornChart          	[varchar](10),
    @NewbornDischargeDate  	[datetime],
    @AcuteLOS                   [varchar](10),
    @ALCLOS                     [varchar](10),
    @GlasgowComaScale           [int],
    @Complication               [int],
    @SurgicalCase               [int],
    @PreOpDays                  [varchar](10),
    @PostOpDays                 [varchar](10),
    @InterfaceDate              [datetime],
    @InterfaceTime              [datetime],
    @InterfaceCoder             [int],
    @InputDate                  [datetime],
    @InputTime                  [datetime],
    @DataEntryCoder             [int],
    @FinishDate                 [datetime],
    @FinishTime                 [datetime],
    @Secret                     [int],
    @AbstractOverflow           [int],
    @TSIDate                    [datetime],
    @TSITime                    [datetime],
    @TSICoder                   [int],
    @InjuryDate                 [datetime],
    @FamilyPhysician            [int],
    @VisitStatus                [int],
    @NurseAssessDate            [datetime],
    @NurseAssessTime            [datetime],
    @NurseAssessDiff            [varchar](10),
    @UniqiueLifetimeID          [varchar](20),
    @DecisionAdmitTimeUnknown   [int], 
    @AssessmentTimeUnknown      [int],
    @PCTASIndicator             [int],
    @SchedEDVisit          	[int],
    @SeatbeltIndicator          [int],
    @HelmetIndicator 		[int], 
    @ReferralDate 		[datetime], 
    @CompleteRecord 		[int],
    @AgeGroup 			[int],
    @StakeHolder 		[int],
    @TimeLeftERUnknown 		[int],
    @DischargeAgeCode 		[int],
    @DischargeTimeUnknown 	[int],
    @ReasonForVisit 		[int],
    @RefPhysician 		[int],
    @TriageTimeUnknown 	[int],
    @AmbulanceArrDate 		[datetime], 
    @AmbulanceArrTime 		[datetime], 
    @AmbulanceTranDate  	[datetime], 
    @AmbulanceTranTime 	[datetime],
    @CDUArrivalDate 	[datetime], 
    @CDUArrivalTime 	[datetime],
    @IsReciprocalBilling int,
    @CDUFlag    int = 0,
    @CDUInTimeUnknown int = 0,
    @CDUOutDate datetime = null,
    @CDUOutTime datetime = null,
    @CDUOutTimeUnknown int = 0,
    @AccessCareCode int = 0,
    @SubmissionLevel int = 0,
    @AmbulanceArrTimeUnknown int = 0,
    @AmbulanceTranTimeUnknown int = 0,
    @IsSubmitLevel1 	int, 
    @IsCorrectLevel1 	int,
    @IsValidLevel1	int,
    @CIHIDateSentLevel1 datetime,
    @IsCompleteLevel1 	int,
    @AdmitTimeUnknown   int,
    @ArrivalTimeUnknown int,
    @RegionalPatientID varchar(50),
    @FixedChartNumber varchar(50),
	@IsCustomValidated int,
    @WaitTimeERHour int,
    @Height varchar(10),
    @WeightKilo varchar(10),
	@InstitutionFromType int,
	@InstitutionToType int,
	@UniversalEpisodeIdentifier varchar(50),
    @IsLiteSubmission int,
    @HospitalAccountRecord varchar(50),
	@IndigenousIdentity int,
	@RacializedGroups int
 )
AS 

If isnull(@IsDeleted, 0) = 0   set @IsDeleted = 2   -- PR - 03723
If isnull(@IsCorrected, 0) = 0 set @IsCorrected = 1 -- PR - 03723
If isnull(@IsSubmitted, 0) = 0  set @IsSubmitted = 2  -- PR - 03723
If isnull(@IsSubmitLevel1, 0) = 0  set @IsSubmitLevel1 = 2  --NP-00125
If isnull(@IsCorrectLevel1, 0) = 0 set @IsCorrectLevel1 = 1 --NP-00125
If isnull(@IsCompleteLevel1, 0) = 0 set @IsCompleteLevel1 = 1 --ED-02065

if @AgeNumber < 0 set @AgeNumber = 0    --PR - 05653

set @LastName = replace(@LastName, '''''', '''')
update [AB_Abstract] 
set 
    [LinkID] 	    	= null,
    [HospitalID]    	= @HospitalID,
    [IsCorrected]   	= @IsCorrected,
    [IsSubmited]    	= @IsSubmitted,
    [IsValidated]   	= @IsValidated,
    [IsCompleted]   	= @IsCompleted,
    [IsDeleted]     	= @IsDeleted,
    [IsReciprocalBilling] = @IsReciprocalBilling,
    [ICDType]       	= @ICDType,
    [CareType]      	= @CareType,
    [CIHIDateSent]  	= @CIHIDateSent,
    [BatchYear]     	= @BatchYear,
    [BatchPeriod]   	= @BatchPeriod,
    [BatchNumber]   	= @BatchNumber,
    [AbstractNumber]   	= @AbstractNumber,
    [ProvinceNumber]    = @ProvinceNumber,
    [InstitutionNumber] = @InstitutionNumber,
    [SiteNumber]    	= @SiteNumber,
    [EncounterNumber]  	= @EncounterNumber,
    [EncounterSequence] = @EncounterSequence,
    [ChartNumber]   	= @ChartNumber,
    [UniqiueLifetimeID]	=@UniqiueLifetimeID,
    [CoderNumber]   	= @CoderNumber,
    [MaidenName]    	= @MaidenName,
    [LastName]      	= @LastName,
    [MiddleName]    	= @MiddleName,
    [FirstName]     	= @FirstName,
    [Gender]        	= @Gender,
    [BirthDate]     	= @BirthDate,
    [BirthDateEstimated]= @BirthDateEstimated,
    [MaritalStatus]     = @MaritalStatus,
    [LanguageCode]  	= @LanguageCode,
    [PostalCode]    	= @PostalCode,
    [ResidenceCode]     = @ResidenceCode,
    [ResponsiblePayment]= @ResponsiblePayment,
    [FamilyPhysician]   = @FamilyPhysician,
    [EducationLevel]    = @EducationLevel,
    [Occupation]    	= @Occupation,
    [LivingArrangement] = @LivingArrangement,
    [ResidenceType]     = @ResidenceType,
    [HCNProvince]   	= @HCNProvince,
    [HealthCareNumber]  = @HealthCareNumber,
    [HCNVersion]    	= @HCNVersion,
    [AdmitDate]     	= @AdmitDate,
    [AdmitTime]     	= @AdmitTime,
    [ArrivalMode]   	= @ArrivalMode,
    [ArrivalDate]   	= @ArrivalDate,
    [ArrivalTime]   	= @ArrivalTime,
    [RegisterNumber]    = @RegisterNumber,
    [SecondChartRegNumber]	= @SecondChartRegNumber,
    [AgeCode]       	= @AgeCode,
    [AgeNumber]     	= @AgeNumber,
    [AgeGroup]		=  @AgeGroup,
    [EntryCode]     	= @EntryCode,
    [DecisionAdmitDate]	= @DecisionAdmitDate,
    [DecisionAdmitTime] = @DecisionAdmitTime,
    [DecisionAdmitDifference]	= @DecisionAdmitDifference,
    [DecisionAdmitTimeUnknown]	=  @DecisionAdmitTimeUnknown,
    [TransferOverloadDate]	= @TransferOverloadDate,
    [TransferOverloadTime]  	= @TransferOverloadTime,
    [TransferOverloadDifference]= @TransferOverloadDifference,
    [NextSchedVisitDate]    	= @NextSchedVisitDate,
    [NextSchedVisitTime]    	= @NextSchedVisitTime,
    [WaitTimeER]    		= @WaitTimeER,
    [Weight]        		= @Weight,
    [AdmitCategory]         	= @AdmitCategory,
    [AdmitAmbulance]        	= @AdmitAmbulance,
    [AmbulanceReportNumber]     = @AmbulanceReportNumber,
    [InstitutionFrom]       	= @InstitutionFrom,
    [Program]       		= @Program,
    [MISCode]       		= @MISCode,
    [ContactMode]   		= @ContactMode,
    [ReferredFrom]  		= @ReferredFrom,
    [VisitType]     		= @VisitType,
    [VisitStatus]   		= @VisitStatus,
    [ReasonForVisit]		= @ReasonForVisit,
    [ReAdmitCode]   		= @ReAdmitCode,
    [UnplanReAdmit]         	= @UnplanReAdmit,
    [AttendingPhysician]    	= @AttendingPhysician,
    [AdmittingDiagnosis]    	= @AdmittingDiagnosis,
    [ChiefComplaint]        	= @ChiefComplaint,
    [Injury]        		= @Injury,
    [InjuryDate]    		= @InjuryDate,
    [InjuryLocation]        	= @InjuryLocation,
    [InjuryActivity]        	= @InjuryActivity,
    [InjuryActivityDescription]	= @InjuryActivityDescription,
    [TriageLevel]   		= @TriageLevel,
    [TriageDate]    		= @TriageDate,
    [TriageTime]    		= @TriageTime,
    [TriageTimeUnknown]		= @TriageTimeUnknown,
    [ArrivalTriageDifference]  	= @ArrivalTriageDifference,
    [AssessmentDate]        	= @AssessmentDate,
    [AssessmentTime]        	= @AssessmentTime,
    [WaitAssessmentDifference]	= @WaitAssessmentDifference,   
    [AssessmentTimeUnknown]   	= @AssessmentTimeUnknown, 
    [NurseAssessDate]      	= @NurseAssessDate, 
    [NurseAssessTime]      	= @NurseAssessTime,
    [NurseAssessDiff]      	= @NurseAssessDiff,
    [AdmittingNurseArea]    	= @AdmittingNurseArea,
    [PreAdmitWorkUp]        	= @PreAdmitWorkUp,
    [DischargeDate]         	= @DischargeDate,
    [DischargeTime]         	= @DischargeTime,
    [DischargeTimeUnknown] 	= @DischargeTimeUnknown,
    [EstimatedDischargeDate]	= @EstimatedDischargeDate,
    [DischargeNurseArea]    	= @DischargeNurseArea,
    [LOSDays]       		= @LOSDays,
    [LOSTime]       		= @LOSTime,
    [LOSMinutes]    		= @LOSMinutes,
    [LOSTotal]      		= @LOSTotal,
    [PhysicianEstimatedLOS]  	= @PhysicianEstimatedLOS,
    [DischargeAge]  		= @DischargeAge,
    [DischargeAgeCode]    	= @DischargeAgeCode,
    [ExitCode]      		= @ExitCode,
    [DispositionCode]       	= @DispositionCode,
    [ReferredTo]    		= @ReferredTo,
    [DischargePlanning]     	= @DischargePlanning,
    [DateReadyDischarge]    	= @DateReadyDischarge,
    [DateLeftER]    		= @DateLeftER,
    [TimeLeftER]    		= @TimeLeftER,
    [InstitutionTo]         	= @InstitutionTo,
    [SocialService]         	= @SocialService,
    [NewbornChart]  		= @NewbornChart,
    [NewbornDischargeDate]  	= @NewbornDischargeDate,
    [AcuteLOS]      		= @AcuteLOS,
    [ALCLOS]        		= @ALCLOS,
    [GlasgowComaScale]      	= @GlasgowComaScale,
    [Complication]  		= @Complication,
    [SurgicalCase]  		= @SurgicalCase,
    [PreOpDays]     		= @PreOpDays,
    [PostOpDays]    		= @PostOpDays,
    [InterfaceDate]         	= @InterfaceDate,
    [InterfaceTime]         	= @InterfaceTime,
    [InterfaceCoder]        	= @InterfaceCoder,
    [InputDate]     		= @InputDate,
    [InputTime]     		= @InputTime,
    [DataEntryCoder]        	= @DataEntryCoder,
    [FinishDate]    		= @FinishDate,
    [FinishTime]    		= @FinishTime,
    [Secret]        		= @Secret,
    [AbstractOverflow]      	= @AbstractOverflow,
    [TSIDate]       		= @TSIDate,
    [TSITime]       		= @TSITime,
    [TSICoder]      		= @TSICoder,
    [PCTASIndicator]       	= @PCTASIndicator, 
    [SchedEDVisit]         	= @SchedEDVisit,
    [SeatbeltIndicator]    	= @SeatbeltIndicator,
    [HelmetIndicator] 		= @HelmetIndicator, 
    [ReferralDate]		= @ReferralDate, 
    [CompleteRecord]		= @CompleteRecord,
    [StakeHolder]		= @StakeHolder,
    [TimeLeftERUnknown] = @TimeLeftERUnknown,
    [RefPhysician]		= @RefPhysician,
    [AmbulanceArrDate]	= @AmbulanceArrDate,
    [AmbulanceArrTime]	= @AmbulanceArrTime,
    [AmbulanceTranDate]	= @AmbulanceTranDate,
    [AmbulanceTranTime]	= @AmbulanceTranTime,
    [CDUArrivalDate]    = @CDUArrivalDate,  
    [CDUArrivalTime]    = @CDUArrivalTime,
    CDUFlag             = @CDUFlag,
    CDUInTimeUnknown    = @CDUInTimeUnknown,
    CDUOutDate          = @CDUOutDate,
    CDUOutTime          = @CDUOutTime,
    CDUOutTimeUnknown   = @CDUOutTimeUnknown,
    AccessCareCode      = @AccessCareCode,
    SubmissionLevel     = @SubmissionLevel,
    AmbulanceArrTimeUnknown = @AmbulanceArrTimeUnknown,
    AmbulanceTranTimeUnknown = @AmbulanceTranTimeUnknown,
    [IsSubmitLevel1]	= @IsSubmitLevel1, 
    [IsCorrectLevel1]	= @IsCorrectLevel1,
    [IsValidLevel1]	= @IsValidLevel1,
    [CIHIDateSentLevel1] = @CIHIDateSentLevel1,
    [IsCompleteLevel1]	 = @IsCompleteLevel1,
    [AdmitTimeUnknown] = @AdmitTimeUnknown,
    [ArrivalTimeUnknown] = @ArrivalTimeUnknown,
    [RegionalPatientID] = @RegionalPatientID,
    [FixedChartNumber]	= @FixedChartNumber ,
	[IsCustomValidated] = @IsCustomValidated,
    [WaitTimeERHour]    = @WaitTimeERHour,
    [Height]            = @Height,
    [WeightKilo]        = @WeightKilo,
	[InstitutionFromType] = @InstitutionFromType,
	[InstitutionToType] = @InstitutionToType,
	[UniversalEpisodeIdentifier] = @UniversalEpisodeIdentifier,
    [IsLiteSubmission]  = @IsLiteSubmission,
    [HospitalAccountRecord] = @HospitalAccountRecord,
	[IndigenousIdentity] = @IndigenousIdentity,
	[RacializedGroups] = @RacializedGroups
where 
   ([AbstractID]    		= @AbstractID)

/*Update multi Enc No's data for common fields*/
if @AdmitDate < '2006/04/01' -- PR-00673
begin
	if @Caretype = 5 and isnull(@EncounterNumber, '') <> ''
	begin
		update	[AB_Abstract] 
		set     
	     		[ChartNumber]          	= @ChartNumber,
		     	[UniqiueLifetimeID]    	= @UniqiueLifetimeID,
		     	[Gender]               	= @Gender,
		     	[BirthDate]            	= @BirthDate,
		     	[BirthDateEstimated]   	= @BirthDateEstimated,
		     	[MaritalStatus]      	= @MaritalStatus,
		     	[PostalCode]           	= @PostalCode,
		     	[ResidenceCode]        	= @ResidenceCode,
		     	[ResponsiblePayment]   	= @ResponsiblePayment,
		     	[HCNProvince]          	= @HCNProvince,
		     	[HealthCareNumber]     	= @HealthCareNumber,
		     	[HCNVersion]           	= @HCNVersion,
		     	[AdmitDate]            	= @AdmitDate,
		     	[RegisterNumber]       	= @RegisterNumber,
		     	[DischargeDate]        	= @DischargeDate,
		     	[DischargeTime]        	= @DischargeTime,
		     	[DischargeTimeUnknown] 	= @DischargeTimeUnknown,
		     	[DispositionCode]      	= @DispositionCode
		
		where  	[EncounterNumber]    	= @EncounterNumber 
		and 	[ChartNumber]		= @ChartNumber 
		and     [EncounterSequence]    	<> @EncounterSequence
		and    	[AdmitDate] 		= @AdmitDate 
		and 	[AdmitTime] 		= @AdmitTime
		and     [CareType]             	= 5
	
	    	--10489 Hong added temp
	    	declare @count     int
	    	declare @ID_001    int
	    	declare @Del_001   int
	    	declare @Sub_001   int
	    	declare @Cor_001   int
	
		set @count = isnull((select count(*)
	    				from AB_Abstract 
	    				where [EncounterNumber] = @EncounterNumber 
	        			and ChartNumber 	= @ChartNumber
	        			and [AdmitDate] 	= @AdmitDate 
	        			and [AdmitTime] 	= @AdmitTime 
	        			and [InstitutionNumber] = @InstitutionNumber
	        			and [CareType]  	= 5
	        			and IsDeleted 		<> 1), 0)
	
		if @count > 1 
	    	begin
	        	select top 1 
				@ID_001 = AbstractID, 
				@Del_001 = IsDeleted,
	            		@Sub_001 = IsSubmited, 
				@Cor_001 = IsCorrected
	        	from AB_Abstract 
	        	where [EncounterNumber]= @EncounterNumber 
	            	and ([EncounterSequence]= '1' or [EncounterSequence] = '001')
	            	and ChartNumber 	= @ChartNumber
	            	and [AdmitDate] 	= @AdmitDate 
	            	and [AdmitTime] 	= @AdmitTime 
	            	and [InstitutionNumber] = @InstitutionNumber
	            	and [CareType]  	= 5
	            	and IsDeleted 		<> 1
	
	    		-- 10758
	    		update [AB_Abstract] 
			set [LinkID] = @ID_001 
			from [AB_Abstract] 
	    		where  [EncounterNumber]= @EncounterNumber 
	        	and ChartNumber 	= @ChartNumber
	        	and [AdmitDate] 	= @AdmitDate 
	        	and [AdmitTime] 	= @AdmitTime 
	        	and [InstitutionNumber] = @InstitutionNumber
	        	and [CareType]  	= 5
	            	and IsDeleted 		<> 1
	

	        	if @Del_001 = 1 
	            		update Ab_Abstract 
				set IsDeleted = 2, 
	                	IsCorrected = (case when IsSubmited = 1 then 2 else IsCorrected end) 
	            		where LinkID 	= @ID_001 
				and CareType 	= 5 
				and abstractId 	<> @ID_001
	                	and IsDeleted 	= 1
	    	end
	end
end

if exists (select * from AB_Abstract where AbstractID = @AbstractID and isnull(VolumeID, 0) <= 0)
begin
     --9854: Update the Volume Number.
     declare @UseDate as DateTime
     declare @P as int 
     declare @V as int
     set @UseDate = @DischargeDate
     if @Caretype = 5 set @UseDate = @AdmitDate
     select top 1 @P = PatientID from CM_CPI where ChartNumber = @ChartNumber 
	and (isnull(HospitalID, 0) = 0 or @HospitalID = case @HospitalID when 0 then 0 else isnull(HospitalID, 0) end) --PR-04125
     select top 1 @V = isnull(VolumeID, 0) from CM_CPI_Volume where PatientID = @P and (([VolumeDateFrom] <= @UseDate) and (@UseDate <= [VolumenDateTo])) order by VolumenDateTo desc, VolumeID desc
     if isnull(@V, 0) = 0 
         select top 1 @V = isnull(VolumeID, 0) from CM_CPI_Volume where PatientID = @P order by VolumenDateTo desc, VolumeID desc
 
     exec P_UpdateAbstractVolume @V, 0, @AbstractID -- 13419: Abst ID is now the 3rd parameter.
end

-- RM: REMOVED - if @CareType = 5 exec P_UpdateAbstractNumber @AbstractID, @AdmitDate, @DischargeDate --PR-01550



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [U_AB_AbstractQueue](
        @AbstractIDs varchar(8000),
        @Coder int,
        @AssignedBy int,
        @IsCompleted varchar(10) --Y is completed, N is not completed to be assigned back to pool, P is to purge from the pool if it is not in the list
    )
as
    declare @sql as varchar(8000)
    set nocount on
    if @IsCompleted = 'Y'
    begin
        Insert into dbo.AB_AbstractQueueLog(AbstractID, Coder, AssignedBy, AssignedTime, IsCompleted, CompletedBy, CompletedTime)
        select AbstractID, Coder, AssignedBy, AssignedTime, 'Y', @AssignedBy, getdate()
        from AB_AbstractQueue
        where AbstractID = cast(@AbstractIDs as int)
        
        delete from AB_AbstractQueue
        where AbstractID = cast(@AbstractIDs as int)
    end
    else if len(@AbstractIDs) = 0
    begin
        Insert into dbo.AB_AbstractQueueLog(AbstractID, Coder, AssignedBy, AssignedTime, IsCompleted, CompletedBy, CompletedTime)
        select AbstractID, Coder, AssignedBy, AssignedTime, 'N', @AssignedBy, getdate()
        from AB_AbstractQueue
        where Coder = @Coder
        
        delete from AB_AbstractQueue where  Coder = @Coder
    end
    else
    begin
        if @IsCompleted = 'P'   --20218 if more than 500, it will remove the first 500 when more patients are added in. Only to remove abstract from the queue in the first patch.
        begin
            set @sql = 'Insert into dbo.AB_AbstractQueueLog(AbstractID, Coder, AssignedBy, AssignedTime, IsCompleted, CompletedBy, CompletedTime)
            select AbstractID, Coder, AssignedBy, AssignedTime, ''N'', ' + cast(@AssignedBy as varchar(10)) + ', getdate()
            from AB_AbstractQueue
            where Coder = ' + cast(@Coder as varchar(10)) + ' and AbstractID not in (' + @AbstractIDs + ') '
            exec (@sql)
        
            set @sql = 'delete from AB_AbstractQueue where Coder = ' + cast(@coder as varchar(10)) + ' and AbstractID not in (' + @AbstractIDs + ') '
            exec (@sql)
        end
        set @sql = 'Insert into AB_AbstractQueue(AbstractID, Coder, AssignedBy, AssignedTime)
        select  ab.AbstractID, ' + cast(@Coder as varchar(10)) + ', ' + cast(@AssignedBy as varchar(10)) + ', getdate()
        from AB_Abstract ab
            left join AB_AbstractQueue q on ab.AbstractID = q.AbstractID 
        where ab.AbstractID in (' + @AbstractIDs + ') and q.AbstractID is null  '
        
        exec (@sql)
        
        set @sql = 'select ab.AbstractID, h.CIHIValue as Institution, ab.ChartNumber,  m.CIHIValue, 
        convert(varchar(20), AdmitDate, 111) as AdmitDate, left(convert(varchar(20), AdmitTime, 114), 5) as AdmitTime,
        convert(varchar(20), dischargeDate, 111) as dischargeDate, left(convert(varchar(20), DischargeTime, 114), 5) as DischargeTime, 
        (case ab.CareType when 1 then ''Inpatient'' when 2 then ''SDS'' when 5 then ''Amcare'' else '''' end) as CareType,
        u.DisplayCode + '' - '' + u.UserDescription as AssignedCoder 
        from (select * from AB_AbstractQueue where AbstractID in (' + @AbstractIDs + ') and Coder <> ' + cast(@coder as varchar(10)) + ') q 
            inner join AB_Abstract ab on q.AbstractID = ab.AbstractID 
            inner join H_Institutionprofile h on h.code = ab.institutionnumber 
            inner join U_Users u on q.Coder = u.code
            left join lu_miscode m on m.code = ab.miscode 
        order by AdmitDate, DischargeDate'
        --print @sql
        exec (@sql)
        
    end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [U_AB_Main]
	@KeyID int,
	@AppType int
AS 

declare @PatientType as int 
declare @UniversalID as bigint
declare @AppID as int 
declare @HospitalID as int 
declare @PatientID as int 
declare @VolumeID as int
declare @AbstractID as int 
declare @LinkID as int 
declare @AssessmentType as int
declare @ICDType as varchar(1)
declare @InstitutionNumber as int 
declare @ChartNumber as varchar(10)
declare @LastName as varchar(40)
declare @FirstName as varchar(35)
declare @MiddleName as varchar(15)
declare @MaidenName as varchar(35)
declare @Gender as int
declare @Birthdate as datetime
declare @VisitDate as datetime
declare @VisitTime as datetime
declare @AdmitDate as datetime
declare @AdmitTime as datetime
declare @DischargeDate as datetime
declare @DischargeTime as datetime
declare @AssessmentDate as datetime -- FollowUpDate, A3, A1
declare @AssessmentTime as datetime 
declare @EncounterNumber as varchar(20)
declare @EncounterSequence as int
declare @RegisterNumber as varchar(8)
declare @HealthCareNumber as varchar(12)
declare @NewbornChart as varchar(10)
declare @SecondChartRegNumber as varchar(10)
declare @MISCode as int 
declare @AttendingPhysician as int 
declare @AdmittingNurseArea as int 
declare @RefPhysician as int 
declare @DiagnosisCode as int
declare @IntervCode as int 
declare @DeathIndicator as int 
declare @IsCompleted as int 
declare @IsValidated as int 
declare @IsCompleteLevel1 as int 
declare @IsValidLevel1 as int
declare @IsDeleted as int
declare @HasTrans as int
declare @HasDAS as bigint
declare @RegionalPatientID  varchar(50)	--PR - 05538
declare @FixedChartNumber varchar(50) --ED - 02787
declare @IsCustomValidated as int
declare @UniversalEpisodeIdentifier varchar(50)
declare @HospitalAccountRecord varchar(50)

set @PatientID = 0
set @VolumeID = 0
set @AbstractID = 0
set @LinkID = 0
set @AssessmentType = 0

select @PatientType = isnull(PatientType, 0), @UniversalID = UniversalID, @HasTrans = HasTrans, @HasDAS = HasDAS, @VolumeID = isnull(VolumeID, 0), 
    @UniversalEpisodeIdentifier = UniversalEpisodeIdentifier , @HospitalAccountRecord = HospitalAccountRecord
    --Keep the Old Volume 
from AB_Main 
where (@AppType = 9 and UniversalID = @KeyID)
or (@AppType = 0 and AppType = 0 and PatientID = @KeyID)
or (@AppType not in (0, 9) and AppType = @AppType and AbstractID = @KeyID)

if isnull(@UniversalID, 0) = 0 --if there is no visit History
begin
	set @PatientType = 0 --PR-02018
	set @UniversalID = isnull((select max(UniversalID) + 1 from AB_Main), 1)
end

if @AppType = 0 --CPI
begin
	set @PatientID = @KeyID
	select @HospitalID = [HospitalID], @ICDType = null, @InstitutionNumber = null, @ChartNumber = [ChartNumber],
		@LastName = [LastName], @FirstName = [FirstName], @MiddleName = [MiddleName], @MaidenName = [MaidenName], @Gender  = [Gender], @Birthdate = [Birthdate], 
		@AdmitDate = null, @AdmitTime = null, @DischargeDate = null, @DischargeTime = null, @AssessmentDate = null, @AssessmentTime = null,
		@EncounterNumber = null, @EncounterSequence = null, @RegisterNumber = null, @HealthCareNumber = [HealthCareNumber],
		@NewbornChart = null, @SecondChartRegNumber = null, @MISCode = null, 
		@AttendingPhysician = null, @AdmittingNurseArea = null, @RefPhysician = null,
		@IsCompleted = null, @IsValidated = null, @IsCompleteLevel1 = null, @IsValidLevel1 = null, @IsDeleted = [IsDeleted],
		@RegionalPatientID = RegionalPatientID, @FixedChartNumber = FixedChartNumber, @IsCustomValidated = null
	from CM_CPI where PatientID = @KeyID

	set @DiagnosisCode = null
	set @IntervCode = null
	set @AppID = 0 
	set @VisitDate = null
	set @VisitTime = null
end

else if @AppType = 9 --Non Abstract (visit history)
begin
	select 	@HospitalID = [HospitalID], @ICDType = [ICDType], @AbstractID = [AbstractID], @LinkID = [LinkID], @InstitutionNumber = [InstitutionNumber], @ChartNumber = [ChartNumber],
		@LastName = [LastName], @FirstName = [FirstName], @MiddleName = [MiddleName], @MaidenName = [MaidenName], @Gender  = [Gender], @Birthdate = [Birthdate], 
		@AdmitDate = [AdmitDate], @AdmitTime = [AdmitTime], @DischargeDate = [DischargeDate], @DischargeTime = [DischargeTime], @VisitDate = [VisitDate], @VisitTime = [VisitTime],
		@EncounterNumber = [EncounterNumber], @EncounterSequence = [EncounterSequence], @RegisterNumber = [RegisterNumber], @HealthCareNumber = [HealthCareNumber],
		@NewbornChart = [NewbornChart], @SecondChartRegNumber = [SecondChartRegNumber], @MISCode = [MISCode], 
		@AttendingPhysician = [AttendingPhysician], @AdmittingNurseArea = [AdmittingNurseArea], @RefPhysician = [RefPhysician],
		@DiagnosisCode = [DiagnosisCode], @IntervCode = [IntervCode],
		@IsCompleted = [IsCompleted], @IsValidated = [IsValidated], @IsCompleteLevel1 = [IsCompleteLevel1], @IsValidLevel1 = [IsValidLevel1], @IsDeleted = [IsDeleted],
		@RegionalPatientID = RegionalPatientID, @FixedChartNumber = FixedChartNumber, @IsCustomValidated = [IsCustomValidated],
		@UniversalEpisodeIdentifier = UniversalEpisodeIdentifier, @HospitalAccountRecord = HospitalAccountRecord
	from AB_Main where UniversalID = @KeyID

	select top 1 @PatientID = PatientID from CM_CPI where ChartNumber = @ChartNumber  and (isnull(HospitalID, 0) = 0 OR @HospitalID = case @HospitalID when 0 then 0 else isnull(HospitalID, 0) end)
	set @AppID = 3 
end

else if @AppType in (1, 2, 5, 101, 102, 105) --DAD, NACRS, SDS 
begin
	set @AbstractID = @KeyID
	select @HospitalID = [HospitalID], @ICDType = [ICDType], @InstitutionNumber = [InstitutionNumber], @ChartNumber = [ChartNumber],
		@LastName = [LastName], @FirstName = [FirstName], @MiddleName = [MiddleName], @MaidenName = [MaidenName], @Gender  = [Gender], @Birthdate = [Birthdate], 
		@AdmitDate = [AdmitDate], @AdmitTime = [AdmitTime], @DischargeDate = [DischargeDate], @DischargeTime = [DischargeTime], @AssessmentDate = null, @AssessmentTime = null,
		@EncounterNumber = [EncounterNumber], @EncounterSequence = [EncounterSequence], @RegisterNumber = [RegisterNumber], @HealthCareNumber = [HealthCareNumber],
		@NewbornChart = [NewbornChart], @SecondChartRegNumber = [SecondChartRegNumber], @MISCode = [MISCode], 
		@AttendingPhysician = [AttendingPhysician], @AdmittingNurseArea = [AdmittingNurseArea], @RefPhysician = [RefPhysician],
		@IsCompleted = [IsCompleted], @IsValidated = [IsValidated], @IsCompleteLevel1 = [IsCompleteLevel1], @IsValidLevel1 = [IsValidLevel1], @IsDeleted = [IsDeleted],
		@RegionalPatientID = RegionalPatientID, @FixedChartNumber = FixedChartNumber, @IsCustomValidated = [IsCustomValidated],
		@UniversalEpisodeIdentifier = UniversalEpisodeIdentifier, @HospitalAccountRecord = HospitalAccountRecord
	from AB_Abstract where AbstractID = @KeyID

	select top 1 @PatientID = PatientID from CM_CPI where ChartNumber = @ChartNumber  and (isnull(HospitalID, 0) = 0 OR @HospitalID = case @HospitalID when 0 then 0 else isnull(HospitalID, 0) end)
	select @DiagnosisCode = DiagnosisCode from AB_Diagnosis where DiagnosisOccurrence = 1 and AbstractID = @KeyID
	select @IntervCode = IntervCode from AB_Intervention where IntervOccurrence = 1 and AbstractID = @KeyID	

	set @AppID = 
		(case 
			when @AppType in (1, 101) and @ICDType in ('C', '9') and @DischargeDate is null then 100
			when @AppType in (1, 101) and @ICDType in ('C', '9') then 101
			when @AppType in (2, 102) and @ICDType in ('C', '9') then 102
			when @AppType in (5, 105) and @ICDType in ('C', '9') then 301
			when @AppType in (1, 101) and @ICDType = 'T' and @DischargeDate is null then 200
			when @AppType in (1, 101) and @ICDType = 'T' then 201
			when @AppType in (2, 102) and @ICDType = 'T' then 202
			when @AppType in (5, 105) and @ICDType = 'T' then 401
		end)

	set @VisitDate = @DischargeDate
	set @VisitTime = @DischargeTime
	if @AppID in (100, 200, 301, 401)
	begin
		set @VisitDate = @AdmitDate
		set @VisitTime = @AdmitTime
	end

	if @AppID in (301) -- ICD 9 NACRS doesn't use the same Attending Physician
		select @AttendingPhysician = ProviderNumber from AB_Provider where ProviderOccurrence = 1 and AbstractID = @KeyID
end

else if @AppType = 3 --NRS
begin
	set @AbstractID = @KeyID
	select @HospitalID = [HospitalID], @ICDType = [ICDType], @AssessmentType = AssessmentType, @LinkID = [LinkID], @InstitutionNumber = [InstitutionNumber], @ChartNumber = [ChartNumber],
		@LastName = [LastName], @FirstName = [FirstName], @MiddleName = [MiddleName], @MaidenName = [MaidenName], @Gender  = [Gender], @Birthdate = [Birthdate], 
		@AdmitDate = [AdmitDate], @AdmitTime = null, @DischargeDate = [DischargeDate], @DischargeTime = null, @AssessmentDate = [FollowUpDate], @AssessmentTime = null,
		@EncounterNumber = [EncounterNumber], @EncounterSequence = null, @RegisterNumber = [RegisterNumber], @HealthCareNumber = [HealthCareNumber],
		@NewbornChart = null, @SecondChartRegNumber = [SecondChartRegNumber], @MISCode = [MISCode], 
		@AttendingPhysician = [AttendingPhysician], @AdmittingNurseArea = [AdmittingNurseArea], @RefPhysician = [RefPhysician],
		@IsCompleted = [IsCompleted], @IsValidated = [IsValidated], @IsCompleteLevel1 = null, @IsValidLevel1 = null, @IsDeleted = [IsDeleted], @FixedChartNumber = FixedChartNumber,
		@IsCustomValidated = 1, @UniversalEpisodeIdentifier = UniversalEpisodeIdentifier, @HospitalAccountRecord = HospitalAccountRecord
	from dbo.RH_ClientInfo left outer join dbo.RH_Demographic ON dbo.RH_ClientInfo.AbstractID = dbo.RH_Demographic.AbstractID
	where dbo.RH_ClientInfo.AbstractID = @KeyID

	select top 1 @PatientID = PatientID from CM_CPI where ChartNumber = @ChartNumber  and (isnull(HospitalID, 0) = 0 OR @HospitalID = case @HospitalID when 0 then 0 else isnull(HospitalID, 0) end)
	set @DiagnosisCode = null
	set @IntervCode = null
	
	set @AppID = (case @AssessmentType when 134 then 250 when 135 then 251 when 136 then 252 when 156 then 253 when 157 then 254 end)

	set @VisitDate = (case @AppID when 250 then @AdmitDate when 252 then @AssessmentDate when 254 then @AssessmentDate else @DischargeDate end)
	set @VisitTime = null
end

else if @AppType = 4 --CCRS
begin
	set @AbstractID = @KeyID
	select @HospitalID = [HospitalID], @ICDType = null, @AssessmentType = [AA8], @LinkID = [LinkID], @InstitutionNumber = [InstitutionNumber], @ChartNumber = [ChartNumber],
		@LastName = [LastName], @FirstName = [FirstName], @MiddleName = [MiddleName], @MaidenName = [MaidenName], @Gender  = [Gender], @Birthdate = [Birthdate], 
		@AdmitDate = [AdmitDate], @AdmitTime = null, @DischargeDate = [DischargeDate], @DischargeTime = null,
		--@AssessmentDate = (case when @AssessmentType = 14500 then Z7 when @AssessmentType = 14510 then AB1b when @AssessmentType = 203626 then Z12 when @AssessmentType = 203627 then Z13 else A3 end), @AssessmentTime = null,		
		@AssessmentDate = 
			(case 
			    --PR - 07327
				when @AssessmentType in (14500, 14501, 14510) then AdmitDate
				--when @AssessmentType in (14500, 14501, 14502, 14509) then AdmitDate
				--when @AssessmentType in (14503, 14504, 14505, 14506, 14511) then A3
				when @AssessmentType in (14507, 14508, 14509) then DischargeDate
				--when @AssessmentType = 14510 and AdmitDate >= '2012/04/01' then AdmitDate 
				--when @AssessmentType = 14510 and isnull(AdmitDate, '1900/01/01') < '2012/04/01' then AB1b
				when @AssessmentType = 203626 then Z12 
				when @AssessmentType = 203627 then Z13 
				else A3 
			end), @AssessmentTime = null,
		@EncounterNumber = [EncounterNumber], @EncounterSequence = null, @RegisterNumber = [RegisterNumber], @HealthCareNumber = [HealthCareNumber],
		@NewbornChart = null, @SecondChartRegNumber = [SecondChartRegNumber], @MISCode = [MISCode], 
		@AttendingPhysician = [AttendingPhysician], @AdmittingNurseArea = [AdmittingNurseArea], @RefPhysician = [RefPhysician],
		@IsCompleted = [IsCompleted], @IsValidated = [IsValidated], @IsCompleteLevel1 = null, @IsValidLevel1 = null, @IsDeleted = [IsDeleted], @FixedChartNumber = FixedChartNumber,
		@IsCustomValidated = 1, @UniversalEpisodeIdentifier = UniversalEpisodeIdentifier, @HospitalAccountRecord = HospitalAccountRecord
	from CRS_Demographic where AbstractID = @KeyID

	select top 1 @PatientID = PatientID from CM_CPI where ChartNumber = @ChartNumber  and (isnull(HospitalID, 0) = 0 OR @HospitalID = case @HospitalID when 0 then 0 else isnull(HospitalID, 0) end)
	select @DiagnosisCode = I3a from CRS_Diagnosis where AbstractID = @KeyID
	set @IntervCode = null
	
	set @AppID = 
		(case 
			when @AssessmentType = 14501 then 470 
			when @AssessmentType = 14500 then 471 
			--when @AssessmentType = 14510 and @AssessmentDate < '2012/04/01' then 475 
			when @AssessmentType = 14510 then 470
			when @AssessmentType in (14502, 14503, 14504, 14505) then 473
			when @AssessmentType in (14507, 14508, 14509) then 474
			when @AssessmentType in (14506, 14511) then 472 
			when @AssessmentType = 203626 then 476 --ED-02133
			when @AssessmentType = 203627 then 477 --ED-02133
		end)

	set @VisitDate = @AssessmentDate 
-- 		(case 
-- 			when @AppID = 470 then @AdmitDate 
-- 			when @AppID in (472, 473) and @AssessmentType = 14502 then @AdmitDate
-- 			when @AppID = 474 and @AssessmentType = 14509 then @AdmitDate
-- 			when @AppID = 474 and @AssessmentType <> 14509 then @DischargeDate
-- 			else @AssessmentDate
-- 		end)
	set @VisitTime = null
end

if @AppType = 7 --OHMRS --PR-00603
begin
	set @AbstractID = @KeyID
	select @HospitalID = [HospitalID], @ICDType = null, @AssessmentType = [Z1], @LinkID = [LinkID], @InstitutionNumber = [InstitutionNumber], @ChartNumber = [ChartNumber],
		@LastName = [LastName], @FirstName = [FirstName], @MiddleName = [MiddleName], @MaidenName = null, @Gender  = [BB1], @Birthdate = [BB2], 
		@AdmitDate = [AdmitDate], @AdmitTime = null, @DischargeDate = [X80], @DischargeTime = null, 
		@EncounterNumber = [AA3], @EncounterSequence = null, @RegisterNumber = [RegisterNumber], @HealthCareNumber = [HealthCareNumber],
		@NewbornChart = null, @SecondChartRegNumber = [SecondChartRegNumber], @MISCode = [MISCode], 
		@AttendingPhysician = [AttendingPhysician], @AdmittingNurseArea = [AdmittingNurseArea], @RefPhysician = [RefPhysician],
		@IsCompleted = [IsCompleted], @IsValidated = [IsValidated], @IsCompleteLevel1 = null, @IsValidLevel1 = null, @IsDeleted = [IsDeleted], @FixedChartNumber = FixedChartNumber,
		@IsCustomValidated = 1, @UniversalEpisodeIdentifier = UniversalEpisodeIdentifier, @HospitalAccountRecord = HospitalAccountRecord
	from dbo.OMHRS_RecInfo inner join dbo.OMHRS_SecAA on dbo.OMHRS_RecInfo.AbstractID = dbo.OMHRS_SecAA.AbstractID 
		left outer join dbo.OMHRS_SecS on dbo.OMHRS_RecInfo.AbstractID = dbo.OMHRS_SecS.AbstractID 
		left outer join dbo.OMHRS_SecBB on dbo.OMHRS_RecInfo.AbstractID = dbo.OMHRS_SecBB.AbstractID
	where OMHRS_SecAA.AbstractID = @KeyID

	--select @AssessmentDate = [A1], @AssessmentTime = [AssessTime] from dbo.OMHRS_SecA where AbstractID = @KeyID
	select @VisitDate = [A1], @VisitTime = [AssessTime] from dbo.OMHRS_SecA where AbstractID = @KeyID

	select top 1 @PatientID = PatientID from CM_CPI where ChartNumber = @ChartNumber  and (isnull(HospitalID, 0) = 0 OR @HospitalID = case @HospitalID when 0 then 0 else isnull(HospitalID, 0) end)
	select @DiagnosisCode = I11 from OMHRS_Med_Diag where Occurrence = 1 and AbstractID = @KeyID
	select @IntervCode = IntervCode from OMHRS_Intervention where IntervOccurrence = 1 and AbstractID = @KeyID

	set @AppID = (case @AssessmentType when 200373 then 650 when 200377 then 651 when 200374 then 652 when 200376 then 653 when 200375 then 654 end) 
end

if @AppType = 8 --Cancer Care
begin
	set @AbstractID = @KeyID
	select @HospitalID = [HospitalID], @ICDType = null, @AssessmentType = null, @LinkID = [LinkID], @InstitutionNumber = [InstitutionNumber], @ChartNumber = [ChartNumber],
		@LastName = [LastName], @FirstName = [FirstName], @MiddleName = [MiddleName], @MaidenName = null, @Gender  = [Gender], @Birthdate = [BirthDate], 
		@AdmitDate = [RegisterDate], @AdmitTime = null, @DischargeDate = null, @DischargeTime = null, @AssessmentDate = null, @AssessmentTime = null,
		@EncounterNumber = null, @EncounterSequence = null, @RegisterNumber = null, @HealthCareNumber = [HealthCareNumber],
		@NewbornChart = null, @SecondChartRegNumber = null, @MISCode = null, 
		@AttendingPhysician = null, @AdmittingNurseArea = null, @RefPhysician = null, @FixedChartNumber = FixedChartNumber 
	from dbo.CC_Demographic inner join dbo.CC_DiseaseRegister on dbo.CC_Demographic.AbstractID = dbo.CC_DiseaseRegister.AbstractID 
	where CC_Demographic.AbstractID = @KeyID

	select @IsCompleted = [IsCompleted], @IsValidated = [IsValidated], @IsCompleteLevel1 = null, @IsValidLevel1 = null, @IsDeleted = [IsDeleted],
	@IsCustomValidated = 1
	from CC_RecordInfo where AbstractID = @KeyID

	select top 1 @PatientID = PatientID from CM_CPI where ChartNumber = @ChartNumber  and (isnull(HospitalID, 0) = 0 OR @HospitalID = case @HospitalID when 0 then 0 else isnull(HospitalID, 0) end)
	set @DiagnosisCode = null
	set @IntervCode = null

	set @AppID = 675
	set @VisitDate = @AdmitDate
	set @VisitTime = null
end

else if @AppType = 10 --CJRR
begin
	set @AbstractID = @KeyID	
	select @HospitalID = [HospitalID], @ICDType = 'T', @AppID = [AppID], @InstitutionNumber = [InstitutionNumber], @ChartNumber = [ChartNumber],
		@LastName = [LastName], @FirstName = [FirstName], @MiddleName = [MiddleName], @MaidenName = [MaidenName], @Gender  = [Gender], @Birthdate = [Birthdate], 
		@AdmitDate = [AdmitDate], @AdmitTime = [AdmitTime], @DischargeDate = [DischargeDate], @DischargeTime = [DischargeTime], @AssessmentDate = null, @AssessmentTime = null,
		@VisitDate = [SurgeryDate], @VisitTime = null,
		@EncounterNumber = null, @EncounterSequence = null, @RegisterNumber = null, @HealthCareNumber = [HealthCareNumber],
		@NewbornChart = null, @SecondChartRegNumber = null, @MISCode = null, 
		@AttendingPhysician = null, @AdmittingNurseArea = null, @RefPhysician = null,
		@IsCompleted = [IsCompleted], @IsValidated = [IsValidated], @IsCompleteLevel1 = null, @IsValidLevel1 = null, @IsDeleted = [IsDeleted], @FixedChartNumber = FixedChartNumber,
		@IsCustomValidated = [IsCustomValidated]
	from dbo.CJRR_Abstract 
	where RecordID = @KeyID

	select top 1 @PatientID = PatientID from CM_CPI where ChartNumber = @ChartNumber  and (isnull(HospitalID, 0) = 0 OR @HospitalID = case @HospitalID when 0 then 0 else isnull(HospitalID, 0) end)
	set @DiagnosisCode = null
	set @IntervCode = null
	
	--set @VisitDate = 
	--set @VisitTime = null
end

--Patient is Dead?
set @DeathIndicator = 0
if exists (select PatientID from CM_CPI where PatientID = @PatientID and (DeathDate > '1900/01/01' or DeathIndicator = 1))
    set @DeathIndicator = 1 

--Look for Volume
if @AppType <> 0 and isnull(@VolumeID, 0) <= 0 --check the volume is blank or not for 2.8.7.002 CHEO complain about abstract volume missing.
begin	 
    select top 1 @VolumeID = isnull(VolumeID, 0) 
    from CM_CPI_Volume 
    where PatientID = @PatientID 
	    and ([VolumeDateFrom] <= @VisitDate and @VisitDate <= [VolumenDateTo]) 
	    and (isnull(HospitalID, 0) = 0 OR @HospitalID = case @HospitalID when 0 then 0 else isnull(HospitalID, 0) end)
    order by VolumeNumber desc, VolumeID desc

    --if no range match is found it will put it in the last volume (assuming that the largest volume # is the most recent)
    if isnull(@VolumeID, 0) = 0 
	    select top 1 @VolumeID = isnull(VolumeID, 0) 
	    from CM_CPI_Volume 
	    where PatientID = @PatientID           		
		    and (isnull(HospitalID, 0) = 0 OR @HospitalID = case @HospitalID when 0 then 0 else isnull(HospitalID, 0) end)
	    order by VolumenDateTo desc, VolumeID desc
    --PR - 04984 for new one. this will not working because no record in ab_main
    --if @VolumeID > 0 
    --	exec P_updateAbstractVolume @VolumeID, @UniversalID -- I changed this SP to use the Universal already
end

delete AB_Main where UniversalID = @UniversalID
insert into AB_Main (
	    [PatientType], [UniversalID], [AppType], [AppID], [HospitalID], [LinkID], [PatientID], [VolumeID], [AbstractID],
	    [ICDType], [InstitutionNumber], [ChartNumber], [LastName], [FirstName], [MiddleName], [MaidenName], [Gender],
	    [Birthdate], [VisitDate], [VisitTime], [AdmitDate], [AdmitTime], [DischargeDate], [DischargeTime], [EncounterNumber],
	    [EncounterSequence], [RegisterNumber], [HealthCareNumber], [NewbornChart], [SecondChartRegNumber], [MISCode], [DeathIndicator],
	    [AdmittingNurseArea], [AttendingPhysician], [RefPhysician], [DiagnosisCode], [IntervCode], --PR-04833
	    [IsCompleted], [IsValidated], [IsCompleteLevel1], [IsValidLevel1], [IsDeleted], [HasTrans], [HasDAS],
	    [RegionalPatientID], [FixedChartNumber], [IsCustomValidated], [UniversalEpisodeIdentifier], [HospitalAccountRecord]
) values (
	    @PatientType, @UniversalID, @AppType, @AppID, @HospitalID, @LinkID, @PatientID, @VolumeID, @AbstractID,
	    @ICDType, @InstitutionNumber, @ChartNumber, @LastName, @FirstName, @MiddleName, @MaidenName, @Gender,
	    @Birthdate, @VisitDate, @VisitTime, @AdmitDate, @AdmitTime, @DischargeDate, @DischargeTime, @EncounterNumber,
	    @EncounterSequence, @RegisterNumber, @HealthCareNumber, @NewbornChart, @SecondChartRegNumber, @MISCode, @DeathIndicator,
	    @AdmittingNurseArea, @AttendingPhysician, @RefPhysician, @DiagnosisCode, @IntervCode, --PR-04833		
	    @IsCompleted, @IsValidated, @IsCompleteLevel1, @IsValidLevel1, @IsDeleted, @HasTrans, @HasDAS,
	    @RegionalPatientID, @FixedChartNumber, @IsCustomValidated, @UniversalEpisodeIdentifier, @HospitalAccountRecord
    )

if @AppType <> 0 --EN-00183
begin
    -- PR-02301
    select top 1 @VisitDate = VisitDate from AB_Main where PatientID = @PatientID order by VisitDate desc
    update CM_CPI set LastVisitDate = @VisitDate where PatientID = @PatientID
end

if @VolumeID > 0 --EN - 00369
begin
    exec dbo.P_UpdateVolumeDigitalIndicator @VolumeID, @HospitalID --TS-222

    --PR - 05169 I notice the @UniversalID is updated. So the volumeID in AB_Abstract is not set for some cases.
    --select top 1 @UniversalID = UniversalID from AB_Main where VolumeID = @VolumeID order by VisitDate desc
    --update CM_CPI_Volume set UniversalID = @UniversalID where VolumeID = @VolumeID and isnull(UniversalID, 0) <> @UniversalID
    declare @MaxUniversalID bigint
    select top 1 @MaxUniversalID = UniversalID from AB_Main where VolumeID = @VolumeID order by VisitDate desc
    update CM_CPI_Volume set UniversalID = @MaxUniversalID where VolumeID = @VolumeID and isnull(UniversalID, 0) <> @MaxUniversalID
    --PR - 04984
    if @AppType in (1, 2, 5)
        exec P_updateAbstractVolume @VolumeID, @UniversalID -- I changed this SP to use the Universal already
end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [U_CC_Demographic]
   (@AbstractID    [int],
    @LinkID        [int],
    @AppID [int],
    @HospitalID    [int],
    @ProvinceNumber        [int],
    @InstitutionNumber     [int],
    @ChartNumber   [varchar](50),
    @LastName      [varchar](50),
    @FirstName     [varchar](50),
    @MiddleName    [varchar](50),
    @MaidenName    [varchar](50),
    @Gender        [int],
    @BirthDate     [datetime],
    @PostalCode    [varchar](50),
    @ResidenceCode         [int],
    @DeathIndicator        [int],
    @DeathDate     [datetime],
    @HealthCareNumber      [varchar](50),
    @HCNVersion    [varchar](50),
    @HCNProvince   [int],
    @ResponsiblePayment    [int], 
--    @HostChartNumber       [varchar](50), - PR - 03282
    @City  	[varchar] (32), 	  --PR - 03332 New fields added
    @Province	[int],
    @Country	[int],
    @FixedChartNumber [varchar](50),
	@UniversalEpisodeIdentifier [varchar](50),
	@HospitalAccountRecord [varchar](50))

AS 
UPDATE [dbo].[CC_Demographic] 
SET        
   -- [LinkID]              = @LinkID,  PR - 03293 it was updating wrong 
    [HospitalID]            = @HospitalID,
    [ProvinceNumber]        = @ProvinceNumber,
    [InstitutionNumber]     = @InstitutionNumber,
    [ChartNumber]           = @ChartNumber,
    [LastName]              = @LastName,
    [FirstName]             = @FirstName,
    [MiddleName]            = @MiddleName,
    [MaidenName]            = @MaidenName,
    [Gender]                = @Gender,
    [BirthDate]             = @BirthDate,
    [PostalCode]            = @PostalCode,
    [ResidenceCode]         = @ResidenceCode,
    [DeathIndicator]        = @DeathIndicator,
    [DeathDate]             = @DeathDate,
    [HealthCareNumber]      = @HealthCareNumber,
    [HCNVersion]            = @HCNVersion,
    [HCNProvince]           = @HCNProvince,
    [ResponsiblePayment]    = @ResponsiblePayment,
--    [HostChartNumber]       = @HostChartNumber,     PR - 03282
    [City]		    = @City,  		   --PR - 03332 New fields added
    [Province]		    = @Province,
    [Country]		    = @Country,
    [FixedChartNumber]	= @FixedChartNumber,
    [UniversalEpisodeIdentifier]	= @UniversalEpisodeIdentifier,
    [HospitalAccountRecord]	= @HospitalAccountRecord
WHERE 
   ( [AbstractID]           = @AbstractID)

-- if @AppID = 675 -- It's the Registration  PR - 03293 it was updating wrong 
--         UPDATE [dbo].[CC_Demographic] 
--         SET      
--                  [HospitalID]            = @HospitalID,
--                  [ProvinceNumber]        = @ProvinceNumber,
--                  [InstitutionNumber]     = @InstitutionNumber,
--                  [ChartNumber]           = @ChartNumber,
--                  [LastName]              = @LastName,
--                  [FirstName]             = @FirstName,
--                  [MiddleName]            = @MiddleName,
--                  [MaidenName]            = @MaidenName,
--                  [Gender]                = @Gender,
--                  [BirthDate]             = @BirthDate,
--                  [PostalCode]            = @PostalCode,
--                  [ResidenceCode]         = @ResidenceCode,
--                  [DeathIndicator]                = @DeathIndicator,
--                  [DeathDate]             = @DeathDate,
--                  [HealthCareNumber]      = @HealthCareNumber,
--                  [HCNVersion]            = @HCNVersion,
--                  [HCNProvince]           = @HCNProvince,
--                  [ResponsiblePayment]    = @ResponsiblePayment,
--                  [HostChartNumber]       = @HostChartNumber 
--         WHERE 
--                 ([LinkID]               = @LinkID)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO






CREATE     PROCEDURE [U_CC_NDFPFromDisease]
   (@LinkID          [int],
    @MaidenName    	[varchar](35),
    @LastName              [varchar](40),
    @MiddleName            [varchar](15),
    @FirstName             [varchar](35),
    @BirthDate             [datetime],
    @Gender                [int],
    @HCNProvince   	[int],
    @HealthCareNumber      [varchar](12),
    @HCNVersion            [varchar](2),
    @PostalCode            [varchar](6),
    @City		   [varchar](32),   -- PR - 03332
    @Province	           [int],
    @Country		   [int],
    @ResidenceCode         [int],
    @DeathInd 		   [int],
    @DeathDate		   [datetime],
    @InstitutionNumber     [int],
    @HospID		[int] = 0)
  
AS 

   UPDATE CC_Demographic SET
           MaidenName = @MaidenName, 
           LastName = @LastName, 
           MiddleName = @MiddleName, 
           FirstName = @FirstName, 
           BirthDate = @BirthDate, 
           Gender = @Gender,
           HealthCareNumber = @HealthCareNumber, 
           HCNProvince = @HCNProvince, 
           HCNVersion = @HCNVersion, 
           PostalCode = @PostalCode, 
	   City = @City,   			-- PR - 03332
    	   Province = @Province, 	  
    	   Country = @Country, 
	   ResidenceCode = @ResidenceCode,
	   DeathIndicator = @DeathInd,
	   DeathDate = @DeathDate,
	   InstitutionNumber   = @InstitutionNumber
   WHERE CC_Demographic.LinkID = @LinkID and AppID = 676  
   AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
    




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE     PROCEDURE [U_CJRR_Abstract]
	(@RecordID                   [int]
	,@AppID                      [int]
	,@HospitalID                 [int]
	,@LinkID					 [int]
	,@InterventionCIHI			 [varchar] (50) 
	,@ChartNumber                [varchar] (50) 
	--,@VolumeID                   [int]
	,@RecordType                 [int]
	,@FiscalSurgeryYear			 [int] 
	,@HospitalProvinceCode		 [int]
	,@RecordSubmitObjective      [int]
	,@InstitutionNumber			 [int]
	,@SurgeryDate                [datetime] 
	,@ProviderNumber			 [int] 
	,@SurgeonID                  [varchar] (50)
	,@SurgeonLastName            [varchar] (50)
	,@SurgeonFirstName           [varchar] (50)
	,@HealthCareNumber           [varchar] (50)
	,@HCNVersion                 [varchar] (50)
	,@HCNProvince                [int] 
	,@Gender                     [int] 
	,@BirthDate                  [datetime] 
	,@MaidenName                 [varchar]  (50)
	,@LastName                   [varchar]  (50)
	,@MiddleName                 [varchar]  (50)
	,@FirstName                  [varchar]  (50)
	,@PostalCode                 [varchar] (50)
	,@SideLocation               [int]
	,@ReplacementType            [int]
	,@PrimaryProcedureType		 [int]
	,@DiagnosisGrouping			 [int]
	,@RevisionReason			 [int]
	,@CoderNumber                [int] 
	--,@IsDeleted                  [int] 
	,@IsValidated                [int] 
	,@IsCompleted                [int] 
	--,@IsSubmited				 [int] 
	,@IsCorrected                [int] 
	--,@CIHIDateSent			[datetime] 
	,@MainDiagnosisCode          [int] 
    ,@InterventionCode           [int] 
    ,@AbstractInstNumber		 [int] 
	,@AdmitDate					 [datetime]
	,@AdmitTime					 [datetime]
	,@DischargeDate				 [datetime]
	,@DischargeTime				 [datetime] 
	,@FixedChartNumber			 [varchar](50)  
	,@IsCustomValidated			 [int]     
	)
AS 

--If isnull(@IsDeleted, 0) = 0   set @IsDeleted = 2 
--If isnull(@IsCorrected, 0) = 0 set @IsCorrected = 1 
--If isnull(@IsSubmitted, 0) = 0  set @IsSubmitted = 2

set @LastName = replace(@LastName, '''''', '''')
update [CJRR_Abstract] 
set 
	 [AppID]				= @AppID
	,[HospitalID]			= @HospitalID
	,[LinkID]				= @LinkID
	,[MainDiagnosisCode]	= @MainDiagnosisCode
	,[InterventionCode]		= @InterventionCode
	,[InterventionCIHI]		= @InterventionCIHI
	,[ChartNumber]			= @ChartNumber
	--,[VolumeID]				= @VolumeID
	,[RecordType]			= @RecordType
	,[FiscalSurgeryYear]	= @FiscalSurgeryYear
	,[HospitalProvinceCode] = @HospitalProvinceCode
	,[RecordSubmitObjective]= @RecordSubmitObjective
    ,[AbstractInstNumber]	= @AbstractInstNumber
	,[InstitutionNumber]	= @InstitutionNumber
	,[AdmitDate]			= @AdmitDate
	,[AdmitTime]			= @AdmitTime
	,[DischargeDate]		= @DischargeDate
	,[DischargeTime]		= @DischargeTime
	,[SurgeryDate]			= @SurgeryDate
	,[ProviderNumber]		= @ProviderNumber
	,[SurgeonID]			= @SurgeonID
	,[SurgeonLastName]		= @SurgeonLastName
	,[SurgeonFirstName]		= @SurgeonFirstName
	,[HealthCareNumber]		= @HealthCareNumber
	,[HCNVersion]			= @HCNVersion
	,[HCNProvince]			= @HCNProvince
	,[Gender]				= @Gender
	,[BirthDate]			= @BirthDate
	,[MaidenName]			= @MaidenName
	,[LastName]				= @LastName
	,[MiddleName]			= @MiddleName
	,[FirstName]			= @FirstName
	,[PostalCode]			= @PostalCode
	,[SideLocation]			= @SideLocation
	,[ReplacementType]		= @ReplacementType
	,[PrimaryProcedureType]	= @PrimaryProcedureType
	,[DiagnosisGrouping]	= @DiagnosisGrouping
	,[RevisionReason]		= @RevisionReason
	,[CoderNumber]			= @CoderNumber
	--,[IsDeleted]			= @IsDeleted
	,[IsValidated]			= @IsValidated
	,[IsCompleted]			= @IsCompleted
	--,[IsSubmited]			= @IsSubmitted
	,[IsCorrected]			= @IsCorrected
	--,[CIHIDateSent]		= @CIHIDateSent
	,[FixedChartNumber]		= @FixedChartNumber
	,[IsCustomValidated]	= @IsCustomValidated
where 
   ([RecordID]    		= @RecordID)

--if exists (select * from CJRR_Abstract where RecordID = @RecordID and isnull(VolumeID, 0) <= 0)
--begin
--     --9854: Update the Volume Number.
--	declare @P as int 
--	declare @V as int
--	select top 1 @P = PatientID from CM_CPI where ChartNumber = @ChartNumber and (isnull(HospitalID, 0) = 0 or @HospitalID = case @HospitalID when 0 then 0 else isnull(HospitalID, 0) end) --PR-04125
--	select top 1 @V = isnull(VolumeID, 0) from CM_CPI_Volume where PatientID = @P and (([VolumeDateFrom] <= @SurgeryDate) and (@SurgeryDate <= [VolumenDateTo])) order by VolumenDateTo desc, VolumeID desc
--	if isnull(@V, 0) = 0 
--		select top 1 @V = isnull(VolumeID, 0) from CM_CPI_Volume where PatientID = @P order by VolumenDateTo desc, VolumeID desc

--	exec P_UpdateAbstractVolume @V, 0, @RecordID -- 13419: Abst ID is now the 3rd parameter.
--end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create  procedure [U_CL_PullListID]
    @OldID varchar(50),
    @NewID varchar(50)
as
    Update CL_PullList
    set PullListID = @NewID
    where PullListID = @OldID
        and isnull(PullListStatus, 0) = 0

    return(@@rowcount)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is called by the Save Method of the CPI Control
CREATE    PROCEDURE [U_CM_CPI]
   (@PatientID             [int],
    @ChartNumber           [varchar](10),
    @MaidenName    [varchar](35),
    @LastName              [varchar](40),
    @MiddleName            [varchar](15),
    @FirstName             [varchar](35),
    @DeathDate             [datetime],
    @Gender                [int],
    @BirthDate             [datetime],
    @BirthDateEstimated    [int],
    @BirthPlace            [varchar](20),
    @LanguageCode  [int],
    @EducationLevel        [int],
    @MaritalStatus         [int],
    @LivingArrangement     [int],
    @PrimaryAddress        [varchar](60),
    @PostalCode            [varchar](12),
    @ResidenceCode         [int],
    @ResidenceType         [int],
    @PrimaryPhone  [varchar](15),
    @HCNProvince   [int],
    @HealthCareNumber      [varchar](12),
    @HCNVersion            [varchar](2),
    @InsurCompany1         [int],
    @InsurPolicy1          [varchar](15),
    @InsurCompany2         [int],
    @InsurPolicy2          [varchar](15),
    @Occupation            [int],
    @SocialInsurNumber     [varchar](9),
    @OptionField1          [int],
    @OptionField2          [int],
    @Secret                [int],
    @DuplicateChart        [varchar](10),
    @MothersChart          [varchar](10),
    @Salutation            [varchar](10),
    @BirthName             [varchar](35),
    @CellPhone             [varchar](15),
    @FaxNumber             [varchar](15), 
    @EMail                 [varchar](50), 
    @LinkProviderNumber    [int],
    @PrimaryAddress2       [varchar](60),
    @City                  [varchar](30), 
    @Province              [int], 
    @Country               [int],
    @UniqiueLifetimeID     [varchar](20),
    @GroupNum1             [varchar](50), 
    @GroupNum2             [varchar](50), 
    @WSIB          	   [varchar](50),
    @DiagMethod 	[int], 
    @FirstDiagDate 	[datetime], 
    @FutureDate 		[datetime], 
    @MedReferralDate 	[datetime], 
    @RadReferralDate 	[datetime], 
    @SupCareReferralDate [datetime],
    @HospitalID		   [int],
    @LabelPrinted		[int],
    @MasterChart		[int],
    @DeathIndicator		[int],
    @LastVisitDate		[datetime],
    @SensitivityLevel 		[int] ,
    @RegionalPatientID	[varchar](50),
    @IAR_ConsentFlag	[int],
    @FixedChartNumber	[varchar](50),
    @LockedChart        int,
    @HighRisk           int,
    @ROILegalComments   [varchar](500)
)
AS 
UPDATE [CM_CPI] 
SET         [ChartNumber]          = @ChartNumber,
    [HospitalID]	   = @HospitalID,
    [LabelPrinted]		= @LabelPrinted,
    [UniqiueLifetimeID]    = @UniqiueLifetimeID,
    [MaidenName]           = @MaidenName,
    [LastName]             = replace(@LastName, '''''', ''''),
    [MiddleName]           = @MiddleName,
    [FirstName]            = @FirstName,
    [DeathDate]            = @DeathDate,
    [DeathIndicator]	   = @DeathIndicator,
    [Gender]               = @Gender,
    [BirthDate]            = @BirthDate,
    [BirthDateEstimated]   = @BirthDateEstimated,
    [BirthPlace]           = @BirthPlace,
    [LanguageCode] = @LanguageCode,
    [EducationLevel]       = @EducationLevel,
    [MaritalStatus]                = @MaritalStatus,
    [LivingArrangement]    = @LivingArrangement,
    [PrimaryAddress]       = @PrimaryAddress,
    [PostalCode]           = @PostalCode,
    [ResidenceCode]        = @ResidenceCode,
    [ResidenceType]        = @ResidenceType,
    [PrimaryPhone]         = @PrimaryPhone,
    [HCNProvince]          = @HCNProvince,
    [HealthCareNumber]     = @HealthCareNumber,
    [HCNVersion]           = @HCNVersion,
    [InsurCompany1]        = @InsurCompany1,
    [InsurPolicy1]         = @InsurPolicy1,
    [InsurCompany2]        = @InsurCompany2,
    [InsurPolicy2]         = @InsurPolicy2,
    [Occupation]           = @Occupation,
    [SocialInsurNumber]    = @SocialInsurNumber,
    [OptionField1]         = @OptionField1,
    [OptionField2]         = @OptionField2,
    [LinkProviderNumber]   = @LinkProviderNumber,
    [Secret]               = @Secret,
    [MasterChart]		= @MasterChart,
    [DuplicateChart]               = @DuplicateChart,
    [MothersChart]         = @MothersChart,    [Salutation]           = @Salutation,
    [BirthName]            = @BirthName,
    [CellPhone]            = @CellPhone,
    [FaxNumber]            = @FaxNumber, 
    [EMail]                        = @EMail, 
    [PrimaryAddress2]      = @PrimaryAddress2,
    [City]                         = @City, 
    [Province]             = @Province, 
    [Country]              = @Country,
    [GroupNum1]            = @GroupNum1,
    [GroupNum2]            = @GroupNum2,
    [WSIB]                 = @WSIB,
    [DiagMethod] 		= @DiagMethod,
    [FirstDiagDate] 	= @FirstDiagDate,
    [FutureDate]		= @FutureDate,
    [MedReferralDate]	= @MedReferralDate,
    [RadReferralDate]	= @RadReferralDate,
    [SupCareReferralDate] = @SupCareReferralDate,
    [LastVisitDate]       = @LastVisitDate,
    [SensitivityLevel]	= @SensitivityLevel,
	[RegionalPatientID] = @RegionalPatientID,
	[IAR_ConsentFlag]	= @IAR_ConsentFlag,
	[FixedChartNumber]	= @FixedChartNumber,
	[LockedChart]       = @LockedChart,
    [HighRisk]          = @HighRisk,
    [ROILegalComments]  = @ROILegalComments
WHERE 
   ([PatientID]    = @PatientID)

   --NP-00025
   if isnull(@HospitalID, 0) <> 0 
	update CM_CPI_Volume set HospitalID = @HospitalID where PatientID = @PatientID
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE  PROCEDURE [U_CM_CPI_Transcription]
	(@PatientID		[int],
	 @BirthPlace		[varchar](20),
	 @PrimaryAddress 	[varchar](60),
	 @PrimaryPhone 	[varchar](15),
	 @AlternateAddress 	[varchar](60),
	 @PhysicianNumber 	[varchar](45),
	 @PhysicianPhone 	[varchar](15))
AS 
UPDATE [CM_CPI] 
SET 	 [BirthPlace]	 	= @BirthPlace,
	 [PrimaryAddress]	= @PrimaryAddress,
	 [PrimaryPhone]	 	= @PrimaryPhone,
	 [AlternateAddress]	= @AlternateAddress,
	 [PhysicianNumber]	= @PhysicianNumber,
	 [PhysicianPhone]	= @PhysicianPhone
WHERE 	([PatientID]	= @PatientID)



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- This is called by the Save Method of the CPI Volumes Form
CREATE PROCEDURE [U_CM_CPI_Volume]
	(@PatientID		[int],
	 @VolumeID		[int],
	 @VolumeNumber	[varchar](12),
     @VolumeType    int,
	 @BarCodeVolume 	[varchar](50),
	 @DateFrom		[datetime],
	 @DateTo		[datetime],
	 @PermLoc		[int],
	 @LinkVolume		[int],
	 @VolumeBox		[varchar](50),
	 @HasInpatient		[int],
	 @HasSDS		[int],
	 @HasOutpatient	[int],
	 @HasAmcare		[int],
	 @HasMicroFilm		[int],
	 @MircoFilmNum	[varchar](50),
	 @HasOption1		[int],
	 @HasOption2		[int],
	 @HasOption3		[int],
	 @HasOption4		[int],
	 @HasComments	[varchar](255),
	 @Location		[int],
	 @SubVolume		[int],
	 @HospitalID		[int],
	 @LabelPrinted		[int],
     @CLPreviousLocation [int],
     @UniversalID   [bigint],
     @DigitalIndicator int,
     @DestructionDate datetime = null
     )
AS 

UPDATE [CM_CPI_Volume]
SET  	 [PatientID] 		= @PatientID,
	 [HospitalID]		= @HospitalID,
	 [LabelPrinted]		= @LabelPrinted,
	 [VolumeNumber]	= @VolumeNumber,
	 [VolumeType]	= @VolumeType,
	 [BarCodeVolume]	= @BarCodeVolume,
	 [VolumeDateFrom]	= @DateFrom,
	 [VolumenDateTo]	= @DateTo,
	 [PermLocation]		= @PermLoc,
	 [CLLinkedVolume]	= @LinkVolume,
	 [CLBoxNumber]		= @VolumeBox,
	 [CLInpatient]		= @HasInpatient,
	 [CLSDS]		= @HasSDS,
	 [CLOutpatient]		= @HasOutpatient,
	 [CLAmcare]		= @HasAmcare,
	 [CLMicroFilm]		= @HasMicroFilm,
	 [CLMircoFilmNum] 	= @MircoFilmNum,
	 [CLOption1]		= @HasOption1,
	 [CLOption2]		= @HasOption2,
	 [CLOption3]		= @HasOption3,
	 [CLOption4]		= @HasOption4,
	 [CLComments]		= @HasComments,
	 [CLCurrentLocation]	= @Location,
	 [SubVolume]		= @SubVolume,
     [CLPreviousLocation] = @CLPreviousLocation,
     [UniversalID] = @UniversalID,
     [DigitalIndicator] = @DigitalIndicator,
     [DestructionDate]  = @DestructionDate 
WHERE 
	([VolumeID]	= @VolumeID)


if isnull(@DestructionDate, 0) > '1900/01/01'
begin
    update AB_Abstract set VolumeID = null where VolumeID = @VolumeID
    update AB_Main set VolumeID = null where VolumeID = @VolumeID
end
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [U_CM_CPIFromAbstract]
   (@ChartNumber           [varchar](10),
    @MaidenName    [varchar](35),
    @LastName              [varchar](40),
    @MiddleName            [varchar](15),
    @FirstName             [varchar](35),
    @BirthDate             [datetime],
    @BirthDateEstimated    [int],
    @Gender                [int],
    @MaritalStatus         [int],
    @PostalCode            [varchar](6),
    @ResidenceCode         [int],
    @HCNProvince   [int],
    @HealthCareNumber      [varchar](12),
    @HCNVersion            [varchar](2),
    @Secret                [int],
    @UniqiueLifetimeID     [varchar](10),
    @HospID		   [int] = 0)  
AS 
    --20719
    declare @PatientID int
    set @PatientID = (select top 1 PatientID from CM_CPI where ChartNumber = @ChartNumber 
                        and (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
                    order by HospitalID desc)

    UPDATE dbo.CM_CPI SET
           MaidenName = @MaidenName, 
           LastName = @LastName, 
           MiddleName = @MiddleName, 
           FirstName = @FirstName, 
           BirthDate = @BirthDate, 
           BirthDateEstimated = @BirthDateEstimated, 
           Gender = @Gender,
           MaritalStatus = @MaritalStatus, 
           --PR - 05485 Allow US 5 digit postal code.
           PostalCode = (case when len(PostalCode) = 5 and isnumeric(PostalCode) = 1    
                                and (select top 1 c.cihivalue from LU_CPI_Country c where c.code = country) = 'US' 
                              then PostalCode 
                              else @PostalCode end), 
           ResidenceCode = @ResidenceCode, 
           HealthCareNumber = @HealthCareNumber, 
           HCNProvince = @HCNProvince, 
           HCNVersion = @HCNVersion, 
           Secret = @Secret, 
           UniqiueLifetimeID = @UniqiueLifetimeID
    where PatientID = @PatientID 
   --WHERE ChartNumber = @ChartNumber
   --AND (ISNULL(HospitalID, 0) = 0 OR ISNULL(HospitalID, 0) = @HospID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [U_CM_CPIFromAmcare]
   (@ChartNumber           [varchar](10),
    @MaidenName    [varchar](35),
    @LastName              [varchar](40),
    @MiddleName            [varchar](15),
    @FirstName             [varchar](35),
    @BirthDate             [datetime],
    @BirthDateEstimated    [int],
    @MaritalStatus         [int],
    @PostalCode            [varchar](6),
    @ResidenceCode         [int],
    @HCNProvince   [int],
    @HealthCareNumber      [varchar](12),
    @HCNVersion            [varchar](2),
    @Secret                [int],
    @LanguageCode  [int],
    @EducationLevel        [int],
    @Occupation            [int],
    @LivingArrangement     [int],
    @ResidenceType         [int],
    @UniqiueLifetimeID     [varchar](10),
    @HospID		   [int])
AS 
    --20719
    declare @PatientID int
    set @PatientID = (select top 1 PatientID from CM_CPI where ChartNumber = @ChartNumber 
                        and (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
                    order by HospitalID desc)

   UPDATE dbo.CM_CPI SET
           MaidenName = @MaidenName, 
           LastName = @LastName, 
           MiddleName = @MiddleName, 
           FirstName = @FirstName, 
           BirthDate = @BirthDate, 
           BirthDateEstimated = @BirthDateEstimated, 
           MaritalStatus = @MaritalStatus, 
           --PR - 05485 Allow US 5 digit postal code.
           PostalCode = (case when len(PostalCode) = 5 and isnumeric(PostalCode) = 1    
                                and (select top 1 c.cihivalue from LU_CPI_Country c where c.code = country) = 'US' 
                              then PostalCode 
                              else @PostalCode end), 
           --PostalCode = @PostalCode, 
           ResidenceCode = @ResidenceCode, 
           HealthCareNumber = @HealthCareNumber, 
           HCNProvince = @HCNProvince, 
           HCNVersion = @HCNVersion, 
           Secret = @Secret, 
           LanguageCode = @LanguageCode, 
           EducationLevel = @EducationLevel, 
           Occupation = @Occupation, 
           LivingArrangement = @LivingArrangement, 
           ResidenceType = @ResidenceType, 
           UniqiueLifetimeID = @UniqiueLifetimeID
    where PatientID = @PatientID 
--   WHERE ChartNumber = @ChartNumber
--   AND (ISNULL(HospitalID, 0) = 0 OR ISNULL(HospitalID, 0) = @HospID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [U_CM_CPIFromVisit]
   (@CareType              [int],
    @AdmitDate             [datetime],
    @DischargeDate [datetime],
    @ChartNumber           [varchar](10),
    @UniqiueLifetimeID     [varchar](10),
    @Secret                [int],
    @MaidenName    [varchar](35),
    @LastName              [varchar](40),
    @MiddleName            [varchar](15),
    @FirstName             [varchar](35),
    @BirthDate             [datetime],
    @BirthDateEstimated    [int],
    @Gender                [int],
    @MaritalStatus         [int],
    @HCNProvince   [int],
    @HealthCareNumber      [varchar](12),
    @HCNVersion            [varchar](2),
    @PostalCode            [varchar](6),
    @ResidenceCode         [int],
    @ResidenceType         [int],
    @LanguageCode  [int],
    @EducationLevel        [int],
    @Occupation            [int],
    @LivingArrangement     [int],
    @SocialInsurNumber     [varchar](9),
    @InsurPolicy1          [varchar](15),
    @GroupNum1             [varchar](15),
    @WSIB          [varchar](15),
    @HospID		[int] = 0,
   @PrimaryAddress 	[varchar](60) = '', 
   @PrimaryAddress2 	[varchar](60) = '', 
   @PrimaryPhone 	[varchar](20) = '',
   @City		[varchar] (32) = '', --PR - 03332: CCO- Added new fields 
   @Province	        [int] = 0,
   @Country		[int] = 0)
AS 
SELECT DischargeDate AS [VisitDate] INTO #Temp FROM AB_Abstract WHERE (ChartNumber = @ChartNumber AND IsDeleted = 2 AND CareType <> 5 AND (ISNULL(HospitalID, 0) = 0 OR ISNULL(HospitalID, 0) = @HospID)) 
INSERT INTO #Temp SELECT AdmitDate AS [VisitDate] FROM AB_Abstract WHERE (ChartNumber = @ChartNumber AND IsDeleted = 2 AND CareType = 5 AND (ISNULL(HospitalID, 0) = 0 OR ISNULL(HospitalID, 0) = @HospID)) 
INSERT INTO #Temp SELECT AdmitDate AS [VisitDate] FROM AB_Main WHERE (ChartNumber = @ChartNumber AND IsDeleted = 2 AND AppType = 9 AND (ISNULL(HospitalID, 0) = 0 OR ISNULL(HospitalID, 0) = @HospID)) 
INSERT INTO #Temp SELECT AdmitDate AS [VisitDate] FROM CRS_Demographic WHERE (ChartNumber = @ChartNumber AND IsDeleted = 2 AND AA8 = 14501 AND (ISNULL(HospitalID, 0) = 0 OR ISNULL(HospitalID, 0) = @HospID)) 
--This does not check Is Deleted flag.
INSERT INTO #Temp SELECT AdmitDate AS [VisitDate] FROM OMHRS_SecAA WHERE (ChartNumber = @ChartNumber AND (Z1 = 200373 or Z1 = 200377) AND (ISNULL(HospitalID, 0) = 0 OR ISNULL(HospitalID, 0) = @HospID)) 
INSERT INTO #Temp SELECT AdmitDate AS [VisitDate] FROM RH_ClientInfo WHERE (ChartNumber = @ChartNumber AND IsDeleted = 2 AND AssessmentType = 134 AND (ISNULL(HospitalID, 0) = 0 OR ISNULL(HospitalID, 0) = @HospID))
INSERT INTO #Temp SELECT ISNULL(AdmitDate, '1950/01/01') AS [VisitDate] FROM CR_Visit WHERE AbstractID IN (SELECT AbstractID FROM CR_Demographic WHERE ChartNumber = @ChartNumber AND IsDeleted = 2)
-- PR - 03304
INSERT INTO #Temp SELECT RegisterDate AS [VisitDate] FROM CC_DiseaseRegister dise, CC_Demographic demo, CC_RecordInfo reco  
			WHERE (dise.AbstractID = demo.AbstractID and demo.AbstractID = reco.AbstractID ) and 
			(ChartNumber = @ChartNumber AND IsDeleted = 2 AND (ISNULL(HospitalID, 0) = 0 OR ISNULL(HospitalID, 0) = @HospID))
--20719
declare @PatientID int
set @PatientID = (select top 1 PatientID from CM_CPI where ChartNumber = @ChartNumber 
                    and (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
                  order by HospitalID desc)

   IF @CareType = 1 OR @CareType = 2       -- ABSCARE
   BEGIN
           IF (SELECT TOP 1 * FROM #Temp ORDER BY [VisitDate] DESC) = @DischargeDate
                   UPDATE dbo.CM_CPI SET
                           UniqiueLifetimeID = @UniqiueLifetimeID,
                           Secret = @Secret,
                           MaidenName = @MaidenName, 
                           LastName = @LastName, 
                           MiddleName = @MiddleName, 
                           FirstName = @FirstName, 
                           BirthDate = @BirthDate, 
                           BirthDateEstimated = @BirthDateEstimated, 
                           Gender = @Gender,
                           MaritalStatus = @MaritalStatus, 
                           HealthCareNumber = @HealthCareNumber, 
                           HCNProvince = @HCNProvince, 
                           HCNVersion = @HCNVersion, 
                           --PR - 05485 Allow US 5 digit postal code.
                           PostalCode = (case when len(PostalCode) = 5 and isnumeric(PostalCode) = 1    
                                                and (select top 1 c.cihivalue from LU_CPI_Country c where c.code = country) = 'US' 
                                              then PostalCode 
                                              else @PostalCode end), 
                           --PostalCode = @PostalCode, 
                           ResidenceCode = @ResidenceCode,
		                PrimaryAddress = @PrimaryAddress,
		                PrimaryAddress2 = @PrimaryAddress2,
		                PrimaryPhone = @PrimaryPhone
                    where PatientID = @PatientID
           ----20719
           --        WHERE ChartNumber = @ChartNumber
		   --AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
   END

   ELSE IF @CareType = 3 -- REHAB  
   BEGIN
           IF (SELECT TOP 1 * FROM #Temp ORDER BY [VisitDate] DESC) = @AdmitDate
                   UPDATE dbo.CM_CPI SET
                           Secret = @Secret,
                           MaidenName = @MaidenName, 
                           LastName = @LastName, 
                           MiddleName = @MiddleName, 
                           FirstName = @FirstName, 
                           BirthDate = @BirthDate, 
                           BirthDateEstimated = @BirthDateEstimated, 
                           Gender = @Gender,
                           HealthCareNumber = @HealthCareNumber, 
                           HCNProvince = @HCNProvince, 
                           HCNVersion = @HCNVersion, 
                           --PR - 05485 Allow US 5 digit postal code.
                           PostalCode = (case when len(PostalCode) = 5 and isnumeric(PostalCode) = 1    
                                                and (select top 1 c.cihivalue from LU_CPI_Country c where c.code = country) = 'US' 
                                              then PostalCode 
                                              else @PostalCode end), 
                           --PostalCode = @PostalCode, 
                           LanguageCode = @LanguageCode
                    where PatientID = @PatientID
           ----20719
           --         WHERE ChartNumber = @ChartNumber
		   --AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
   END

   ELSE IF @CareType = 4 -- CCRS
   BEGIN
           IF (SELECT TOP 1 * FROM #Temp ORDER BY [VisitDate] DESC) = @AdmitDate
                   UPDATE dbo.CM_CPI SET
                           Secret = @Secret,
                           MaidenName = @MaidenName, 
                           LastName = @LastName, 
                           MiddleName = @MiddleName, 
                           FirstName = @FirstName, 
                           BirthDate = @BirthDate, 
                           BirthDateEstimated = @BirthDateEstimated, 
                           Gender = @Gender,
                           MaritalStatus = @MaritalStatus, 
                           HealthCareNumber = @HealthCareNumber, 
                           HCNProvince = @HCNProvince, 
                           HCNVersion = @HCNVersion, 
                           --PR - 05485 Allow US 5 digit postal code.
                           PostalCode = (case when len(PostalCode) = 5 and isnumeric(PostalCode) = 1    
                                                and (select top 1 c.cihivalue from LU_CPI_Country c where c.code = country) = 'US' 
                                              then PostalCode 
                                              else @PostalCode end) 
                           --PostalCode = @PostalCode
                    where PatientID = @PatientID
           ----20719
           --        WHERE ChartNumber = @ChartNumber
		   --AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
   END

   ELSE IF @CareType = 5 -- AMCARE 
   BEGIN
           IF (SELECT TOP 1 * FROM #Temp ORDER BY [VisitDate] DESC) = @AdmitDate   
	begin
                   UPDATE dbo.CM_CPI SET
                           UniqiueLifetimeID = @UniqiueLifetimeID,
                           Secret = @Secret, 
                           MaidenName = @MaidenName, 
                           LastName = @LastName, 
                           MiddleName = @MiddleName, 
                           FirstName = @FirstName, 
                           BirthDate = @BirthDate, 
                           BirthDateEstimated = @BirthDateEstimated, 
                           MaritalStatus = @MaritalStatus, 
                           HealthCareNumber = @HealthCareNumber, 
                           HCNProvince = @HCNProvince, 
                           HCNVersion = @HCNVersion, 
                           --PR - 05485 Allow US 5 digit postal code.
                           PostalCode = (case when len(PostalCode) = 5 and isnumeric(PostalCode) = 1    
                                                and (select top 1 c.cihivalue from LU_CPI_Country c where c.code = country) = 'US' 
                                              then PostalCode 
                                              else @PostalCode end), 
                           --PostalCode = @PostalCode, 
                           ResidenceCode = @ResidenceCode, 
                           LanguageCode = @LanguageCode, 
                           EducationLevel = @EducationLevel, 
                           Occupation = @Occupation, 
                           LivingArrangement = @LivingArrangement, 
                           ResidenceType = @ResidenceType
                    where PatientID = @PatientID
           ----20719
           --        WHERE ChartNumber = @ChartNumber
		--AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

                   if @AdmitDate > '2003/04/01' 
                        UPDATE dbo.CM_CPI SET Gender = @Gender 
                        where PatientID = @PatientID
           ----20719
          --         WHERE ChartNumber = @ChartNumber 
		--AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
	end
   END

   ELSE IF @CareType = 6 -- CLINIC
   BEGIN
           IF (SELECT TOP 1 * FROM #Temp ORDER BY [VisitDate] DESC) = @AdmitDate   
           BEGIN
                   UPDATE dbo.CM_CPI SET
                           MaidenName = @MaidenName, 
                           LastName = @LastName, 
                           MiddleName = @MiddleName, 
                           FirstName = @FirstName, 
                           BirthDate = @BirthDate, 
                           Gender = @Gender,
                           HealthCareNumber = @HealthCareNumber, 
                           HCNVersion = @HCNVersion, 
                           SocialInsurNumber = @SocialInsurNumber,
                           WSIB = @WSIB
                    where PatientID = @PatientID
           ----20719
           --        WHERE ChartNumber = @ChartNumber
		   --AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

                   UPDATE dbo.CM_CPI SET
                           InsurPolicy1 = @InsurPolicy1
                    where PatientID = @PatientID AND InsurPolicy2 <> @InsurPolicy1     
           ----20719
           --        WHERE ChartNumber = @ChartNumber AND InsurPolicy2 <> @InsurPolicy1                      
		   --AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)

                   UPDATE dbo.CM_CPI 
                   SET GroupNum1 = @GroupNum1
                   where PatientID = @PatientID AND GroupNum2 <> @GroupNum1
           ----20719
           --        WHERE ChartNumber = @ChartNumber AND GroupNum2 <> @GroupNum1
		   --AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
           END
   END

   ELSE IF @CareType = 7 -- OMHRS
   BEGIN
           IF (SELECT TOP 1 * FROM #Temp ORDER BY [VisitDate] DESC) = @AdmitDate
                   UPDATE dbo.CM_CPI SET
                           Secret = @Secret,
                           MaidenName = @MaidenName, 
                           LastName = @LastName, 
                           MiddleName = @MiddleName, 
                           FirstName = @FirstName, 
                           BirthDate = @BirthDate, 
                           BirthDateEstimated = @BirthDateEstimated, 
                           Gender = @Gender,
                           MaritalStatus = @MaritalStatus, 
                           HealthCareNumber = @HealthCareNumber, 
                           HCNProvince = @HCNProvince, 
                           HCNVersion = @HCNVersion, 
                           --PR - 05485 Allow US 5 digit postal code.
                           PostalCode = (case when len(PostalCode) = 5 and isnumeric(PostalCode) = 1    
                                                and (select top 1 c.cihivalue from LU_CPI_Country c where c.code = country) = 'US' 
                                              then PostalCode 
                                              when isnull(@PostalCode, '') = '' then PostalCode
                                              else @PostalCode end) 
                         --PostalCode = @PostalCode
                   where PatientID = @PatientID
           ----20719
           --        WHERE ChartNumber = @ChartNumber
		   --AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
   END


   ELSE IF @CareType = 8 -- Cancer Care  'PR - 03304
   BEGIN
           IF (SELECT TOP 1 * FROM #Temp ORDER BY [VisitDate] DESC) = @AdmitDate
                   UPDATE dbo.CM_CPI SET
                           MaidenName = @MaidenName, 
                           LastName = @LastName, 
                           MiddleName = @MiddleName, 
                           FirstName = @FirstName, 
                           BirthDate = @BirthDate, 
                           Gender = @Gender,
                           HealthCareNumber = @HealthCareNumber, 
                           HCNProvince = @HCNProvince, 
                           HCNVersion = @HCNVersion, 
                           --PR - 05485 Allow US 5 digit postal code.
                           PostalCode = (case when len(PostalCode) = 5 and isnumeric(PostalCode) = 1    
                                                and (select top 1 c.cihivalue from LU_CPI_Country c where c.code = country) = 'US' 
                                              then PostalCode 
                                              else @PostalCode end), 
                           --PostalCode = @PostalCode,
		 	               ResidenceCode = @ResidenceCode,
			               City = @City, 			--PR - 03332: CCO- Added new fields 
			               Province = @Province, 
   			               Country = @Country		
                        where PatientID = @PatientID
           ----20719
           --        WHERE ChartNumber = @ChartNumber
		   --AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
   END


   ELSE IF @CareType = 9 -- Non Abstract
   BEGIN
           IF (SELECT TOP 1 * FROM #Temp ORDER BY [VisitDate] DESC) = @AdmitDate
                   UPDATE dbo.CM_CPI SET
                           MaidenName = @MaidenName, 
                           LastName = @LastName, 
                           MiddleName = @MiddleName, 
                           FirstName = @FirstName, 
                           BirthDate = @BirthDate, 
                           Gender = @Gender,
                           HealthCareNumber = @HealthCareNumber
                    where PatientID = @PatientID
           ----20719
           --      WHERE ChartNumber = @ChartNumber
		   --AND (ISNULL(HospitalID, 0) = 0 OR @HospID = case @HospID when 0 then 0 else ISNULL(HospitalID, 0) end)
   END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE PROCEDURE [U_CMV_ClinicalPathway]
	(@HospitalID		[int],
	 @RecordID 		[int],
	 @ClinicPatientID 	[int],
	 @ClinicPatLName 	[varchar](50),
	 @ClinicPatFName 	[varchar](50),
	 @ClinicPatDOB 	[datetime],
	 @ClinicAbstractID 	[int],
	 @ClinicInstNumber 	[int],
	 @ClinicAdmitDate	 [datetime] ,
	 @ClinicDischDate	 [datetime],
	 @ClinicAssessDate	 [datetime],
	 @ClinicPath	 	[int],
	 @ClinicLOS	 	[int],
	 @ActualLOS	 	[int],
	 @StartDate	 	[datetime],
	 @EndDate	 	[datetime],
	 @IntervDate	 	[datetime])

AS 
UPDATE [CMV_ClinicalPathway] 
SET  	 [ClinicPatientID]	 	 = @ClinicPatientID,
	 [ClinicPatLName]	 = @ClinicPatLName,
	 [ClinicPatFName]	 = @ClinicPatFName,
	 [ClinicPatDOB]	 	 = @ClinicPatDOB,
	 [ClinicAbstractID]	 = @ClinicAbstractID,
	 [ClinicInstNumber]	 = @ClinicInstNumber,
	 [ClinicAdmitDate] 	 = @ClinicAdmitDate,
	 [ClinicDischDate]	 = @ClinicDischDate,
	 [ClinicAssessDate]	 = @ClinicAssessDate,
	 [ClinicPath]	 	 = @ClinicPath,
	 [ClinicLOS]	 	 = @ClinicLOS,
	 [ActualLOS]	 	 = @ActualLOS,
	 [StartDate]	 	 = @StartDate,
	 [EndDate]	 	 = @EndDate,
	 [IntervDate]	 	 = @IntervDate 

WHERE 
	( [RecordID]	 	= @RecordID)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [U_CR_Demographic]
   (@AbstractID            [int],
    @AmCareID              [int],
    @ChartNumber           [varchar](10),
    @HealthCareNumber      [varchar](12),
    @HCNVersion            [varchar](2),
    @MaidenName    [varchar](35),
    @LastName              [varchar](40),
    @MiddleName            [varchar](15),
    @FirstName             [varchar](35),
    @Gender                [int],
    @BirthDate             [datetime],
    @IsCompleted           [int],
    @IsValidated           [int],
    @IsSubmitted           [int],
    @IsCorrected           [int],
    @IsDeleted             [int],
    @BillDate              [datetime],
    @BillNumber            [varchar](8),
    @HCNProvince   [int])

AS 
UPDATE [dbo].[CR_Demographic] 
SET         [AmCareID]             = @AmCareID,
    [IsCorrected]          = @IsCorrected,
    [IsSubmited]           = @IsSubmitted,
    [IsValidated]          = @IsValidated,
    [IsCompleted]          = @IsCompleted,
    [IsDeleted]            = @IsDeleted,
    [ChartNumber]          = @ChartNumber,
    [HealthCareNumber]     = @HealthCareNumber,
    [HCNVersion]           = @HCNVersion,
    [MaidenName]           = @MaidenName,
    [LastName]             = @LastName,
    [MiddleName]           = @MiddleName,
    [FirstName]            = @FirstName,
    [Gender]               = @Gender,
    [BirthDate]            = @BirthDate,
    [BillDate]             = @BillDate,
    [BillNumber]           = @BillNumber,
    [HCNProvince]          = @HCNProvince
WHERE ([AbstractID]                = @AbstractID)




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [U_CR_ErrorClaimHD]
	(@CErrorID	 	[int],
	 @AbstractID	 	[int],
	 @HealthCareNumber 	[varchar](12),
	 @HCNProvince 	[varchar](2),
	 @LastName	 	[varchar](9),
	 @FirstName	 	[varchar](5),
	 @Gender		[varchar](1),
	 @Error1	 	[varchar](3),
	 @Error2	 	[varchar](3),
	 @Error3	 	[varchar](3),
	 @Error4	 	[varchar](3),
	 @Error5	 	[varchar](3))
AS 
UPDATE [dbo].[CR_ErrorClaimHD] SET
	 [HealthCareNumber] 	= @HealthCareNumber,
	 [HCNProvince]		= @HCNProvince,
	 [LastName]		= @LastName,
	 [FirstName]		= @FirstName,
	 [Gender]		= @Gender,
	 [Error1]			= @Error1,
	 [Error2]			= @Error2,
	 [Error3]			= @Error3,
	 [Error4]			= @Error4,
	 [Error5]			= @Error5
WHERE [CErrorID] = @CErrorID



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [U_CR_ErrorsHeader]
	(@HErrorID		[int],
	 @MOHOfficeCode 	[varchar](1),
	 @Operator	 	[varchar](6),
	 @GroupNumber 	[varchar](4),
	 @ProviderNumber 	[varchar](6),
	 @ProviderSpecialty 	[varchar](2),
	 @ProcessDate	 	[datetime],
	 @StationNumber 	[varchar](3),
	 @FileName		[varchar](50),
	 @HDR1Cnt		[int],
	 @HDR2Cnt		[int],
	 @ItemCnt		[int],
	 @MsgCnt		[int])
AS  
--The Update will do the other half (fed by the Footer). The Insert did the Header Half of the fields.
UPDATE [dbo].[CR_ErrorsHeader] 
SET  	 [FileName]	 	= @FileName,
	 [HDR1Cnt]	 	= @HDR1Cnt,
	 [HDR2Cnt]	 	= @HDR2Cnt,
	 [ItemCnt]	 	= @ItemCnt,
	 [MsgCnt]	 	= @MsgCnt 
WHERE 
	([HErrorID]	 	= @HErrorID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [U_CR_ReconHeader]
	(@HReconID	 	[int],
	 @MOHOfficeCode 	[varchar](1),
	 @GroupNumber 	[varchar](4),
	 @ProviderNumber 	[varchar](12),
	 @ProviderSpecialty 	[varchar](2),
	 @PaymentDate 	[datetime],
	 @PayeeName 		[varchar](30),
	 @TotalPayable	 	[money],
	 @ChequeNumber 	[varchar](9),
	 @BillingAgent	 	[varchar](30),
	 @Address1	 	[varchar](30),
	 @Address2	 	[varchar](30),
	 @Address3	 	[varchar](30),
	 @AmtAdjustment 	[money],
	 @AmtAdvances 	[money],
	 @AmtReductions 	[money],
	 @AmtOther		[money],
	 @TransCode	 	[varchar](2),
	 @ChequeIndicator 	[varchar](1),
	 @TransDate	 	[datetime],
	 @TransAmount 	[money],
	 @TransMessage 	[varchar](50),
	 @MinistryMessage 	[text])
AS 
UPDATE [dbo].[CR_ReconHeader] 
SET  	 [AmtAdjustment]	 	= @AmtAdjustment,
	 [AmtAdvances]	 	= @AmtAdvances,
	 [AmtReductions]	= @AmtReductions,
	 [AmtOther]	 	= @AmtOther,
	 [TransCode]	 	= @TransCode,
	 [ChequeIndicator]	= @ChequeIndicator,
	 [TransDate]	 	= @TransDate,
	 [TransAmount]	 	= @TransAmount,
	 [TransMessage]	 	= @TransMessage,
	 [MinistryMessage]	= @MinistryMessage 
WHERE 
	([HReconID]	 	= @HReconID)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--select FieldID, Header_User, ParamOrder, SortOrder from U_UsersFields where AppID = 472 and UserID = 1 and ParamProcID = 1 order by paramOrder
CREATE  PROCEDURE [U_CRS_Demographic]
   (@HospitalID		   [int],
    @AbstractID            [int],
    @LinkID                [int],
    @AA8                   [int],
    @AA1                   [varchar](20),
    @ChartNumber           [varchar](10),
    @RegisterNumber        [int],
    @AdmitDate             [datetime],
    @Z7                    [datetime],
    @A3                    [datetime],
    @DischargeDate         [datetime],
    @AB1b          [datetime],
    @MaidenName    [varchar](35),
    @LastName              [varchar](40),
    @MiddleName            [varchar](15),
    @FirstName             [varchar](35),
    @AdmittingNurseArea    [int],
    @RoomNumber            [varchar](10),
    @Gender                [int],
    @BirthDate             [datetime],
    @BirthDateEstimated    [int],
    @AA4a          [int],
    @MaritalStatus         [int],
    @HealthCareNumber      [varchar](12),
    @HCNProvince   [int],
    @InstitutionNumber     [int],
    @AB2a          [int],
    @AB2c          [int],
    @InstitutionFrom       [int],
    @R3a                   [int],
    @InstitutionTo         [int],
    @Z1                    [int],
    @IsCompleted           [int],
    @IsValidated           [int], 
    @IsSubmited            [int], 
    @SiteNumber            [int],
    @CoderNumber           [int],
    @HCNVersion            [varchar](2),
    @ZA6b          [int], 
    @ZAB1          [datetime], 
    @ZR4                   [datetime],
    @InterfaceDate         [datetime], 
    @InterfaceTime         [datetime], 
    @InterfaceCoder        [int], 
    @InputDate             [datetime],
    @InputTime             [datetime], 
    @DataEntryCoder        [int], 
    @FinishDate            [datetime], 
    @FinishTime            [datetime],
    @Secret                [int], 
    @TSIDate               [datetime], 
    @TSITime               [datetime], 
    @TSICoder              [int],
    @EncounterNumber [varchar](50), 
    @SecondChartRegNumber [varchar](50), 
    @MISCode 		[int], 
    @AttendingPhysician 	[int], 
    @RefPhysician 	[int],
    @Z12		[datetime],
    @Z13		[datetime],
    @IsCorrected int,
    @Y3 int,
    @AA4b int,
    @AA4c int,
    @FixedChartNumber [varchar](50),
    @NextAssessmentDate datetime,
	@UniversalEpisodeIdentifier [varchar](50),
    @HospitalAccountRecord varchar(50),
    @R3c    int
)

AS
If isnull(@IsSubmited, 0) = 0  set @IsSubmited = 2  -- PR - 03723

--PR - 04367 the HL7 does not populate field Z1. Submission use Z1.
if isnull(@Z1, 0) = 0
begin
    --PR - 05912
    /*
    set @Z1 = (case @AA8 when 14500 then 15356 --DEMO 00
                         when 14501 then 15351 --ADMIT 01
                         when 14502 then 15353 --FULL 01
                         when 14503 then 15353 --FULL 02
                         when 14504 then 15353 --FULL 03
                         when 14505 then 15353 --FULL 04
                         when 14506 then 15354 --QUART 05
                         when 14511 then 15354 --QUART 10
                         when 14507 then 15357 --DISCH 06
                         when 14508 then 15357 --DISCH 07
                         when 14509 then 15357 --DISCH 08
                         when 14510 then 15352 --RE_ENTR 09
            			 when 203626 then 203621 --UPDATE
			             when 203627 then 203622 --PROJECT
                         else @Z1
               end)
    */               
    set @Z1 = (case @AA8 when 14500 then 15356 --DEMO 00
                         when 14501 then 18539 --ADMIT 01
                         when 14502 then 18540 --FULL 01
                         when 14503 then 18540 --FULL 02
                         when 14504 then 18540 --FULL 03
                         when 14505 then 18540 --FULL 04
                         when 14506 then 18541 --QUART 05
                         when 14511 then 18541 --QUART 10
                         when 14507 then 18543 --DISCH 06
                         when 14508 then 18543 --DISCH 07
                         when 14509 then 18543 --DISCH 08
                         when 14510 then 18539 --RE_ENTR 09
            			 when 203626 then 18544 --UPDATE
			             when 203627 then 18545 --PROJECT
                         else @Z1
               end)
end

if isnull(@Y3, 0) = 0 set @Y3 = 15769    --PR - 05912

UPDATE [dbo].[CRS_Demographic] 
SET [HospitalID]	   = @HospitalID,        
    [AA8]                  = @AA8,
    [AA1]                  = @AA1,
    [ChartNumber]          = @ChartNumber,
    [RegisterNumber]       = @RegisterNumber,
    [ZA6b]                 = @ZA6b, 
    [AdmitDate]            = @AdmitDate,
    [ZAB1]                 = @ZAB1, 
    [Z7]                   = @Z7,
    [A3]                   = @A3,
    [DischargeDate]        = @DischargeDate,
    [ZR4]                  = @ZR4,
    [AB1b]                 = @AB1b,
    [MaidenName]           = @MaidenName,
    [LastName]             = @LastName,
    [MiddleName]           = @MiddleName,
    [FirstName]            = @FirstName,
    [AdmittingNurseArea]   = @AdmittingNurseArea,
    [RoomNumber]           = @RoomNumber,
    [Gender]               = @Gender,
    [BirthDate]            = @BirthDate,
    [BirthDateEstimated]   = @BirthDateEstimated,
    [AA4a]                 = @AA4a,
    [MaritalStatus]                = @MaritalStatus,
    [HealthCareNumber]     = @HealthCareNumber,
    [HCNVersion]           = @HCNVersion,
    [HCNProvince]          = @HCNProvince,
    [InstitutionNumber]    = @InstitutionNumber,
    [SiteNumber]           = @SiteNumber, 
    [CoderNumber]          = @CoderNumber,
    [AB2a]                 = @AB2a,
    [AB2c]                 = @AB2c,
    [InstitutionFrom]              = @InstitutionFrom,
    [R3a]                  = @R3a,
    [InstitutionTo]                = @InstitutionTo,
    [Z1]                   = @Z1,
    [IsSubmited]           = @IsSubmited, 
    [IsValidated]          = @IsValidated, 
    [IsCompleted]          = @IsCompleted,
    [InterfaceDate]                = @InterfaceDate,
    [InterfaceTime]                = @InterfaceTime,
    [InterfaceCoder]               = @InterfaceCoder,
    [InputDate]            = @InputDate,
    [InputTime]            = @InputTime,
    [DataEntryCoder]       = @DataEntryCoder,
    [FinishDate]           = @FinishDate,
    [FinishTime]           = @FinishTime,
    [Secret]               = @Secret,
    [TSIDate]              = @TSIDate, 
    [TSITime]              = @TSITime, 
    [TSICoder]             = @TSICoder,
    [EncounterNumber]		= @EncounterNumber,
    [SecondChartRegNumber]	= @SecondChartRegNumber,
    [MISCode]			= @MISCode,
    [AttendingPhysician]	= @AttendingPhysician,
    [RefPhysician]		= @RefPhysician,
    [Z12]			= @Z12,
    [Z13]			= @Z13,
    IsCorrected     = @IsCorrected,
    Y3              = @Y3,
    AA4b            = @AA4b,
    AA4c            = @AA4c,
    [FixedChartNumber]	= @FixedChartNumber,
    NextAssessmentDate  = @NextAssessmentDate,
	[UniversalEpisodeIdentifier] = @UniversalEpisodeIdentifier,
    [HospitalAccountRecord] = @HospitalAccountRecord,
    [R3c]           = @R3c
WHERE 
   ([AbstractID]           = @AbstractID)

   --IF @AA8 = 14500 OR @AA8 = 14501
   IF @AA8 = 14501 --PR-01427
   begin
       UPDATE [dbo].[CRS_Demographic] 
       SET  [HospitalID]	       = @HospitalID,
		    [RegisterNumber]       = (case when AdmitDate = @AdmitDate then @RegisterNumber else [RegisterNumber] end),
            [MaidenName]           = @MaidenName,
            [LastName]             = @LastName,
            [MiddleName]           = @MiddleName,
            [FirstName]            = @FirstName,
            [Gender]               = @Gender,
            [BirthDate]            = @BirthDate,
            [BirthDateEstimated]   = @BirthDateEstimated,
            [MaritalStatus]        = @MaritalStatus,
            [HealthCareNumber]     = (case when AA8 = 203626 and datediff(day, '2014/03/31', Z12) > 0 then [HealthCareNumber] else @HealthCareNumber end), --ED - 02990
            [HCNVersion]           = (case when AA8 = 203626 and datediff(day, '2014/03/31', Z12) > 0  then [HCNVersion]      else @HCNVersion end),       --ED - 02990
            [HCNProvince]          = (case when AA8 = 203626 and datediff(day, '2014/03/31', Z12) > 0  then [HCNProvince]     else @HCNProvince end),      --ED - 02990
            [InstitutionNumber]    = @InstitutionNumber,
            [SiteNumber]           = @SiteNumber,
            [Secret]               = @Secret
       WHERE ([LinkID] = @LinkID)

       UPDATE [dbo].[CRS_Demographic] 
       SET  [UniversalEpisodeIdentifier] = @UniversalEpisodeIdentifier,
            HospitalAccountRecord = @HospitalAccountRecord
       WHERE ([LinkID] = @LinkID) and AdmitDate = @AdmitDate and AA8 not in (14501, 14510)

	end
    else IF @AA8 = 14510 --ED - 03107
       UPDATE [dbo].[CRS_Demographic] 
       SET  [RegisterNumber]       = @RegisterNumber,
			[UniversalEpisodeIdentifier] = @UniversalEpisodeIdentifier,
            [HospitalAccountRecord] = @HospitalAccountRecord
       WHERE ([LinkID] = @LinkID) and AdmitDate = @AdmitDate and AA8 <> 14501
     --ED - 02990
    IF @AA8 = 203626 and datediff(day, '2014/03/31', @Z12) > 0 and isnull(@HealthCareNumber, '') > 0
    begin
        UPDATE [dbo].[CRS_Demographic] 
        SET  [HealthCareNumber]     = @HealthCareNumber, 
             [HCNVersion]           = @HCNVersion,       
             [HCNProvince]          = @HCNProvince
        WHERE ([LinkID] = @LinkID) and @AA8 <> 203626
    end

	--Some Client CCRS IsCurrent Flag is messed up.
	declare @ID int
	if not exists (select AbstractID from [dbo].[CRS_Demographic] where LinkID = @LinkID and Iscurrent = 1)
	begin
		set @ID = (select top 1 AbstractID from [dbo].[CRS_Demographic] where LinkID = @LinkID order by isnull(isnull(DischargeDate, A3), AdmitDate) desc, AA8 desc)
		if @ID > 0
			UPDATE [dbo].[CRS_Demographic] SET IsCurrent = 1 WHERE AbstractID = @ID
	end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--This is to sync the demographic changes that 
CREATE PROCEDURE [U_CRS_SyncDemoChange]
	(@AbstractID 		[int],
	@LinkID			[int],
	@AdmitDate	 	[datetime],
	@NewADate		[datetime],
	@DischargeDate		[datetime],
	@NewDDate		[datetime],
	@Gender                	[int],
	@BirthDate             	[datetime],
	@BirthDateEstimated    	[int],
	@HealthCareNumber      	[varchar](12),
	@HCNVersion            	[varchar](2),
	@HCNProvince   		[int],
    @RegisterNumber        	[int],	
	@ZA6b          		[int]
)
AS

--PR - 04067 Demographic cannot change original AB1, R4, A6b for demographic assessment
if isdate(@NewADate) = 1 
	update CRS_Demographic set AdmitDate = @NewADate 
    where LinkID = @LinkID and AdmitDate = @AdmitDate and (AA8 in (14501, 14502, 14503, 14504, 14505, 14506, 14511, 14507, 14508, 14509)) 
        and AA8 NOT IN (14500)
    --where LinkID = @LinkID and AdmitDate = @AdmitDate and (AA8 in (14500, 14501, 14502, 14503, 14504, 14505, 14506, 14511, 14507, 14508, 14509)) 

if isdate(@NewDDate) = 1 
	update CRS_Demographic set DischargeDate = @NewDDate 
    where LinkID = @LinkID and DischargeDate = @DischargeDate and AA8 NOT IN (14500)
    --where LinkID = @LinkID and DischargeDate = @DischargeDate 

--PR-01427
if isnull(@Gender, 0) > 0  
	update CRS_Demographic set Gender = @Gender 
    where LinkID = @LinkID and AA8 NOT IN (14500)
    --where LinkID = @LinkID  

if isdate(@BirthDate) = 1 
	update CRS_Demographic set BirthDate = @BirthDate 
    where LinkID = @LinkID and AA8 NOT IN (14500)
    --where LinkID = @LinkID 

if isnull(@BirthDateEstimated, 0) > 0 
	update CRS_Demographic set BirthDateEstimated = @BirthDateEstimated 
    where LinkID = @LinkID  and AA8 NOT IN (14500)
    --where LinkID = @LinkID  

if len(isnull(@HealthCareNumber, '')) > 0 
	update CRS_Demographic set HealthCareNumber = @HealthCareNumber 
    where LinkID = @LinkID  and AA8 NOT IN (14500)
    --where LinkID = @LinkID  

if len(isnull(@HCNVersion, '')) > 0 
	update CRS_Demographic set HCNVersion = @HCNVersion 
    where LinkID = @LinkID  and AA8 NOT IN (14500)
    --where LinkID = @LinkID  

if isnull(@HCNProvince, 0) > 0 
	update CRS_Demographic set HCNProvince = @HCNProvince 
    where LinkID = @LinkID  and AA8 NOT IN (14500)
    --where LinkID = @LinkID  

if isnull(@ZA6b, 0) > 0 
	update CRS_Demographic set RegisterNumber = @ZA6b 
    where LinkID = @LinkID and RegisterNumber = @RegisterNumber 
		and AA8 NOT IN (14500) -- PR - 03734  NOT FOR Change demographics
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
--This is to sync the Admission Date / Re-Entry Date with the subsequent Assessments if the date changes
CREATE  PROCEDURE [U_CRS_SyncRecords]
	(@AbstractID 	[int],
	 @LinkID		[int],
	 @AA8			[int],
	 @AdmitDate	 	[datetime])
AS

DECLARE @RDate as datetime

--IF @AA8 = 14500 --Demo Change
-- DO NOTHING FOR THIS HERE. IT WILL BE HANDLED IN IT'S OWN SP (U_CRS_SyncDemoChange)
--BEGIN
--	UPDATE CRS_Demographic SET AdmitDate = @AdmitDate WHERE LinkID = @LinkID AND AA8 = 14501
--	IF ISDATE(@RDate) <> 1 
--		--Do them all, but Re-Entry (it doesn't retain the Admit Date
--		UPDATE CRS_Demographic SET AdmitDate = @AdmitDate WHERE LinkID = @LinkID AND (AA8 = 14502 OR  AA8 = 14503 OR AA8 = 14504 OR AA8 = 14505 OR AA8 = 14506 OR AA8 = 14511 OR AA8 = 14507 OR  AA8 = 14508 OR AA8 = 14509) 
--	ELSE
--	BEGIN
--		--Qtr & Full Assessments
--		UPDATE CRS_Demographic SET AdmitDate = @AdmitDate WHERE LinkID = @LinkID AND (AA8 = 14502 OR  AA8 = 14503 OR AA8 = 14504 OR AA8 = 14505 OR AA8 = 14506 OR AA8 = 14511) 
--		AND A3 < @RDate
--		--Discharges
--		UPDATE CRS_Demographic SET AdmitDate = @AdmitDate WHERE LinkID = @LinkID AND (AA8 = 14507 OR  AA8 = 14508 OR AA8 = 14509) 
--		AND DischargeDate < @RDate
--	END
--END
declare @LastAdmitDate as datetime  --2.x-00103

--ED - 02756 The Admission date cannot be corrected if the record is submited.
IF @AA8 = 14501 
BEGIN
	--PR-02858
	declare @AA1 as varchar(20)
	select @AA1 = AA1 from CRS_Demographic where AbstractID = @LinkID 
	update CRS_Demographic set AA1 = @AA1 where LinkID = @LinkID and AA8 <> 14500 and isnull(AA1, '') <> @AA1

    SELECT top 1 @RDate = (case when AB1b is null then AdmitDate else AB1b end) FROM CRS_Demographic WHERE LinkID = @LinkID AND AA8 = 14510 ORDER BY (case when AB1b is null then AdmitDate else AB1b end) ASC
    	
	IF ISDATE(@RDate) <> 1 
	BEGIN
		-- Make sure that there isn't another Admission after the discharge w/out assessment
		SELECT top 1 @RDate = AdmitDate FROM CRS_Demographic WHERE LinkID = @LinkID AND AbstractID <> @AbstractID AND AbstractID <> LinkID AND AA8 = 14501 ORDER BY [AdmitDate] ASC			
		IF ISDATE(@RDate) <> 1 
			--Do them all, but Re-Entry, it doesn't retain the Admit Date
			UPDATE CRS_Demographic SET AdmitDate = @AdmitDate 
			WHERE LinkID = @LinkID AND (AA8 = 14500 OR AA8 = 14502 OR  AA8 = 14503 OR AA8 = 14504 OR AA8 = 14505 OR AA8 = 14506 OR AA8 = 14511 OR AA8 = 14507 OR  AA8 = 14508 OR AA8 = 14509 or AA8 = 203626) 
			    and isnull(AdmitDate, getdate()) <> @AdmitDate  --PR - 05366 if the date match, we do not need to update
			    and IsSubmited <> 1 --ED - 02756
		ELSE
		BEGIN
			--Qtr & Full Assessments
			UPDATE CRS_Demographic SET AdmitDate = @AdmitDate WHERE LinkID = @LinkID AND (AA8 = 14502 OR  AA8 = 14503 OR AA8 = 14504 OR AA8 = 14505 OR AA8 = 14506 OR AA8 = 14511) 
			AND A3 < @RDate and IsSubmited <> 1 --ED - 02756
			    and isnull(AdmitDate, getdate()) <> @AdmitDate  --PR - 05366 if the date match, we do not need to update
			--Discharges
			UPDATE CRS_Demographic SET AdmitDate = @AdmitDate WHERE LinkID = @LinkID AND (AA8 = 14507 OR  AA8 = 14508 OR AA8 = 14509) 
		    	AND DischargeDate < @RDate and IsSubmited <> 1 --ED - 02756
                and isnull(AdmitDate, getdate()) <> @AdmitDate  --PR - 05366 if the date match, we do not need to update			--Demo Changes
			UPDATE CRS_Demographic SET AdmitDate = @AdmitDate WHERE LinkID = @LinkID AND (AA8 = 14500) 
	    		AND Z7 < @RDate and IsSubmited <> 1 --ED - 02756
    			and isnull(AdmitDate, getdate()) <> @AdmitDate  --PR - 05366 if the date match, we do not need to update
		    --Update
            UPDATE CRS_Demographic SET AdmitDate = @AdmitDate 
	        WHERE LinkID = @LinkID AND (AA8 = 203626) 
    	        AND Z12 < @RDate and IsSubmited <> 1 --ED - 02756
		END
	END

	ELSE
	BEGIN
		--Qtr & Full Assessments
		UPDATE CRS_Demographic SET AdmitDate = @AdmitDate WHERE LinkID = @LinkID AND (AA8 = 14502 OR  AA8 = 14503 OR AA8 = 14504 OR AA8 = 14505 OR AA8 = 14506 OR AA8 = 14511) 
		    AND A3 < @RDate and IsSubmited <> 1 --ED - 02756
		    and isnull(AdmitDate, getdate()) <> @AdmitDate  --PR - 05366 if the date match, we do not need to update
		--Discharges
		UPDATE CRS_Demographic SET AdmitDate = @AdmitDate WHERE LinkID = @LinkID AND (AA8 = 14507 OR  AA8 = 14508 OR AA8 = 14509) 
		AND DischargeDate < @RDate and IsSubmited <> 1 --ED - 02756
		--Demo Changes
		UPDATE CRS_Demographic SET AdmitDate = @AdmitDate WHERE LinkID = @LinkID AND (AA8 = 14500) 
		AND Z7 < @RDate --and IsSubmited <> 1 --ED - 02756
		--Update
        UPDATE CRS_Demographic SET AdmitDate = @AdmitDate 
	    WHERE LinkID = @LinkID AND (AA8 = 203626) 
    	    AND Z12 < @RDate and IsSubmited <> 1 --ED - 02756
	END
END

ELSE IF @AA8 = 14510 --Re-Entry Date Change
BEGIN
    SELECT top 1 @RDate = isnull(AB1b, AdmitDate) FROM CRS_Demographic WHERE LinkID = @LinkID AND AA8 = 14510 AND isnull(AB1b, AdmitDate) > @AdmitDate ORDER BY isnull(AB1b, AdmitDate) ASC
    --2.x-0103
    SELECT top 1 @LastAdmitDate = max(AdmitDate) FROM CRS_Demographic WHERE LinkID = @LinkID AND AA8 in (14501, 14510) AND AdmitDate < @AdmitDate
    
	IF ISDATE(@RDate) <> 1 --No Date Later than the passed, So check for Earlier one
	BEGIN
	    --PR - 05366 disable code to check precious re-entry
		--SELECT top 1  @RDate = AB1b FROM CRS_Demographic WHERE LinkID = @LinkID AND AA8 = 14510 AND AB1b < @AdmitDate ORDER BY [AB1b] DESC
		--IF ISDATE(@RDate) <> 1 -- No Date Earlier, so that means it's the only Re-Entry.
		--BEGIN
			--Qtr & Full Assessments
			UPDATE CRS_Demographic SET AdmitDate = @AdmitDate WHERE LinkID = @LinkID AND (AA8 = 14502 OR  AA8 = 14503 OR AA8 = 14504 OR AA8 = 14505 OR AA8 = 14506 OR AA8 = 14511) 
			AND IsSubmited <> 1 --ED - 02756
            and (A3 > @AdmitDate or (A3 = @AdmitDate and AbstractID > @AbstractID))
			--2.x-0103 Patient discharge and re-entry at the same date. break into two steps
			--Discharges
			UPDATE CRS_Demographic 
			SET AdmitDate = @AdmitDate 
			WHERE LinkID = @LinkID AND (AA8 = 14507 OR  AA8 = 14508 OR AA8 = 14509) 
			    AND DischargeDate > @AdmitDate and IsSubmited <> 1 --ED - 02756
			--    AND DischargeDate >= @AdmitDate and IsSubmited <> 1 --ED - 02756
		    if exists (select * from CRS_Demographic where LinkID = @LinkID AND AA8 in (14507, 14508, 14509) and AdmitDate = @LastAdmitDate)
		        UPDATE CRS_Demographic 
		        SET AdmitDate = @AdmitDate 
		        WHERE LinkID = @LinkID AND (AA8 = 14507 OR  AA8 = 14508 OR AA8 = 14509) 
		            AND DischargeDate = @AdmitDate and IsSubmited <> 1 --ED - 02756
                    and AbstractID > @AbstractID
			    
			--Demo Changes
			UPDATE CRS_Demographic SET AdmitDate = @AdmitDate WHERE LinkID = @LinkID AND (AA8 = 14500) 
			AND Z7 >= @AdmitDate and IsSubmited <> 1 --ED - 02756
			--Update
            UPDATE CRS_Demographic SET AdmitDate = @AdmitDate 
		    WHERE LinkID = @LinkID AND (AA8 = 203626) 
	    	    AND Z12 >= @AdmitDate and IsSubmited <> 1 --ED - 02756
		--END
		    --PR - 05366 Not need to update assessment before re-entry
		/*
		ELSE	-- There is an Earlier Date Pick all Assessments in the Range RDate -> Admit
		BEGIN
			--Qtr & Full Assessments
			UPDATE CRS_Demographic SET AdmitDate = @AdmitDate WHERE LinkID = @LinkID AND (AA8 = 14502 OR  AA8 = 14503 OR AA8 = 14504 OR AA8 = 14505 OR AA8 = 14506 OR AA8 = 14511) 
			AND (A3 > @RDate AND A3 <= @AdmitDate)
			--Discharges
			UPDATE CRS_Demographic SET AdmitDate = @AdmitDate WHERE LinkID = @LinkID AND (AA8 = 14507 OR  AA8 = 14508 OR AA8 = 14509) 
			AND (DischargeDate > @RDate AND DischargeDate <= @AdmitDate)
			--Demo Changes
			UPDATE CRS_Demographic SET AdmitDate = @AdmitDate WHERE LinkID = @LinkID AND (AA8 = 14500) 
			AND (Z7 > @RDate AND Z7 <= @AdmitDate)
			
		END
		*/
	END

	ELSE	-- There is a Date Later then the Passed Pick all Assessments in the Range Admit -> RDate
	BEGIN
        --2.x-0103
        SELECT top 1 @LastAdmitDate = max(AdmitDate) FROM CRS_Demographic WHERE LinkID = @LinkID AND AA8 in (14501, 14510) AND AdmitDate < @AdmitDate
		--Qtr & Full Assessments
		UPDATE CRS_Demographic SET AdmitDate = @AdmitDate WHERE LinkID = @LinkID AND (AA8 = 14502 OR  AA8 = 14503 OR AA8 = 14504 OR AA8 = 14505 OR AA8 = 14506 OR AA8 = 14511) 
		AND (A3 > @AdmitDate or (A3 = @AdmitDate and AbstractID > @AbstractID)) AND A3 < @RDate and IsSubmited <> 1 --ED - 02756
        --2.x-0103 Patient discharge and re-entry at the same date. cha
		--Discharges
		UPDATE CRS_Demographic SET AdmitDate = @AdmitDate WHERE LinkID = @LinkID AND (AA8 = 14507 OR  AA8 = 14508 OR AA8 = 14509) 
		AND (DischargeDate > @AdmitDate AND DischargeDate < @RDate) and IsSubmited <> 1 --ED - 02756
		--AND (DischargeDate >= @AdmitDate AND DischargeDate < @RDate) and IsSubmited <> 1 --ED - 02756
		if exists (select * from CRS_Demographic where LinkID = @LinkID AND AA8 in (14507, 14508, 14509) and AdmitDate = @LastAdmitDate)
		    UPDATE CRS_Demographic 
		    SET AdmitDate = @AdmitDate 
		    WHERE LinkID = @LinkID AND (AA8 = 14507 OR  AA8 = 14508 OR AA8 = 14509) 
		        AND DischargeDate = @AdmitDate 
                and AbstractID < @AbstractID
                and IsSubmited <> 1 --ED - 02756

		--Demo Changes
		UPDATE CRS_Demographic SET AdmitDate = @AdmitDate WHERE LinkID = @LinkID AND (AA8 = 14500) 
		AND (Z7 >= @AdmitDate AND Z7 < @RDate) --and IsSubmited <> 1 --ED - 02756
		--Update
        UPDATE CRS_Demographic SET AdmitDate = @AdmitDate 
	    WHERE LinkID = @LinkID AND (AA8 = 203626) 
    	    AND (Z12 >= @AdmitDate AND Z12 < @RDate) and IsSubmited <> 1 --ED - 02756
	END
END
ELSE IF @AA8 <> 14500 --Must not change admission date in demographic change PR - 04067
BEGIN
	--For the Rest get the most appropriate date and set the Admit Date to it.
	-- I DO NOT KNOW WHY THIS IS HERE, IT IS REPLACED BY STATEMENT BELOW
	--SET @RDate = (SELECT TOP 1 AB1b FROM CRS_Demographic WHERE LinkID = @LinkID AND AA8 = 14510 AND AB1b < @AdmitDate ORDER BY [AB1b] DESC)

	SELECT TOP 1 @RDate = VisitDate FROM (
		SELECT AdmitDate AS [VisitDate] FROM CRS_Demographic WHERE LinkID = @LinkID AND AA8 = 14501 AND AdmitDate <= @AdmitDate
		UNION
		SELECT AdmitDate AS [VisitDate] FROM CRS_Demographic WHERE LinkID = @LinkID AND AA8 = 14510 AND AdmitDate <= @AdmitDate) AS T
	ORDER BY [VisitDate] DESC

	--2.x-0535 if the re-entry date is the same as the discharge date, it assigns wrong if client modify the discharge date.
	if (@AA8 = 14507 or @AA8 = 14508 or @AA8 = 14509) and @RDate = @AdmitDate
	begin
		declare @AdmitDate_L datetime
		declare @DID int

		set @AdmitDate_L = (select max(Admitdate) from CRS_Demographic where LinkID = @LinkID AND AA8 in (14501, 14510) and AdmitDate < @AdmitDate)
		set @DID = (select top 1 AbstractID from crs_demographic where LinkID = @LinkID and abstractID <> @AbstractID and AdmitDate = @AdmitDate_L and AA8 in (14507, 14508, 14509)) 
		if @DID is null
			set @RDate = @AdmitDate_L
	end
    if @RDate is not null
    	UPDATE CRS_Demographic SET AdmitDate = @RDate 
    	WHERE AbstractID = @AbstractID and isnull(AdmitDate, '1950/01/01') <> @RDate 
    	    and IsSubmited <> 1 --ED - 02756
END
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO




-- This is called by the Save Method of the Control File Sub-Form
CREATE      PROCEDURE [U_CtrlDetail]
	@AppID as int, 
	@UserID as int,
	@FKey as int,
	@MandStatus as int,
	@HeaderUser as VarChar(100),
	@FieldEnabled as int,
	@FieldVisible as int,
	@DefaultValue as VarChar(100)
AS 

declare @IsGroup as int
declare @Mindex as int
declare @GroupID as int --PR - 04281

set @IsGroup = (select IsGroup from U_Fields where (FieldID = @FKey))
set @Mindex = (select Multipleindex from U_UsersFields where (AppID = @AppID) and (UserID = @UserID) and (FieldID = @FKey))
set @GroupID = (select GroupID from U_UsersFields where (AppID = @AppID) and (UserID = @UserID) and (FieldID = @FKey))

-- This will set blank and 0 Default Values to NULL
if len(@DefaultValue) = 0 or @DefaultValue = '0' set @DefaultValue = NULL

update dbo.U_UsersFields set 
	MandatoryStatus = @MandStatus,
	Header_User = @HeaderUser, 
	FieldEnabled = @FieldEnabled, 
	FieldVisible = @FieldVisible, 
	DefaultValue = @DefaultValue
where AppID = @AppID and UserID = @UserID and FieldID = @FKey

--This will reset Enabled to No if it's Field Access is not 0.
update dbo.U_UsersFields set FieldEnabled = 2 where AppID = @AppID and UserID = @UserID 
    and FieldID in (select FieldID from U_Fields where FieldID = @FKey and FieldAccess <> 0)

--TICKET 7305 - Turn toggle the Multi-form header depending on the status of it's fields
-- if the header is not on, then turn off all of the fields
if @IsGroup = 3 and (@FieldVisible = 2 or @FieldEnabled = 2)
	update U_UsersFields set FieldVisible = 2, FieldEnabled = 2
	where (AppID = @AppID) and (UserID = @UserID) and (Multipleindex = @Mindex) 
--PR - 04281
if @IsGroup = 1 and (@FieldVisible = 2 or @FieldEnabled = 2) and @GroupID > 1
	update U_UsersFields set FieldVisible = 2, FieldEnabled = 2
	where (AppID = @AppID) and (UserID = @UserID) and (GroupID = @GroupID) 
--ED - 02768
if @IsGroup = 2 and (@FieldVisible = 2 or @FieldEnabled = 2) and @GroupID > 1
	update U_UsersFields set FieldVisible = 2, FieldEnabled = 2
	where (AppID = @AppID) and (UserID = @UserID) and (GroupID = @GroupID) 

-- if it's not the header and the field is on, then turn the header on as well 
if (@FieldVisible = 1 and @FieldEnabled = 1) and @Mindex <> 0
	update U_UsersFields set FieldVisible = 1, FieldEnabled = 1 
	where (AppID = @AppID) 
	and (UserID = @UserID) 
	and (Multipleindex = @Mindex) 
	and FieldID = (select U.FieldID from U_Fields U JOin U_UsersFields UF ON U.FieldID = UF.FieldID where UF.AppID = @AppID and UF.UserID = @UserID and UF.Multipleindex = @Mindex and U.IsGroup = 3)

-- if it's not the header and none of the fields are on then turn off the header too
else if (@FieldVisible = 2 or @FieldEnabled = 2) and @Mindex <> 0
begin	
	if (select COUNT(FieldID) from U_UsersFields where (AppID = @AppID) and (UserID = @UserID) and (Multipleindex = @Mindex) 
	and FieldVisible = 1 and FieldEnabled = 1) <= 1
		update U_UsersFields set FieldVisible = 2, FieldEnabled = 2
		where (AppID = @AppID) and (UserID = @UserID) and (Multipleindex = @Mindex) 
		and FieldID = (select U.FieldID from U_Fields U JOin U_UsersFields UF ON U.FieldID = UF.FieldID where UF.AppID = @AppID and UF.UserID = @UserID and UF.Multipleindex = @Mindex and U.IsGroup = 3)
end		

--PR - 04281
if (@FieldVisible = 1 and @FieldEnabled = 1) and @GroupID > 1 and @Mindex = 0
	update U_UsersFields set FieldVisible = 1, FieldEnabled = 1 
	where (AppID = @AppID) 
	and (GroupID = @GroupID) 
	and UserID = @UserID
	and FieldID = (select top 1 U.FieldID from U_Fields U JOin U_UsersFields UF on U.FieldID = UF.FieldID where UF.AppID = @AppID and UF.GroupID = @GroupID and (U.IsGroup = 1 or U.IsGroup = 2))
else if (@FieldVisible = 2 or @FieldEnabled = 2) and @GroupID > 1 and @Mindex = 0
begin	
	if (select count(FieldID) from U_UsersFields where (AppID = @AppID) and (Multipleindex = @Mindex) 
	and FieldVisible = 1 and FieldEnabled = 1) <= 1
		update U_UsersFields set FieldVisible = 2, FieldEnabled = 2
		where (AppID = @AppID) 
    	and (GroupID = @GroupID) 
		and UserID = @UserID
		and FieldID = (select top 1 U.FieldID from U_Fields U JOin U_UsersFields UF ON U.FieldID = UF.FieldID where UF.AppID = @AppID and UF.GroupID = @GroupID and (U.IsGroup = 1 or U.IsGroup = 2))
end		

--TICKET 7850 - if the Header is being turned on and none of the fields are on, turn them all on
if @IsGroup = 3 and (@FieldVisible = 1 and @FieldEnabled = 1)
begin
	if (select COUNT(FieldID) from U_UsersFields where (AppID = @AppID) and (UserID = @UserID) and (Multipleindex = @Mindex) 		
	and FieldVisible = 1 and FieldEnabled = 1)  = 1
	begin
		update U_UsersFields set FieldEnabled = 1
		where (AppID = @AppID) and (UserID = @UserID) and (Multipleindex = @Mindex) 
		and FieldID in (select FieldID from U_Fields where FieldAccess = 0)

		update U_UsersFields set FieldVisible = 1
		where (AppID = @AppID) and (UserID = @UserID) and (Multipleindex = @Mindex) 
	end
end
--PR - 04281
if @IsGroup = 1 and (@FieldVisible = 1 and @FieldEnabled = 1) and @GroupID > 1
begin
	if (select count(FieldID) from U_UsersFields where (AppID = @AppID) and (GroupID = @GroupID) and (UserID = @UserID)		
    	and FieldVisible = 1 and FieldEnabled = 1)  = 1
	begin
		update U_UsersFields set FieldEnabled = 1
		where (AppID = @AppID) 
		and (GroupID = @GroupID) 
		and (UserID = @UserID)
		and FieldID in (select FieldID from U_Fields where FieldAccess = 0)

		update U_UsersFields set FieldVisible = 1
		where (AppID = @AppID) 
		and (GroupID = @GroupID) 
		and (UserID = @UserID)
	end
end

--ED - 02768
if @IsGroup = 2 and (@FieldVisible = 1 and @FieldEnabled = 1) and @GroupID > 1
begin
	if (select count(FieldID) from U_UsersFields where (AppID = @AppID) and (GroupID = @GroupID) and (UserID = @UserID)		
    	and FieldVisible = 1 and FieldEnabled = 1)  = 1
	begin
		update U_UsersFields set FieldEnabled = 1
		where (AppID = @AppID) 
		and (GroupID = @GroupID) 
		and (UserID = @UserID)
		and FieldID in (select FieldID from U_Fields where FieldAccess = 0)

		update U_UsersFields set FieldVisible = 1
		where (AppID = @AppID) 
		and (GroupID = @GroupID) 
		and (UserID = @UserID)
	end
end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



-- This is called by the Save Method of the Control File Sub-Form
CREATE  PROCEDURE [U_CtrlDetail_All]
	@AppID as int, 
	@UserID as int,
	@FKey as int,
	@MandStatus as int,
	@HeaderUser as VarChar(100),
	@FieldEnabled as int,
	@FieldVisible as int,
	@DefaultValue as VarChar(100)
AS 

declare @IsGroup as int
declare @Mindex as int
declare @GroupID as int --PR - 04281

select * from U_Users

set @IsGroup = (select IsGroup from U_Fields where (FieldID = @FKey))
set @Mindex = (select top 1 Multipleindex from U_UsersFields where (AppID = @AppID) and (FieldID = @FKey))
set @GroupID = (select GroupID from U_UsersFields where (AppID = @AppID) and (UserID = @UserID) and (FieldID = @FKey))

-- This will set blank and 0 Default Values to NULL
if len(@DefaultValue) = 0 or @DefaultValue = '0' set @DefaultValue = NULL

update dbo.U_UsersFields set 
	MandatoryStatus = @MandStatus,
	Header_User = @HeaderUser, 
	FieldEnabled = @FieldEnabled, 
	FieldVisible = @FieldVisible, 
	DefaultValue = @DefaultValue
where AppID = @AppID 
and FieldID = @FKey
and UserID not in (1, 2, 77777, 88888, 99999)

--This will reset Enabled to No if it's Field Access is not 0.
update dbo.U_UsersFields set FieldEnabled = 2 
where AppID = @AppID 
and FieldID in (select FieldID from U_Fields where FieldID = @FKey and FieldAccess <> 0)
and UserID not in (1, 2, 77777, 88888, 99999)

--TICKET 7305 - Turn toggle the Multi-form header depending on the status of it's fields
-- if the header is not on, then turn off all of the fields
if @IsGroup = 3 and (@FieldVisible = 2 or @FieldEnabled = 2)
	update U_UsersFields set FieldVisible = 2, FieldEnabled = 2
	where (AppID = @AppID) 
	and (Multipleindex = @Mindex) 
	and UserID not in (1, 2, 77777, 88888, 99999)
--PR - 04281
if @IsGroup = 1 and (@FieldVisible = 2 or @FieldEnabled = 2) and @GroupID > 1
	update U_UsersFields set FieldVisible = 2, FieldEnabled = 2
	where (AppID = @AppID) 	and UserID not in (1, 2, 77777, 88888, 99999)
	and (GroupID = @GroupID) 

--ED - 02768
if @IsGroup = 2 and (@FieldVisible = 2 or @FieldEnabled = 2) and @GroupID > 1
	update U_UsersFields set FieldVisible = 2, FieldEnabled = 2
	where (AppID = @AppID) 	and UserID not in (1, 2, 77777, 88888, 99999)
    and (GroupID = @GroupID) 

-- if it's not the header and the field is on, then turn the header on as well 
if (@FieldVisible = 1 and @FieldEnabled = 1) and @Mindex <> 0
	update U_UsersFields set FieldVisible = 1, FieldEnabled = 1 
	where (AppID = @AppID) 
	and (Multipleindex = @Mindex) 
	and UserID not in (1, 2, 77777, 88888, 99999)
	and FieldID = (select top 1 U.FieldID from U_Fields U JOin U_UsersFields UF on U.FieldID = UF.FieldID where UF.AppID = @AppID and UF.Multipleindex = @Mindex and U.IsGroup = 3)

-- if it's not the header and none of the fields are on then turn off the header too
else if (@FieldVisible = 2 or @FieldEnabled = 2) and @Mindex <> 0
begin	
	if (select count(FieldID) from U_UsersFields where (AppID = @AppID) and (Multipleindex = @Mindex) 
	and FieldVisible = 1 and FieldEnabled = 1) <= 1
		update U_UsersFields set FieldVisible = 2, FieldEnabled = 2
		where (AppID = @AppID) 
		and (Multipleindex = @Mindex) 
		and UserID not in (1, 2, 77777, 88888, 99999)
		and FieldID = (select top 1 U.FieldID from U_Fields U JOin U_UsersFields UF ON U.FieldID = UF.FieldID where UF.AppID = @AppID and UF.Multipleindex = @Mindex and U.IsGroup = 3)
end		
--PR - 04281
if (@FieldVisible = 1 and @FieldEnabled = 1) and @GroupID > 1 and @Mindex = 0
	update U_UsersFields set FieldVisible = 1, FieldEnabled = 1 
	where (AppID = @AppID) 
	and (GroupID = @GroupID) 
	and UserID not in (1, 2, 77777, 88888, 99999)
	and FieldID = (select top 1 U.FieldID from U_Fields U JOin U_UsersFields UF on U.FieldID = UF.FieldID where UF.AppID = @AppID and UF.GroupID = @GroupID and (U.IsGroup = 1 or U.IsGroup = 2))
else if (@FieldVisible = 2 or @FieldEnabled = 2) and @Mindex = 0 and @GroupID > 1
begin	
	if (select count(FieldID) from U_UsersFields where (AppID = @AppID) and (Multipleindex = @Mindex) 
	and FieldVisible = 1 and FieldEnabled = 1) <= 1
		update U_UsersFields set FieldVisible = 2, FieldEnabled = 2
		where (AppID = @AppID) 
    	and (GroupID = @GroupID) 
		and UserID not in (1, 2, 77777, 88888, 99999)
		and FieldID = (select top 1 U.FieldID from U_Fields U JOin U_UsersFields UF ON U.FieldID = UF.FieldID where UF.AppID = @AppID and UF.GroupID = @GroupID and (U.IsGroup = 1 or U.IsGroup = 2))
end		

--TICKET 7850 - if the Header is being turned on and none of the fields are on, turn them all on
if @IsGroup = 3 and (@FieldVisible = 1 and @FieldEnabled = 1)
begin
	if (select count(FieldID) from U_UsersFields where (AppID = @AppID) and (Multipleindex = @Mindex) 		
	and FieldVisible = 1 and FieldEnabled = 1)  = 1
	begin
		update U_UsersFields set FieldEnabled = 1
		where (AppID = @AppID) 
		and (Multipleindex = @Mindex) 
		and UserID not in (1, 2, 77777, 88888, 99999)
		and FieldID in (select FieldID from U_Fields where FieldAccess = 0)

		update U_UsersFields set FieldVisible = 1
		where (AppID = @AppID) 
		and (Multipleindex = @Mindex) 
		and UserID not in (1, 2, 77777, 88888, 99999)
	end
end
--PR - 04281
if @IsGroup = 1 and (@FieldVisible = 1 and @FieldEnabled = 1) and @GroupID > 1
begin
	if (select count(FieldID) from U_UsersFields where (AppID = @AppID) and (GroupID = @GroupID) and FieldVisible = 1 and FieldEnabled = 1)  = 1
	begin
		update U_UsersFields set FieldEnabled = 1
		where (AppID = @AppID) 
		and (GroupID = @GroupID) 
		and UserID not in (1, 2, 77777, 88888, 99999)
		and FieldID in (select FieldID from U_Fields where FieldAccess = 0)

		update U_UsersFields set FieldVisible = 1
		where (AppID = @AppID) 
		and (GroupID = @GroupID) 
		and UserID not in (1, 2, 77777, 88888, 99999)
	end
end

--ED - 02768
if @IsGroup = 2 and (@FieldVisible = 1 and @FieldEnabled = 1) and @GroupID > 1
begin
	if (select count(FieldID) from U_UsersFields where (AppID = @AppID) and (GroupID = @GroupID) and FieldVisible = 1 and FieldEnabled = 1)  = 1
	begin
		update U_UsersFields set FieldEnabled = 1
		where (AppID = @AppID) 
		and (GroupID = @GroupID) 
		and UserID not in (1, 2, 77777, 88888, 99999)
		and FieldID in (select FieldID from U_Fields where FieldAccess = 0)

		update U_UsersFields set FieldVisible = 1
		where (AppID = @AppID) 
		and (GroupID = @GroupID) 
		and UserID not in (1, 2, 77777, 88888, 99999)
	end
end

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE PROCEDURE [U_DAS_Header]
	(@ImgID	[int],
	 @HospitalID 	[int],
	 @AppID	[int],
	 @PatientID 	[int],
	 @AbstractID 	[int],
	 @ImgType 	[int],
	 @PageNo 	[int],
	 @Revision 	[int],
	 @DateScan 	[datetime],
--	 @Location 	[int],
--	 @FileType 	[int],
	 @ImgNote 	[varchar](255))

AS 
UPDATE [dbo].[DAS_Header] 

SET  	 [HospitalID]	 = @HospitalID,
	 [AppID]	 	 = @AppID,
	 [PatientID]	 = @PatientID,
	 [AbstractID]	 = @AbstractID,
	 [ImgType]	 = @ImgType,
	 [PageNo]	 = @PageNo,
	 [Revision]	 = @Revision,
	 [DateScan]	 = @DateScan,
--	 [Location]	 = @Location,
--	 [FileType]	 = @FileType,
	 [ImgNote]	 = @ImgNote 

WHERE 
	( [ImgID]	 = @ImgID)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE   PROCEDURE [U_Def_SlipMain]
   (@HospitalID		[int],
    @DefID        [int],
    @DefeciencyID  [int],
    @DefPatientID          [int],
    @DefLastName           [varchar](40),
    @DefFirstName          [varchar](35),
    @DefBirthDate          [datetime],
    @DefAbstractID         [int],
    @DefVolumeID   [int],
    @DefInstNumber [int],
    @DefSiteNumber [int],
    @DefDrNumber   [int],
    @DefDrStatus           [varchar](10),
    @DefColour             [int],
    @DefMainStatus         [int],
    @DefMainNote   [varchar](255),
    @DefStartDate          [datetime],
    @DefEndDate            [datetime],
    @DefDays               [int],
    @DefHoldStartDate      [datetime],
    @DefHoldEndDate        [datetime],
    @DefHoldDays   [int],
    @DefManualDays         [int],
    @DefVacationDays       [int],
    @DefSuspensionDays     [int],
    @ProviderService 	[int], 
    @ProviderSpecialty 	[int],
    @DefTotalDays int)
AS 

/*Put Hold Date Calculation here when ready*/

UPDATE [dbo].[Def_SlipMain] 
SET         
[HospitalID]	= @HospitalID,
[DefeciencyID]          = @DefeciencyID,
[DefPatientID]                  = @DefPatientID,
[DefPatLastName]        = @DefLastName,
[DefPatFirstName]       = @DefFirstName,
[DefBirthDate]          = @DefBirthDate,
[DefAbstractID]                 = @DefAbstractID,
[DefVolumeID]           = @DefVolumeID,
[DefInstNumber]         = @DefInstNumber,
[DefSiteNumber]         = @DefSiteNumber,
[DefDrNumber]           = @DefDrNumber,
[ProviderService]	= @ProviderService,
[ProviderSpecialty]	= @ProviderSpecialty,
[DefDrStatus]           = @DefDrStatus,
[DefColour]             = @DefColour,
[DefMainStatus]                 = @DefMainStatus,
[DefMainNote]           = @DefMainNote,
[DefStartDate]          = @DefStartDate,
[DefEndDate]            = @DefEndDate,
[DefDays]               = @DefDays,
[DefHoldStartDate]      = @DefHoldStartDate,
[DefHoldEndDate]        = @DefHoldEndDate,
[DefHoldDays]           = @DefHoldDays,
[DefManualDays]         = @DefManualDays,
[DefVacationDays]       = @DefVacationDays,
[DefSuspensionDays]     = @DefSuspensionDays,
[DefTotalDays]          = @DefTotalDays
where DefID = @DefID
--EN-00183
--WHERE  ([DefeciencyID] = @DefeciencyID)

return(@DefID)





GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO


--EN-00183	 @DefeciencyID 	[int],
CREATE  PROCEDURE [U_Def_Status]
	(@DefHeader		[int],
	 @DefID 	[int],
	 @DefStatus 		[int], 
	 @DefEndDate		[datetime])
AS 
/*If status is complete, we may want to calculate days now*/
IF @DefHeader = 1 
	UPDATE [dbo].[Def_SlipMain] SET [DefMainStatus] = @DefStatus, [DefEndDate] = @DefEndDate WHERE ([DefID] = @DefID)
ELSE
	UPDATE [dbo].[Def_Activity] SET [DefStatus] = @DefStatus, [DefEndDate] = @DefEndDate WHERE ([DefID] = @DefID)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [U_DefRollBackByProvider]
	@Provider int,
    @Coder    int,
    @Level    int
AS 
    declare @OldLevel int
    declare @MaxLevel int
    declare @RollBackLevel    int --PR - 03120

    set @OldLevel = isnull((select top 1 ProvdrCurLetter from LU_Provider where code = @Provider), 0)
    set @MaxLevel = isnull((select top 1 ProvdrMaxLetter from LU_Provider where code = @Provider), 0)

    if (@OldLevel > 0)
    begin
        if @MaxLevel = @Level set @Level = @Level - 1
        set @RollBackLevel = @Level --PR - 03120
        set @Level = (case when isnull(@Level, 0) <= 0 then 0
                           when @OldLevel + 1 = @Level then @OldLevel - 1
                           else @Level - 1
                      end)

        if @RollBackLevel > (@Level + 1) set @RollBackLevel = @Level + 1
        Update LU_Provider
        set ProvdrCurLetter = @Level,
            ProvdrCurLevel  = @RollBackLevel,  
            ProvdrLastUpdateDate = getdate()
        where code = @Provider
        --PR - 03120
        INSERT INTO [dbo].[REC_Notes] 
    	([LogID], [AppID], [RecordID], [LogNote], [LogDate], [LogTime], [LogCoder]) 
    	SELECT ISNULL(MAX(LogID), 0) + 1,  1104, @Provider, 'Rollback to Level ' + cast(@RollBackLevel as varchar(10)) + ' - Last Letter Issued Level Reset to ' + CONVERT(varchar(10), @Level) , GetDate(), GetDate(), @Coder FROM REC_Notes
 --    	SELECT ISNULL(MAX(LogID), 0) + 1,  1104, @Provider, 'Roll Back Level' + CONVERT(varchar(10), @Level) , GetDate(), GetDate(), @Coder FROM REC_Notes

    end

 

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [U_H_HospitalProfile]
	 (@Code 		[int],
	 @CDKey 		[varchar](40),
	 @ProvinceNumber 	[int],
	 @DefaultInstNumber 	[int],
	 @GrouperYear 		[varchar](10),
	 @ChartMask		[varchar](20),
	 @TerminalDigit 	[varchar](10),
	 @AutoGenChartNum 	[int],
	 @StartChartNumber 	[varchar](10),
	 @CIHIDirectory		[varchar](1000),
	 @PaediatricAge		[varchar](10), 
	 @TaxRate1		[int],
	 @TaxRate2		[int],
	 @DefAddDays		[int],
	 @FilterMorphCodes	[int],
	 @StartTransNumber	[int],
	 @ThreeM_CMD_I 		[varchar](10), 
	 @ThreeM_PAY_I 		[varchar](10), 
	 @ThreeM_CMD_S 		[varchar](10), 
	 @ThreeM_PAY_S 		[varchar](10), 
	 @ThreeM_CMD_A 		[varchar](10), 
	 @ThreeM_PAY_A 		[varchar](10),
	 @PasswordAttempt	[int],
	 @TopSearch 		[int],
	 @EnableSearchAudit 	[int],
	 @MultiUserSave 	[int],
	 @DisplayCode		[varchar] (12),
	 @CIHIValue		[varchar] (12),
	 @UserDescription 	[varchar] (255),
	 @ValidFrom		[datetime],
	 @ValidTo		[datetime],
	 @InterfaceIn		[varchar] (12),
	 @MinDeficiency 	[int],
	 @MaxActivityNumber	[int],
	 @AuditReport 		[int],
	 @HelpFilePath 		[varchar](255),
	 @MinPassWordLen 	[int], 
	 @LogOutTime 		[int],
	 @OMHRSAddDays 		[int],
     @ScrnLogOut    	[int],
	 @LUText 		[varchar](255),
	 @FormatPullID 		[int],
	 @ManualReturnLocation 	[int],
	 @UseWorkLoad 		[int],
	 @GSTNumber 		[varchar](50) ,
	 @ReIssueChart 		[int], 
	 @DisplayMultUser 	[int], 
	 @FilterNonAbstVH	[int], 
	 @New3M 		[int], 
	 @StoreOptimize 	[int] ,
	 @ChangePasswordDays 	[int], 
	 @UserDateFormat 	[int],
	 @BatVolPrinter 	[varchar](255),
	 @VolumePrintQue 	[int],
	 @VolumeSort 		[int],
	 @ReportPath 		[varchar](1000),
     @RBillingDirectory 	[varchar](1000),
     @AccessoryDirectory 	[varchar](1000),
	 @MDASPath 		[varchar](255), 
	 @MDASServer 		[varchar](50), 
	 @MDASDatabase 		[varchar](50),
	 --, @FacilityNumber	[varchar](4) 
	 @WinRecsTempFilesPath [varchar](255),
	 @PromptDeleteReason	[int],
	 @CCMSearchHCN	[int],
	 @ReportGroup   [varchar](100),
	 @AlterProviderService  [int],
	 @PasswordStartAlphabetic int,
	 @PasswordSpecialCharacter int,
	 @PasswordIncludeNumber int,
	 @PasswordIncludeAlphabetic int,
	 @PasswordIncludeLowCase int,
	 @PasswordIncludeUpperCase int,
	 @PasswordNotMatchPervious int,
	 @PasswordNotMatchUserName int,
	 @PasswordNotMatchFirstName int,
	 @PasswordNotMatchLastName int,
	 @UseQueue				   int,
	 @RegionalCancerCentres    int,
	 @AlternateENCNo           int,
     @AutoValidation3M         int

) 
AS 
update [H_HospitalProfile] 
set	
	[CDKey]	 		    = @CDKey,
	[DisplayCode] 		= @DisplayCode,
	[CIHIValue] 		= @CIHIValue,
	[UserDescription]	= @UserDescription,
-- 	[ValidFrom]		= '1950/04/01', --@ValidFrom, --PR-01814
-- 	[ValidTo]		= '2020/03/31', --@ValidTo, --PR-01814
 	[ValidFrom]		    = @ValidFrom,
 	[ValidTo]		    = @ValidTo,
    [LUText] 		= @LUText,
	[InterfaceIn]		= @InterfaceIn, 
	[ProvinceNumber]	= @ProvinceNumber,
	[DefaultInstNumber]	= @DefaultInstNumber,
	[GrouperYear]	 	= @GrouperYear,
	[ChartMask]		    = @ChartMask,
	[TerminalDigit]	 	= @TerminalDigit,
	[AutoGenChartNum]	= @AutoGenChartNum,
	[StartChartNumber]	= @StartChartNumber,
	[CIHIDirectory]		= @CIHIDirectory,
	[PaediatricAge]		= @PaediatricAge,
	[GSTNumber]		    = @GSTNumber,
	[TaxRate1]		    = @TaxRate1,
	[TaxRate2]		    = @TaxRate2,
	[DefAddDays]		= @DefAddDays,
	[FilterMorphCodes]	= @FilterMorphCodes,
	[StartTransNumber]	= @StartTransNumber,
	[ThreeM_CMD_I]		= @ThreeM_CMD_I,
	[ThreeM_PAY_I]		= @ThreeM_PAY_I,
	[ThreeM_CMD_S]		= @ThreeM_CMD_S,
	[ThreeM_PAY_S]		= @ThreeM_PAY_S,
	[ThreeM_CMD_A]		= @ThreeM_CMD_A,
	[ThreeM_PAY_A]		= @ThreeM_PAY_A,
	[PasswordAttempt]	= @PasswordAttempt,
	[TopSearch]		    = @TopSearch,
	[EnableSearchAudit]	= @EnableSearchAudit,
	[MultiUserSave]		= @MultiUserSave,
	[MinDeficiency]		= @MinDeficiency, 
	[MaxActivityNumber] = @MaxActivityNumber,
	[AuditReport]		= @AuditReport,
	[HelpFilePath]		= @HelpFilePath,
	[MinPassWordLen]	= @MinPassWordLen, 
	[LogOutTime]		= @LogOutTime,
    [ScrnLogOut]       	= @ScrnLogOut,
	[OMHRSAddDays]		= @OMHRSAddDays,
	[FormatPullID]		= @FormatPullID,
	[ManualReturnLocation]	= @ManualReturnLocation,
	[UseWorkLoad]		= @UseWorkLoad,
	[ReIssueChart]		= @ReIssueChart,
	[DisplayMultUser]	= @DisplayMultUser,
	[FilterNonAbstVH]	= @FilterNonAbstVH,
	[New3M]			    = @New3M,
	[StoreOptimize]		= @StoreOptimize,
	[ChangePasswordDays]	= @ChangePasswordDays,
	[UserDateFormat]	= @UserDateFormat,
	[BatVolPrinter]		= @BatVolPrinter,
	[VolumePrintQue]	= @VolumePrintQue,
	[VolumeSort]		= @VolumeSort,
	[ReportPath]		= @ReportPath,
    [RBillingDirectory] 	= @RBillingDirectory,
    [AccessoryDirectory] 	= @AccessoryDirectory,
	[MDASPath]		= @MDASPath,
	[MDASServer]		= @MDASServer,
	[MDASDatabase]		= @MDASDatabase,
    --,    [FacilityNumber]    = @FacilityNumber
	[WinRecsTempFilesPath]	=@WinRecsTempFilesPath,
	[PromptDeleteReason]	= @PromptDeleteReason,
	[CCMSearchHCN]          = @CCMSearchHCN,
	[ReportGroup]           = @ReportGroup,
	[AlterProviderService]  = @AlterProviderService,
	[PasswordStartAlphabetic]   = @PasswordStartAlphabetic,
	[PasswordSpecialCharacter]  = @PasswordSpecialCharacter,
	[PasswordIncludeNumber]	    = @PasswordIncludeNumber,
	[PasswordIncludeAlphabetic] = @PasswordIncludeAlphabetic,
	[PasswordIncludeLowCase]	= @PasswordIncludeLowCase,
	[PasswordIncludeUpperCase]  = @PasswordIncludeUpperCase,
	[PasswordNotMatchPervious]  = @PasswordNotMatchPervious,
	[PasswordNotMatchUserName]  = @PasswordNotMatchUserName,
	[PasswordNotMatchFirstName] = @PasswordNotMatchFirstName,
	[PasswordNotMatchLastName]  = @PasswordNotMatchLastName,
	[UseQueue] = @UseQueue,
	[RegionalCancerCentres] = @RegionalCancerCentres,
    [AlternateENCNo]        = @AlternateENCNo,
    [AutoValidation3M]      = @AutoValidation3M
where 
	[Code] = @Code
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [U_H_InstitutionProfile]
	(@Code		 		[int],
	@DisplayCode 			[varchar](50),
	@UserDescription		[varchar](255),
	@DefaultDescription		[varchar](255),
	@CIHIValue			[varchar](50),
	@ValidFrom			[datetime],
	@ValidTo			[datetime],
	@InterfaceIn			[varchar](50),
	@AssociationID			[int],
	@SiteNumber	 		[int],
	@ICDCMLive			[datetime],
	@ICDTLive 			[datetime],
	@CIHIYear			[varchar](10),
	@CIHIPeriod	 		[int],
	@RegionYear			[varchar](10),
	@RegionPeriod 			[varchar](10),
	@CostPerRIW	 		[varchar](10),
	@AutoGenEncounterNum 	[int],
	@StartEncounterNumber		[varchar](20),
	@UseMentalHealth		[int],
	@BOP_State1 			[int],
	@BOP_Text1			[varchar](100),
	@BOP_State2 			[int],
	@BOP_Text2			[varchar](100),
	@BOP_State3 			[int],
	@BOP_Text3			[varchar](100),
	@BOP_State4 			[int],
	@BOP_Text4			[varchar](100),
	@BOP_State5 			[int],
	@BOP_Text5			[varchar](100),
	@BOP_State6 			[int],
	@BOP_Text6			[varchar](100),
	@BOP_State7 			[int],
	@BOP_Text7			[varchar](100),
	@BOP_State8 			[int],
	@BOP_Text8			[varchar](100),
	@BOP_State9 			[int],
	@BOP_Text9			[varchar](100),
	@BOP_State10 			[int],
	@BOP_Text10			[varchar](100),
	@BOP_State11 			[int],
	@BOP_Text11			[varchar](100),
	@BOP_State12 			[int],
	@BOP_Text12			[varchar](100),
	@BOP_State13 			[int],
	@BOP_Text13			[varchar](100),
	@BOP_State14 			[int],
	@BOP_Text14	 		[varchar](100),
	@BOP_State15 			[int],
	@BOP_Text15 			[varchar](100),
	@BOP_State16 			[int],
	@BOP_Text16			[varchar](100),
	@BOP_State17 			[int],
	@BOP_Text17	 		[varchar](100),	
	@BOP_State18 			[int],
	@BOP_Text18			[varchar](100),
	@BOP_State19 			[int],
	@BOP_Text19	 		[varchar](100),
	@UserEditsPath			[varchar](255),
	@MOHOfficeCode		[varchar](1),
	@GroupNumber			[varchar](4),
	@LocationCode			[varchar](4),
	@RefLabNumber 		[varchar](4), 
	@GSTNumber 			[varchar](25), 
	@PSTNumber 			[varchar](25), 
	@ContactID 			[varchar](35), 
	@Street 			[varchar](35), 
	@City 				[varchar](35), 
	@ProvinceNumber 		[varchar](2), 
	@PostalCode 			[varchar](7), 
	@WebAddress 			[varchar](60), 
	@EMail 			[varchar](60), 
	@PrimaryPhone 			[varchar](15),
	@LockDownDate 		[datetime],
	@OverlookCIHI 			[int],
	@UsetransferWorksheetData	[int],
	@NewChartPrefix 		[varchar](3),
	@CIHIDirectory 			[varchar] (1000),
	@NextAssessDay 		[int],
	@HospitalID			[int],
	@ProvdrRequestor 	 	[int],
    @LUText 			[varchar](255),
	@FacilitySequence 		[int],
    @RBillingDirectory      [varchar] (1000),
    @RehabSubDate       datetime,
    @IsMultiSubmission  int,
	--, @PatientType 			[int] 
	@ShowSubmissionLog  int,
	@PreferedLevelCode  int,
	@CopyAssessment     int,
	@UseLite			int,
	@EnableCopyButton   int,
    @SubmitCJRR         int,
    @InstitutionType  varchar(1),
    @AutoProject012     int
)
AS 

--EN - 00458 to make @IsMultiSubmission has value 1, 2
if @IsMultiSubmission > 2 and @AssociationID = 3 
	set @IsMultiSubmission = isnull((select top 1 code from LU_YeaBlankAlpha where code in (1, 2) and 
							CIHIValue in (select CIHIValue from LU_YeaBlankAlpha where code = @IsMultiSubmission)), 2)
 
update [H_InstitutionProfile] 
set 
 	[DisplayCode]	 	= @DisplayCode,
	[UserDescription]	= @UserDescription,
	[DefaultDescription]	= @DefaultDescription,
	--[CIHIValue]	 	= @CIHIValue,   --PR - 06218
	[ValidFrom]	 	= @ValidFrom,
	[ValidTo]	 	= @ValidTo,
    [LUText] 		= @LUText, 
	[InterfaceIn]	 	= @InterfaceIn,
	[AssociationID]	 	= @AssociationID,
	--[PatientType]		= @PatientType,
	[HospitalID]		= @HospitalID, 
	[SiteNumber]	 	= @SiteNumber,
	[ICDCMLive]	 	= @ICDCMLive,
	[ICDTLive]	 	= @ICDTLive,
	[CIHIYear]		= @CIHIYear,
	[CIHIPeriod]	 	= @CIHIPeriod,
	[FacilitySequence]	= @FacilitySequence,
	[RegionYear]		= @RegionYear,
	[RegionPeriod]	 	= @RegionPeriod,
	[CostPerRIW]	 	= @CostPerRIW,
	[AutoGenEncounterNum]	= @AutoGenEncounterNum,
	[StartEncounterNumber]	= @StartEncounterNumber,
	[UseMentalHealthData]	= @UseMentalHealth,
	[UsetransferWorksheetData]	=@UsetransferWorksheetData,
	[BOP_State1]		= @BOP_State1,		
	[BOP_Text1]		= @BOP_Text1,
	[BOP_State2] 		= @BOP_State2,
	[BOP_Text2]		= @BOP_Text2,
	[BOP_State3] 		= @BOP_State3,
	[BOP_Text3]		= @BOP_Text3,
	[BOP_State4] 		= @BOP_State4,
	[BOP_Text4]		= @BOP_Text4,
	[BOP_State5] 		= @BOP_State5,	
	[BOP_Text5]		= @BOP_Text5,
	[BOP_State6] 		= @BOP_State6,
	[BOP_Text6]		= @BOP_Text6,
	[BOP_State7] 		= @BOP_State7,
	[BOP_Text7]		= @BOP_Text7,
	[BOP_State8] 		= @BOP_State8,
	[BOP_Text8]		= @BOP_Text8,
	[BOP_State9] 		= @BOP_State9,
	[BOP_Text9]		= @BOP_Text9,
	[BOP_State10] 		= @BOP_State10,
	[BOP_Text10]		= @BOP_Text10,
	[BOP_State11] 		= @BOP_State11,
	[BOP_Text11]		= @BOP_Text11,
	[BOP_State12] 		= @BOP_State12,
	[BOP_Text12]		= @BOP_Text12,
	[BOP_State13] 		= @BOP_State13,
	[BOP_Text13]		= @BOP_Text13,
	[BOP_State14] 		= @BOP_State14,
	[BOP_Text14] 		= @BOP_Text14,
	[BOP_State15] 		= @BOP_State15,
	[BOP_Text15]		= @BOP_Text15,
	[BOP_State16] 		= @BOP_State16,
	[BOP_Text16]		= @BOP_Text16,
	[BOP_State17] 		= @BOP_State17,
	[BOP_Text17] 		= @BOP_Text17,
	[BOP_State18]		= @BOP_State18,
	[BOP_Text18]		= @BOP_Text18,
	[BOP_State19] 		= @BOP_State19,
	[BOP_Text19]		= @BOP_Text19,
	[UserEditsPath]		= @UserEditsPath,
	[MOHOfficeCode]		= @MOHOfficeCode,
	[GroupNumber]		= @GroupNumber,
	[LocationCode]		= @LocationCode,
	[RefLabNumber]		= @RefLabNumber, 
	[GSTNumber]			= @GSTNumber, 
	[PSTNumber]			= @PSTNumber, 
	[ContactID]			= @ContactID, 
	[Street]			= @Street, 
	[City]				= @City, 
	[ProvinceNumber]	= @ProvinceNumber, 
	[PostalCode]		= @PostalCode, 
	[WebAddress]		= @WebAddress, 
	[EMail]				= @EMail, 
	[PrimaryPhone]		= @PrimaryPhone,
	[LockDownDate]		= @LockDownDate,
	[OverlookCIHI]		= @OverlookCIHI,
	[NewChartPrefix]	= @NewChartPrefix,
	[ProvdrRequestor]	= @ProvdrRequestor,
	[NextAssessDay]		= @NextAssessDay,
	[CIHIDirectory]		= @CIHIDirectory,
    RBillingDirectory	= @RBillingDirectory,
    RehabSubDate		= @RehabSubDate,
    IsMultiSubmission	= @IsMultiSubmission,
    ShowSubmissionLog	= @ShowSubmissionLog,
    PreferedLevelCode	= @PreferedLevelCode,
    CopyAssessment		= @CopyAssessment,
	UseLite				= @UseLite,
	EnableCopyButton	= @EnableCopyButton,
    SubmitCJRR          = @SubmitCJRR,
    InstitutionType     = @InstitutionType,
    AutoProject012      = @AutoProject012
where 
	([Code]	 = @Code)

--If there is a ROI Requestor
if @ProvdrRequestor > 0
    update [LU_ROI_Requesters] set [UserDescription] = @UserDescription, [ValidFrom] = @ValidFrom, [ValidTo] = @ValidTo, [Address] = @Street, [PostalCode] = @PostalCode, [Phone] = @PrimaryPhone, [City] = @City, [Province] = @ProvinceNumber, [HospitalID] = @HospitalID where Code = @ProvdrRequestor


declare @FacID as varchar(50)
select @FacID = FacilityFileID from H_InstitutionProfile where Code = @Code

if len(isnull(@FacID, '')) <= 0 
begin
	if isnull(@HospitalID, 0) = 0 
		update H_InstitutionProfile set FacilityFileID = (select top 1 h.Code from H_HospitalProfile h) where Code = @Code
	else
		update H_InstitutionProfile set FacilityFileID =  @HospitalID where Code = @Code
end
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE PROCEDURE [U_H_InstProfPostSubmit]
	@InstNumber as int,
	@BatchYear as int,
	@BatchPeriod as int
AS 

/*
    declare @ProvNumber int, @PeriodCode int, @PeriodCIHI varchar(12), @CIHIDate datetime
    
    declare @sql nvarchar(1000)    

    select top 1 @ProvNumber = ProvinceNumber from H_HospitalProfile 

    select 
        @BatchYear  = CIHIYear,
        @PeriodCode = CIHIPeriod,
        @PeriodCIHI = l.CIHIValue
    from H_InstitutionProfile h join LU_BatchPeriod l on h.CIHIPeriod = l.Code
    where (@InstNumber = h.Code)

    -- exit if invalid
    if (nullif(@PeriodCode, 0) is null) return 

    -- BC Institution
    if (@ProvNumber = 14) begin 

        if (@PeriodCIHI = '13') begin
            set @BatchYear = @BatchYear + 1
        end

        select @BatchYear, @PeriodCode

        set @sql = N'select @NewCode = Code from LU_BatchPeriod where CIHIDateFrom = (' +
                'select dateadd(day, 1, CIHIDateTo) from LU_BatchPeriod where Code = @OldCode)'

        exec sp_executesql @sql, N'@NewCode int output, @OldCode int', @BatchPeriod output, @PeriodCode
        
        select @BatchYear, @BatchPeriod


    end
    else begin
        
        if (@PeriodCIHI = '12') begin
            set @BatchPeriod = 1
            set @BatchYear = @BatchYear + 1
        end
        else begin
            set @BatchPeriod = @PeriodCode + 1
        end
        

    end

*/
    --Ticket 11529 Duplicate Submission File Created. 
    update dbo.H_InstitutionProfile 
    Set CIHIYear = @BatchYear, CIHIPeriod = @BatchPeriod 
    --where (Code = @InstNumber)
    where Code = @InstNumber and (isnull(CIHIYear, 0) < @BatchYear or 
        (CIHIYear = @BatchYear and isnull(CIHIPeriod, 0) < @BatchPeriod))



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [U_H_RegionProfile]
	(@DisplayCode		[varchar](12),
	 @CIHIValue		[varchar](12),
	 @UserDescription	[varchar](255),
	 @ValidFrom		[datetime],
	 @ValidTo		[datetime],
	 @InterfaceIn		[varchar](12),
	 @ProvinceNumber 	[int],
	 @GrouperYear	 	[int],
	 @PaediatricAge 	[int],
	 @TaxRate1	 	[int],
	 @TaxRate2	 	[int],
	 @PasswordAttempt 	[int],
	 @TopSearch	 	[int],
	 @EnableSearchAudit 	[int],
	 @UniqueChartNum 	[int],
	 @AutoGenChartNum 	[int],
	 @StartChartNumber 	[varchar](10),
	 @ChartMask		[varchar](20),
	 @TerminalDigit	 	[varchar](10),
	 @UniqueVolumeNum 	[int],
	 @UniqueDefNum		[int],
	 @DefAddDays	 	[int],
	 @UniqueTransNum 	[int],
	 @StartTransNumber 	[int],
	 @CIHIDirectory 	[varchar](1000), 
	 @HelpFilePath 		[varchar](255), 
	 @MinPassWordLen 	[int], 
	 @LogOutTime 		[int], 
	 @AuditReport 		[int], 
	 @MultiUserSave 	[int],
	 @OMHRSAddDays 		[int],
     @ScrnLogOut    	[int],
     @LUText 		[varchar](255),
	 @FormatPullID		[int],
	 @ManualReturnLocation 	[int],
	 @UseWorkLoad 		[int],
	 @GSTNumber 		[varchar](50) ,
	 @ReIssueChart 		[int], 
	 @DisplayMultUser 	[int], 
	 @SiteSpecificVolume 	[int], 
	 @FilterNonAbstVH 	[int], 
	 @New3M 		[int], 
	 @StoreOptimize 	[int],
	 @ChangePasswordDays 	[int], 
	 @UserDateFormat 	[int],
	 @VolumePrintQue 	[int],
	 @VolumeSort 		[int],
	 @ReportPath 		[varchar](1000),
     @RBillingDirectory 	[varchar](1000),
	 @AccessoryDirectory 	[varchar](1000),
	 @MDASPath 		[varchar](255), 
	 @MDASServer 		[varchar](50), 
	 @MDASDatabase 		[varchar](50),
	 @WinRecsTempFilesPath 	[varchar](255),
	 @PromptDeleteReason	[int] ,
	 @CCMSearchHCN          [int],
	 @UseCorporateChart     [int],
	 @HospitalSelect		[int]
    )
AS 
update [H_RegionProfile] 
set  	 [DisplayCode]	 	= @DisplayCode,
	 [CIHIValue]	 	= @CIHIValue,
	 [UserDescription]	= @UserDescription,
	 [ValidFrom]	 	= @ValidFrom,
	 [ValidTo]	 	    = @ValidTo,
     [LUText] 		    = @LUText, 
	 [InterfaceIn]	 	= @InterfaceIn,
	 [ProvinceNumber]	= @ProvinceNumber,
	 [GrouperYear]	 	= @GrouperYear,
	 [PaediatricAge]	= @PaediatricAge,
	 [GSTNumber]		= @GSTNumber,
	 [TaxRate1]	 	    = @TaxRate1,
	 [TaxRate2]	 	    = @TaxRate2,
	 [PasswordAttempt]	= @PasswordAttempt,
	 [TopSearch]	 	= @TopSearch,
	 [EnableSearchAudit]	= @EnableSearchAudit,
	 [UniqueChartNum]	= @UniqueChartNum,
	 [AutoGenChartNum]	= @AutoGenChartNum,
	 [StartChartNumber]	= @StartChartNumber,
	 [ChartMask]	 	= @ChartMask,
	 [TerminalDigit]	= @TerminalDigit,
	 [UniqueVolumeNum]	= @UniqueVolumeNum,
	 [UniqueDefNum]		= @UniqueDefNum,
	 [DefAddDays]	 	= @DefAddDays,
	 [UniqueTransNum]	= @UniqueTransNum,
	 [StartTransNumber]	= @StartTransNumber,
	 [CIHIDirectory]	= @CIHIDirectory,
	 [HelpFilePath]		= @HelpFilePath,
	 [MinPassWordLen]	= @MinPassWordLen,
	 [LogOutTime]		= @LogOutTime,
     [ScrnLogOut]      	= @ScrnLogOut,
	 [AuditReport]		= @AuditReport,
	 [MultiUserSave]	= @MultiUserSave,
	 [OMHRSAddDays]		= @OMHRSAddDays,
	 [FormatPullID]		= @FormatPullID,
	 [ManualReturnLocation]	= @ManualReturnLocation,
	 [UseWorkLoad]		= @UseWorkLoad,
	 [ReIssueChart]		= @ReIssueChart,
	 [DisplayMultUser]	= @DisplayMultUser,
	 [SiteSpecificVolume]	= @SiteSpecificVolume,
	 [FilterNonAbstVH]	= @FilterNonAbstVH,
	 [New3M]		    = @New3M,
	 [StoreOptimize]	= @StoreOptimize,
	 [ChangePasswordDays]	= @ChangePasswordDays,
	 [UserDateFormat]	= @UserDateFormat,
	 [VolumePrintQue]	= @VolumePrintQue,
	 [VolumeSort]		= @VolumeSort,
	 [ReportPath]		= @ReportPath, 
     [RBillingDirectory] 	= @RBillingDirectory,
     [AccessoryDirectory] 	= @AccessoryDirectory,
	 [MDASPath]		    = @MDASPath,
	 [MDASServer]		= @MDASServer,
	 [MDASDatabase]		= @MDASDatabase,
	 [WinRecsTempFilesPath]	= @WinRecsTempFilesPath,
	 [PromptDeleteReason]	= @PromptDeleteReason,
	 [CCMSearchHCN]         = @CCMSearchHCN,
	 [UseCorporateChart]    = @UseCorporateChart,
	 [HospitalSelect]		= @HospitalSelect
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [U_LLU_ProviderServices]
	(@AssociationID		[int],
	 @Code 		[int],
	 @Type 		[int],
	 @ValidFrom 		[datetime],
	 @ValidTo 		[datetime])
AS 

UPDATE [LLU_ProviderServices] 
SET  	 [Type]	 	= @Type,
	 [ValidFrom]	= @ValidFrom,
	 [ValidTo]	= @ValidTo
WHERE 
	([Code]	 	= @Code
AND  	[AssociationID]	= @AssociationID)




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [U_LLU_ProviderSpecialty]
	(@AssociationID		[int],
	 @Code 		[int],
	 @Type 		[int],
	 @ValidFrom 		[datetime],
	 @ValidTo 		[datetime])
AS 

UPDATE [LLU_ProviderSpecialty] 
SET  	 [Type]	 	= @Type,
	 [ValidFrom]	= @ValidFrom,
	 [ValidTo]	= @ValidTo
WHERE 
	([Code]	 	= @Code
AND  	[AssociationID]	= @AssociationID)




GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE      PROCEDURE [U_LU_Borrower] (
    @Code             int         ,
    @DisplayCode      varchar(20) ,
    @BorrowerName     varchar(50) ,
    @BorrowerAddress  varchar(255),
    @BorrowerCity     varchar(50) ,
    @ValidFrom        datetime    ,
    @ValidTo          datetime    ,
    @InterfaceIn      varchar(20) ,
    @BorrowerProvince varchar(50) ,
    @BorrowerPostal   varchar(50) ,
    @BorrowerContact  varchar(50) ,
    @BorrowerPhone    varchar(16),
    @Location		int,	
    @HospitalID		int,
    @CLRequestPriority int,
    @LUText         varchar(255)
)
AS 

update [LoanLU_Borrower] 
set [DisplayCode]      = @DisplayCode     ,
    [UserDescription]     = @BorrowerName    ,
    [BorrowerAddress]  = @BorrowerAddress ,
    [BorrowerCity]     = @BorrowerCity    ,        
    [ValidFrom]        = @ValidFrom       ,        
    [ValidTo]          = @ValidTo         ,        
    [LUText] = @LUText, 
    [InterfaceIn]      = @InterfaceIn     ,    
    [HospitalID]       = @HospitalID,
    [BorrowerProvince] = @BorrowerProvince,
    [BorrowerPostal]   = @BorrowerPostal  ,
    [BorrowerContact]  = @BorrowerContact ,
    [BorrowerPhone]    = @BorrowerPhone,
    [PullLocation]	 = @Location,
    CLRequestPriority = @CLRequestPriority
where ([Code] = @Code)



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [U_LU_CC_RT_PROTOCOL]
(   @Code 	[int],
    @DisplayCode 	[varchar](50),
    @UserDescription 	[varchar](255),
    @DefaultDescription 	[varchar](255),
    @CIHIValue 	[varchar](50),
    @Validfrom 	[datetime],
    @ValidTo 	[datetime],
    @InterfaceIn 	[varchar](50),
    @HospitalID 	[int],
    @LUText [varchar](255),
	@RT_CLINICAL_PRTC_GRP [varchar](50),
	@RT_CLINICAL_PRTC_SUB_GRP [varchar](50),
	@Modality [varchar](50),
	@INTENT [varchar](50),
	@DOSE_Gy [varchar](50),
	@DOSE_MIN [varchar](50),
	@DOSE_MAX [varchar](50),
	@FRACTIONATION [varchar](50),
	@NUMBER_OF_FRACTIONS_MIN [varchar](50),
	@NUMBER_OF_FRACTIONS_MAX [varchar](50),
	@DOSE_Gy_PER_FRACTION [varchar](50),
	@DOSE_PER_FRACTION_MIN [varchar](50),
	@DOSE_PER_FRACTION_MAX [varchar](50)
)

AS 
update [dbo].LU_CC_RT_PROTOCOL 
set 
    [DisplayCode] = @DisplayCode,
    [UserDescription] = @UserDescription,
    [DefaultDescription] = @DefaultDescription,
    [CIHIValue] = @CIHIValue,
    [Validfrom] = @Validfrom,
    [ValidTo] = @ValidTo,
    [InterfaceIn] = @InterfaceIn,
    [HospitalID] = @HospitalID,
    [LUText] = @LUText, 
	[RT_CLINICAL_PRTC_GRP] = @RT_CLINICAL_PRTC_GRP,
	[RT_CLINICAL_PRTC_SUB_GRP] = @RT_CLINICAL_PRTC_SUB_GRP,
	[Modality] = @Modality,
	[INTENT] = @INTENT,
	[DOSE_Gy] = @DOSE_Gy,
	[DOSE_MIN] = @DOSE_MIN,
	[DOSE_MAX] = @DOSE_MAX,
	[FRACTIONATION] = @FRACTIONATION,
	[NUMBER_OF_FRACTIONS_MIN] = @NUMBER_OF_FRACTIONS_MIN,
	[NUMBER_OF_FRACTIONS_MAX] = @NUMBER_OF_FRACTIONS_MAX,
	[DOSE_Gy_PER_FRACTION] = @DOSE_Gy_PER_FRACTION,
	[DOSE_PER_FRACTION_MIN] = @DOSE_PER_FRACTION_MIN,
	[DOSE_PER_FRACTION_MAX] = @DOSE_PER_FRACTION_MAX
where   [Code] = @Code
   
	return @Code
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [U_LU_CCM_BodyRegion]
	(@Code 	[int],
	 @DisplayCode 	[varchar](50),
	 @UserDescription 	[varchar](255),
	 @DefaultDescription	[varchar](255),
	 @CIHIValue 	[varchar](50),
	 @ValidFrom 	[datetime],
	 @ValidTo 	[datetime],
	 @InterfaceIn 	[varchar](50),
	 @HospitalID 	[int],
     @LUText [varchar](255),
	 @BodyGroup 	[varchar](50) 
)
AS 
update [dbo].LU_CCM_BodyRegion 
set  [DisplayCode]	 = @DisplayCode,
	 [UserDescription]	 = @UserDescription,
	 [DefaultDescription]	 = @DefaultDescription,
	 [CIHIValue]	 = @CIHIValue,
	 [ValidFrom]	 = @ValidFrom,
	 [ValidTo]	 = @ValidTo,
	 [InterfaceIn]	 = @InterfaceIn,
	 [HospitalID]	 = @HospitalID,
   	 [LUText] 	 = @LUText, 
	 BodyGroup	 = @BodyGroup

where ( [Code]	 = @Code)
return 0



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [U_LU_CCM_NHPIP_Code]
(   @Code 	[int],
    @DisplayCode 	[varchar](50),
    @UserDescription 	[varchar](255),
    @DefaultDescription 	[varchar](255),
    @CIHIValue 	[varchar](50),
    @Validfrom 	[datetime],
    @ValidTo 	[datetime],
    @InterfaceIn 	[varchar](50),
    @HospitalID 	[int],
    @LUText [varchar](255),
    @NHPIP_ACT_TYPE varchar(10),
    @NHPIP_DURATION_UNIT int,
    @NHPIP_MAX_DOES_PF varchar(10),
    @NHPIP_USAGE_CD varchar(10),
    @NHPIP_ACTIVE_STATUS  varchar(10)
)

AS 
Update [dbo].LU_CCM_NHPIP_Code 
set 
    [DisplayCode] = @DisplayCode,
    [UserDescription] = @UserDescription,
    [DefaultDescription] = @DefaultDescription,
    [CIHIValue] = @CIHIValue,
    [Validfrom] = @Validfrom,
    [ValidTo] = @ValidTo,
    [InterfaceIn] = @InterfaceIn,
    [HospitalID] = @HospitalID,
    [LUText] = @LUText, 
    NHPIP_ACT_TYPE = @NHPIP_ACT_TYPE,
    NHPIP_DURATION_UNIT = @NHPIP_DURATION_UNIT,
    NHPIP_MAX_DOES_PF = @NHPIP_MAX_DOES_PF,
    NHPIP_USAGE_CD = @NHPIP_USAGE_CD,
    NHPIP_ACTIVE_STATUS = @NHPIP_ACTIVE_STATUS
   
where  [Code] = @Code
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE     PROCEDURE [U_LU_ChartLocation]
	(@Code 		[int],
	@DisplayCode		[varchar](50),
	@UserDescription	[varchar](255),
	@ValidFrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](50),
	@LoanDays		[int],
	@LoanHospital		[int],
	@LoanInOut		[int],
	@HospitalID		[int],
    @CLRequestPriority [int],
    @LUText [varchar](255),
	@LocationType		[int])
AS 

update [LoanLU_Location] 
set  	[DisplayCode]	 	= @DisplayCode,
	[UserDescription]	= @UserDescription,
	[ValidFrom]	 	= @ValidFrom,
	[ValidTo]	 	= @ValidTo,
    [LUText] = @LUText, 
	[InterfaceIn]	 	= @InterfaceIn,
	[LoanDays]		= @LoanDays,
	[LoanHospital]		= @LoanHospital,
	[InHospital] 		= @LoanInOut,
	[HospitalID]		= @HospitalID,
    [CLRequestPriority] = @CLRequestPriority,
	[LocationType]		= @LocationType
where 
	([Code]	 		= @Code)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [U_LU_CJRR_StickerCode]
	(@TableName             [varchar](50),
	 @Code 					[varchar](50),
	 @DisplayCode 			[varchar](50),
	 @UserDescription 		[varchar](255),
	 @DefaultDescription	[varchar](255),
	 @CIHIValue 			[varchar](50),
	 @ValidFrom 			[varchar](50),
	 @ValidTo 				[varchar](50),
	 @InterfaceIn 			[varchar](50),
	 @HospitalID 			[varchar](50),
     @LUText				[varchar](255),
	 @Manufacturer 			[varchar](50),
	 @OtherManufacturer		[varchar](100),
	 @CatalogueNumber		[varchar](50),
	 @LotNumber				[varchar](50)
)
AS 

   declare @SQL varchar(2000)
   set @Displaycode = replace(@DisplayCode, '''',  '''''')
   set @UserDescription = replace(@UserDescription, '''',  '''''')
   set @DefaultDescription = replace(@DefaultDescription, '''',  '''''')
   set @InterfaceIn = replace(@InterfaceIn, '''',  '''''')

   set @OtherManufacturer = replace(@OtherManufacturer, '''',  '''''')
   set @CatalogueNumber = replace(@CatalogueNumber, '''',  '''''')
   set @LotNumber = replace(@LotNumber, '''',  '''''')

   select @SQL = 'update ' + @TableName + ' set [DisplayCode] = ''' + @DisplayCode + ''', [UserDescription] = ''' + @UserDescription + 
   ''', [ValidFrom] = ''' + @ValidFrom + ''', [ValidTo] = ''' + @ValidTo + ''', [LUText] = ''' + @LUText + ''', [InterfaceIn] = ''' + @InterfaceIn + ''', [HospitalID] = ' + @HospitalID + 
   ', [Manufacturer] = ' + @Manufacturer + ', [OtherManufacturer] = ''' + @OtherManufacturer + ''', [CatalogueNumber] = ''' + @CatalogueNumber + ''', [LotNumber] = ''' + @LotNumber + '''' + 
   ' where [Code] = ' + @Code
   execute (@SQL)

   return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [U_LU_ClinicalPathway]
	(@Code 	[int],
	 @DisplayCode 	[varchar](50),
	 @UserDescription 	[varchar](255),
	 @DefaultDescription	[varchar](255),
	 @CIHIValue 	[varchar](12),
	 @ValidFrom 	[datetime],
	 @ValidTo 	[datetime],
	 @InterfaceIn 	[varchar](50),
	 @HospitalID 	[int],
	 @ClinicalLOS 	[varchar](50),
     	 @LUText [varchar](255))
AS 
update [dbo].[LU_ClinicalPathway] 

set  	 [DisplayCode]	 	= @DisplayCode,
	 [UserDescription]	= @UserDescription,
	 [DefaultDescription]	= @DefaultDescription,
	 [CIHIValue]	 	= @CIHIValue,
	 [ValidFrom]	 	= @ValidFrom,
	 [ValidTo]	 	= @ValidTo,
     	 [LUText] 		= @LUText, 
	 [InterfaceIn]	 	= @InterfaceIn,
	 [HospitalID]	 	= @HospitalID,
	 [ClinicalLOS]	 	= @ClinicalLOS 
where 
	 [Code]	 		= @Code
return 0



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



-- This is called by the Save Method of the Deficiency Code Look Up Maint Sub-Form
CREATE   PROCEDURE [U_LU_DeficiencyCode] 
	(@Code			AS INTEGER,
	@DisplayCode 		AS varchar(50),
	@UserDescription 	AS varchar(255),
	@ValidFrom		AS DATETIME,
	@ValidTo		AS DATETIME,
	@InterfaceIn		AS varchar(50),
	@AssociationID		AS INTEGER,
	@LinkDefCode		AS INTEGER, 
	@DefCountDays	AS INTEGER,
	@HospitalID		as integer,
    @LUText as varchar(255))
AS 

	update DefLU_DeficiencyCode set 
	[DisplayCode] 		= @DisplayCode, 
	[UserDescription] 	= @UserDescription,
	[ValidFrom] 		= @ValidFrom, 
	[ValidTo] 		= @ValidTo, 
    [LUText] = @LUText, 
	[InterfaceIn] 		= @InterfaceIn,
	[HospitalID]		= @HospitalID,
	[AssociationID] 		= @AssociationID,
	[DefCountDays]		= @DefCountDays,
	[LinkDefCode]		= @LinkDefCode
	where [Code] 		= @Code
	return 0


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE  PROCEDURE [U_LU_DeficiencyStatus]
	(@Code			[int],
	 @DisplayCode	 	[varchar](50),
	 @UserDescription 	[varchar](255),
	 @ValidFrom	 	[datetime],
	 @ValidTo		[datetime],
	 @InterfaceIn	 	[varchar](50),
	 @NumberDays	 	[int],
	 @SuspensionType 	[int],
	 @LetterNameE	 	[varchar](50),
	 @LetterNameF	 	[varchar](50),
	 @LetterNameS	 	[varchar](50),
	 @HospitalID		[int],
     @LUText [varchar](255))

AS update [dbo].[DefLU_ChartStatus] 
set  	 [DisplayCode]	 	= @DisplayCode,
	 [UserDescription]	= @UserDescription,
	 [ValidFrom]	 	= @ValidFrom,
	 [ValidTo]	 	= @ValidTo,
     [LUText] = @LUText, 
	 [InterfaceIn]	 	= @InterfaceIn,
	 [HospitalID]		= @HospitalID,
	 [NumberDays]	 	= @NumberDays,
	 [SuspensionType]	= @SuspensionType,
	 [LetterNameE]	 	= @LetterNameE,
	 [LetterNameF]	 	= @LetterNameF,
	 [LetterNameS]	 	= @LetterNameS 
where 
	([Code]	 		= @Code)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



-- This is called by the Save Method of the Institution 10 Look Up Maint Sub-Form
CREATE   PROCEDURE [U_LU_DirectBillFeeCodes]
	(@Code 		[int],
	 @DisplayCode		[varchar](50),
	 @UserDescription	[varchar](255),
	 @DefaultDescription	[varchar](255),
	 @CIHIValue		[varchar](12),
	 @ValidFrom 		[datetime],
	 @ValidTo 		[datetime],
	 @InterfaceIn	 	[varchar](50),
	 @ItemPrice		[money],
	 @ItemTaxType		[int],
	 @HospitalID		[int],
     @LUText [varchar](255))
AS 

update LU_DirectBillFeeCodes set
	[DisplayCode] 		= @DisplayCode, 
	[UserDescription] 	= @UserDescription,
	[ValidFrom] 		= @ValidFrom, 
	[ValidTo] 		= @ValidTo,
    [LUText] = @LUText, 
	[InterfaceIn] 		= @InterfaceIn,
	[HospitalID]		= @HospitalID,
	[ItemPrice] 		= @ItemPrice,
	[ItemTaxType] 		= @ItemTaxType
where [Code] 			=  @Code
return 0


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



-- This is called by the Save Method of the General Look Up Maint Sub-Form
CREATE   PROCEDURE [U_LU_General] 
   (@TableName             AS varchar(50),
   @Code                   AS varchar(50),
   @DisplayCode            AS varchar(50),
   @UserDescription        AS varchar(250),
   @DefaultDescription     AS varchar(250),
   @CIHIValue              AS varchar(50),
   @ValidFrom              AS varchar(10),
   @ValidTo                AS varchar(10),
   @InterfaceIn            AS varchar(50),
   @HospitalID             as varchar(100),
   @LUText                 as varchar(255))
AS 

   declare @SQL varchar(2000)
   set @Displaycode = replace(@DisplayCode, '''',  '''''')
   set @UserDescription = replace(@UserDescription, '''',  '''''')
   set @DefaultDescription = replace(@DefaultDescription, '''',  '''''')
   set @InterfaceIn = replace(@InterfaceIn, '''',  '''''')

   if isnumeric(@TableName) <> 0
           update LU_CodeFile set [DisplayCode] = @DisplayCode, [UserDescription] = @UserDescription, [ValidFrom] = @ValidFrom, [ValidTo] = @ValidTo, [LUText] = @LUText, [InterfaceIn] = @InterfaceIn, [HospitalID] = @HospitalID where [LookUpID] = @TableName AND [Code] = @Code
   else
           select @SQL = 'update ' + @TableName + ' set [DisplayCode] = ''' + @DisplayCode + ''', [UserDescription] = ''' + @UserDescription + ''',
                   [ValidFrom] = ''' + @ValidFrom + ''', [ValidTo] = ''' + @ValidTo + ''', [LUText] = ''' + @LUText + ''', [InterfaceIn] = ''' + @InterfaceIn + ''', [HospitalID] = ' + @HospitalID + ' where [Code] = ' + @Code
           execute (@SQL)
   
   return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



-- This is called by the Save Method of the General Look Up Maint Sub-Form
CREATE   PROCEDURE [U_LU_General_NoCIHI]
	(@TableName 		AS varchar(50),
	@Code			AS varchar(50),
	@DisplayCode 		AS varchar(50),
	@UserDescription 	AS varchar(250),
	@ValidFrom		AS varchar(10),
	@ValidTo		AS varchar(10),
	@InterfaceIn		AS varchar(50),
	@HospitalID		as varchar(100),
    @LUText         as varchar(255))
AS 

	declare @SQL varchar(500)

   	set @Displaycode = replace(@DisplayCode, '''',  '''''')
   	set @UserDescription = replace(@UserDescription, '''',  '''''')
   	set @InterfaceIn = replace(@InterfaceIn, '''',  '''''') --RM [2007/05/29]

	select @SQL = 'update ' + @TableName + ' set [DisplayCode] = ''' + @DisplayCode + ''', [UserDescription] = ''' + @UserDescription + ''',
			[ValidFrom] = ''' + @ValidFrom + ''', [ValidTo] = ''' + @ValidTo + ''', [LUText] = ''' + @LUText + ''', [InterfaceIn] = ''' + @InterfaceIn + ''', [HospitalID] = ' + @HospitalID + '
			where [Code] = ' + @Code
	execute (@SQL)
	return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
-- This is called by the Save Method of the General Look Up Maint Sub-Form w/Associate ID's
CREATE   PROCEDURE [U_LU_GeneralAssoc]
	(@TableName 		AS varchar(50),
	@AssocCode		AS varchar(50),
	@Code			AS varchar(50),
	@DisplayCode 		AS varchar(50),
	@UserDescription 	AS varchar(250),
	@DefaultDescription	AS varchar(250),
	@CIHIValue		AS varchar(50),
	@ValidFrom		AS varchar(10),
	@ValidTo		AS varchar(10),
	@InterfaceIn		AS varchar(50),
	@HospitalID		as varchar(100),
    @LUText         as varchar(255))
AS 

	declare @SQL varchar(500)
	
   	set @Displaycode = replace(@DisplayCode, '''',  '''''')
   	set @UserDescription = replace(@UserDescription, '''',  '''''')
   	set @DefaultDescription = replace(@DefaultDescription, '''',  '''''')
   	set @InterfaceIn = replace(@InterfaceIn, '''',  '''''')

	select @SQL = 'update ' + @TableName + ' set 
				[DisplayCode] = ''' + @DisplayCode + ''', 
				[UserDescription] = ''' + @UserDescription + ''',
				[ValidFrom] = ''' + @ValidFrom + ''', 
				[ValidTo] = ''' + @ValidTo + ''', 
                [LUText] = ''' + @LUText + ''', 
				[InterfaceIn] = ''' + @InterfaceIn + ''', 
				[HospitalID] = ' + @HospitalID + '
			where [Code] = ' + @Code + '
			AND [AssociationID] = ' + @AssocCode
	execute (@SQL)
	return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE   PROCEDURE [U_LU_ICD10Diag]
	(@Code 		[int],
	@DisplayCode		[varchar](50),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@CIHIValue		[varchar](20),
	@ValidFrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](50),
	@IsMain		[varchar](1),
	@ICDGender		[varchar](1),
	@AgeLow		[int],
	@AgeHigh		[int],
	@ICD9			[varchar](10),
	@ICD9CM		[varchar](10),
	@ICDNotes		[varchar](255),
	@ProjectLink 		[int],
	@ICDLink		[int],
    @LUText [varchar](255))
AS 

update ICD_DiagFile10 set
	[DisplayCode]  		= @DisplayCode,
	[UserDescription]	= @UserDescription,
	[DefaultDescription]	= @DefaultDescription,
	[CIHIValue]		= @CIHIValue, 
	[ValidFrom]		= @ValidFrom,
	[ValidTo]		= @ValidTo,
    [LUText] = @LUText, 
	[InterfaceIn]		= @InterfaceIn,
	[MRDxFlag]		= @IsMain,
	[DiagnosisGender]	= @ICDGender,
	[AgeLow]		= @AgeLow,
	[AgeHigh]		= @AgeHigh,
	[ICD9]			= @ICD9,
	[ICD9CM]		= @ICD9CM,
	[ICDNotes]		= @ICDNotes,
	[ProjectLink]		= @ProjectLink,
	[ICDLink]		= @ICDLink
where [Code] 			= @Code

update NU_Codes set ValidFrom = @ValidFrom, ValidTo = @ValidTo, ICDNotes = @ICDNotes where CIHIValue =  @CIHIValue


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [U_LU_ICD10DiagCCRS]
		(@Code 		[int],
	@DisplayCode		[varchar](50),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@ShortDescription	[varchar](255),
	@CIHIValue		[varchar](20),
	@Validfrom 		[datetime],
	@ValidTo 		[datetime],
	@ICDGender		[varchar](1),
	@AgeLow		[int],
	@AgeHigh		[int],
	@InterfaceIn	 	[varchar](50),
    @LUText        [varchar](255)
)
AS 

update ICD_DiagFileMDS set
	[DisplayCode]  		= @DisplayCode,
	[UserDescription]	= @UserDescription,
	[DefaultDescription]	= @DefaultDescription,
	[ShortDescription]	= @ShortDescription,
	[CIHIValue]		= @CIHIValue, 
	[ValidFrom]		= @ValidFrom,
	[ValidTo]		= @ValidTo,
    [LUText] = @LUText, 
	[InterfaceIn]		= @InterfaceIn,
	[DiagnosisGender]	= @ICDGender,
	[AgeLow]		= @AgeLow,
	[AgeHigh]		= @AgeHigh
where [Code] 			= @Code
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE   PROCEDURE [U_LU_ICD10Interv]
	(@Code 		[int],
	@DisplayCode		[varchar](50),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@CIHIValue		[varchar](20),
	@ValidFrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](50),
	@ICDGender		[varchar](1),
	@AgeLow		[int],
	@AgeHigh		[int],
	@ICD9			[varchar](10),
	@ICD9CM		[varchar](10),
	@ICDNotes		[varchar](255),
	@ProjectLink		[int],
	@ICDLink		[int],
    @LUText [varchar](255))
AS 

update ICD_ProcFile10 set
	[DisplayCode]  		= @DisplayCode,
	[UserDescription]	= @UserDescription,
	[DefaultDescription]	= @DefaultDescription,
	[CIHIValue]		= @CIHIValue, 
	[ValidFrom]		= @ValidFrom,
	[ValidTo]		= @ValidTo,
    [LUText] = @LUText, 
	[InterfaceIn]		= @InterfaceIn,
	[DiagnosisGender]	= @ICDGender,
	[AgeLow]		= @AgeLow,
	[AgeHigh]		= @AgeHigh,
	[ICD9]			= @ICD9,
	[ICD9CM]		= @ICD9CM,
	[ICDNotes]		= @ICDNotes,
	[ProjectLink]		= @ProjectLink,
	[ICDLink]		= @ICDLink
where [Code] 			= @Code

update NU_IntCodes set ValidFrom = @ValidFrom, ValidTo = @ValidTo, ICDNotes = @ICDNotes where CIHIValue =  @CIHIValue


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE   PROCEDURE [U_LU_ICD9CMDiag]
	(@Code 		[int],
	@DisplayCode		[varchar](20),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@CIHIValue		[varchar](20),
	@ValidFrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](20),
	@IsMain		[varchar](1),
	@ICDGender		[varchar](1),
	@AgeLow		[int],
	@AgeHigh		[int],
    @LUText [varchar](255))
AS 

update ICD_DiagFile9CM set
	[DisplayCode]  		= @DisplayCode,
	[UserDescription]	= @UserDescription,
	[DefaultDescription]	= @DefaultDescription,
	[CIHIValue]		= @CIHIValue, 
	[ValidFrom]		= @ValidFrom,
	[ValidTo]		= @ValidTo,
    [LUText] = @LUText, 
	[InterfaceIn]		= @InterfaceIn,
	[MRDxFlag]		= @IsMain,
	[DiagnosisGender]	= @ICDGender,
	[AgeLow]		= @AgeLow,
	[AgeHigh]		= @AgeHigh
where [Code] 			= @Code


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE   PROCEDURE [U_LU_ICD9CMInterv]
	(@Code 		[int],
	@DisplayCode		[varchar](20),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@CIHIValue		[varchar](20),
	@ValidFrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](20),
	@ICDGender		[varchar](1),
	@AgeLow		[int],
	@AgeHigh		[int],
    @LUText [varchar](255))
AS 

update ICD_ProcFile9CM set
	[DisplayCode]  		= @DisplayCode,
	[UserDescription]	= @UserDescription,
	[DefaultDescription]	= @DefaultDescription,
	[CIHIValue]		= @CIHIValue, 
	[ValidFrom]		= @ValidFrom,
	[ValidTo]		= @ValidTo,
    [LUText] = @LUText, 
	[InterfaceIn]		= @InterfaceIn,
	[DiagnosisGender]	= @ICDGender,
	[AgeLow]		= @AgeLow,
	[AgeHigh]		= @AgeHigh
where [Code] 			= @Code


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE   PROCEDURE [U_LU_ICD9Diag]
	(@Code 		[int],
	@DisplayCode		[varchar](20),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@CIHIValue		[varchar](20),
	@ValidFrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](20),
	@IsMain		[varchar](1),
	@ICDGender		[varchar](1),
	@AgeLow		[int],
	@AgeHigh		[int],
    @LUText [varchar](255))
AS 

update ICD_DiagFile9 set
	[DisplayCode]  		= @DisplayCode,
	[UserDescription]	= @UserDescription,
	[DefaultDescription]	= @DefaultDescription,
	[CIHIValue]		= @CIHIValue, 
	[ValidFrom]		= @ValidFrom,
	[ValidTo]		= @ValidTo,
    [LUText] = @LUText, 
	[InterfaceIn]		= @InterfaceIn,
	[MRDxFlag]		= @IsMain,
	[DiagnosisGender]	= @ICDGender,
	[AgeLow]		= @AgeLow,
	[AgeHigh]		= @AgeHigh
where [Code] 			= @Code


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE   PROCEDURE [U_LU_ICD9Interv]
	(@Code 		[int],
	@DisplayCode		[varchar](20),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@CIHIValue		[varchar](20),
	@ValidFrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](20),
	@ICDGender		[varchar](1),
	@AgeLow		[int],
	@AgeHigh		[int],
    @LUText [varchar](255))
AS 

update ICD_ProcFile9 set
	[DisplayCode]  		= @DisplayCode,
	[UserDescription]	= @UserDescription,
	[DefaultDescription]	= @DefaultDescription,
	[CIHIValue]		= @CIHIValue, 
	[ValidFrom]		= @ValidFrom,
	[ValidTo]		= @ValidTo,
    [LUText] = @LUText, 
	[InterfaceIn]		= @InterfaceIn,
	[DiagnosisGender]	= @ICDGender,
	[AgeLow]		= @AgeLow,
	[AgeHigh]		= @AgeHigh
where [Code] 			= @Code


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



-- This is called by the Save Method of the Institution 10 Look Up Maint Sub-Form
CREATE   PROCEDURE [U_LU_Institution10]
	(@Code 		[int],
	 @DisplayCode		[varchar](50),
	 @UserDescription	[varchar](255),
	 @DefaultDescription	[varchar](255),
	 @CIHIValue		[varchar](12),
	 @ValidFrom 		[datetime],
	 @ValidTo 		[datetime],
	 @InterfaceIn	 	[varchar](50),
	 @InstCareType		[varchar](1),
	 @HospitalType		[varchar](2),
	 @HospitalID 		[int],
     @LUText [varchar](255),
     @InstitutionType  varchar(1)
     )
AS 

update LU_Institution_10 set
	[DisplayCode] 		= @DisplayCode, 
	[UserDescription] 	= @UserDescription,
	[ValidFrom] 		= @ValidFrom, 
	[ValidTo] 		= @ValidTo,
    [LUText] = @LUText, 
	[InterfaceIn] 		= @InterfaceIn,
	[HospitalID]		= @HospitalID,
	[InstCareType] 		= @InstCareType,
	[HospitalType] 		= @HospitalType,
    InstitutionType     = @InstitutionType
where [Code] 			=  @Code
return 0


GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO


CREATE     PROCEDURE [U_LU_LoanLocationType]
	(@Code 		[int],
	@DisplayCode		[varchar](50),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@CIHIValue		[varchar](20),
	@Validfrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](50),
	@HospitalID		[int],
    	@LUText 		[varchar](255),
	@LoanDays		[int])
AS 

update [LoanLU_LocationType] 
set  	
	[DisplayCode]	 	= @DisplayCode,
	[UserDescription]	= @UserDescription,
	[ValidFrom]	 	= @ValidFrom,
	[ValidTo]	 	= @ValidTo,
	[InterfaceIn]	 	= @InterfaceIn,
	[HospitalID]		= @HospitalID,
    	[LUText] 		= @LUText, 
	[LoanDays]		= @LoanDays
where 
	([Code]	 		= @Code)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE     PROCEDURE [U_LU_MDAS_Group]
   (@Code                   as int,
   @DisplayCode            as varchar(50),
   @UserDescription        as varchar(250),
   @DefaultDescription     as varchar(250),
   @CIHIValue              as varchar(50),
   @Validfrom              as datetime,
   @ValidTo                as datetime, 
   @InterfaceIn            as varchar(12),
   @HospitalID             as int,
   @LUText                 as varchar(255),
   @SensitivityLevel	   as int)
AS 
	update LU_CodeFile 
	set 
		[DisplayCode] 		= @DisplayCode,
		[UserDescription] 	= @UserDescription,
		[ValidFrom]		= @ValidFrom,
		[ValidTo]		= @ValidTo,
		[LUText] 		= @LUText, 
		[InterfaceIn]		= @InterfaceIn,
		[HospitalID]		= @HospitalID
	where [Code] = @Code
	
	delete LLU_MDAS_Group_Sensitivity where LUCode = @Code
	insert into LLU_MDAS_Group_Sensitivity (LUCode, SensitivityLevel) values (@Code, @SensitivityLevel)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [U_LU_MISCode]
	(@Code 	[int],
	 @DisplayCode 	[varchar](50),
	 @UserDescription 	[varchar](255),
	 @DefaultDescription	[varchar](255),
	 @CIHIValue 	[varchar](20),
	 @ValidFrom 	[datetime],
	 @ValidTo 	[datetime],
	 @InterfaceIn 	[varchar](50),
	 @HospitalID 	[int],
	 @AMCareType 	[int],
     @LUText [varchar](255),
	 @AmCareTypeCode [varchar](50),     --ED - 02297
	 @AmCareGroup 	[varchar](50),
     @ClinicLite    [int] 
)
AS 
update [dbo].[LU_MISCode] 

set  [DisplayCode]	 = @DisplayCode,
	 [UserDescription]	 = @UserDescription,
	 [DefaultDescription]	 = @DefaultDescription,
	 [CIHIValue]	 = @CIHIValue,
	 [ValidFrom]	 = @ValidFrom,
	 [ValidTo]	 = @ValidTo,
     [LUText] 	 = @LUText, 
	 [InterfaceIn]	 = @InterfaceIn,
	 [HospitalID]	 = @HospitalID,
	 [AMCareType]	 = @AMCareType,
	 [AmCareTypeCode]= @AmCareTypeCode, 
	 [AmCareGroup]	 = @AmCareGroup,
     [ClinicLite]    = @ClinicLite

where 
	( [Code]	 = @Code)
return 0



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [U_LU_OR_GeneralLink]
(
    @TableName              as varchar(100),
    @Code                   as varchar(50),
    @DisplayCode            as varchar(50),
    @UserDescription        as varchar(250),
    @DefaultDescription     as varchar(250),
    @CIHIValue              as varchar(50),
    @Validfrom              as varchar(10),
    @ValidTo                as varchar(10), 
    @InterfaceIn            as varchar(50),
    @HospitalID             as varchar(100),
    @LUText                 as varchar(255),
	@AssociationID          as int
)
AS 
    declare @SQL varchar(2000)
    set @Displaycode = replace(@DisplayCode, '''',  '''''')
    set @UserDescription = replace(@UserDescription, '''',  '''''')
    set @DefaultDescription = replace(@DefaultDescription, '''',  '''''')
    set @InterfaceIn = replace(@InterfaceIn, '''',  '''''')
    if @AssociationID is null set @AssociationID = 0
    
    select @SQL = 'update ' + @TableName + ' set [DisplayCode] = ''' + @DisplayCode + ''', [UserDescription] = ''' + @UserDescription + ''',
           [ValidFrom] = ''' + @ValidFrom + ''', [ValidTo] = ''' + @ValidTo + ''', [LUText] = ''' + @LUText + ''', [InterfaceIn] = ''' + @InterfaceIn + ''', [HospitalID] = ' + @HospitalID + ', 
           AssociationID = ' + cast(@AssociationID as varchar(10)) + ' where [Code] = ' + @Code
    execute (@SQL)
   
   return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE    PROCEDURE [U_LU_PatientService]
	(@Code 		[int],
	@DisplayCode		[varchar](50),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@CIHIValue		[varchar](20),
	@ValidFrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](50),
	@ProjectLink		[int],
	@HospitalID		[int],
    @LUText [varchar](255))
AS 

update LU_PatientService set
	[DisplayCode]  		= @DisplayCode,
	[UserDescription]	= @UserDescription,
	[DefaultDescription]	= @DefaultDescription,
	[CIHIValue]		= @CIHIValue, 
	[ValidFrom]		= @ValidFrom,
	[ValidTo]		= @ValidTo,
    [LUText] = @LUText, 
	[InterfaceIn]		= @InterfaceIn,
	[HospitalID]		= @HospitalID,
	[ProjectLink]		= @ProjectLink	
where [Code] 			= @Code


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is called by the Save Method of the General Look Up Maint Sub-Form
CREATE  PROCEDURE [U_LU_PostalCode] 
	(@Code			AS varchar(50),
	@DisplayCode 		AS varchar(50),
	@UserDescription 	AS varchar(250),
	@DefaultDescription	AS varchar(250),
	@CIHIValue		AS varchar(50),
	@ValidFrom		AS varchar(10),
	@ValidTo		AS varchar(10),
	@InterfaceIn		AS varchar(50),
	@LinkCode		AS varchar(12),
	@HospitalID		as varchar(100),
    @LUText         as varchar(255))
AS 

	declare @SQL varchar(5000) --PR-01624

   	set @Displaycode = replace(@DisplayCode, '''',  '''''')
   	set @CIHIValue = upper(replace(replace(@CIHIValue, '''',  ''), ' ', '')) --ED - 01714
   	set @InterfaceIn = replace(@InterfaceIn, '''',  '''''')
	set @UserDescription = replace(@UserDescription, '''', '''''') --PR-01277
	set @DefaultDescription = replace(@DefaultDescription, '''', '''''') --PR-01277
	
	select @SQL = 'update LU_PostalCode set	
				[DisplayCode] = ''' + @DisplayCode + ''', 
				[UserDescription] = ''' + @UserDescription + ''',
				[ValidFrom] = ''' + @ValidFrom + ''', 
				[ValidTo] = ''' + @ValidTo + ''', 
                			[LUText] = ''' + @LUText + ''', 
				[InterfaceIn] = ''' + @InterfaceIn + ''',
				[LinkCode] = ''' + @LinkCode + ''', 
				[HospitalID] = ' + @HospitalID + '
			where [Code] = ' + @Code
	execute (@SQL)
	return 0
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE     PROCEDURE [U_LU_Project]
	(@Code			[int],
	@DisplayCode 		[varchar](50),
	@UserDescription 	[varchar](250),
	@DefaultDescription	[varchar](250),
	@CIHIValue		[varchar](50),
	@ValidFrom		[datetime],
	@ValidTo		[datetime], 
	@InterfaceIn		[varchar](50),
	@QuestionState1 	[int],
	@Question1		[varchar](100),
	@QuestionState2 	[int],
	@Question2		[varchar](100),
	@QuestionState3 	[int],
	@Question3		[varchar](100),
	@QuestionState4 	[int],
	@Question4		[varchar](100),
	@QuestionState5 	[int],
	@Question5		[varchar](100),
	@QuestionState6 	[int],
	@Question6		[varchar](100),
	@QuestionState7 	[int],
	@Question7		[varchar](100),
	@QuestionState8 	[int],
	@Question8		[varchar](100),
	@QuestionState9 	[int],
	@Question9		[varchar](100),
	@QuestionState10 	[int],
	@Question10		[varchar](100),
	@QuestionState11 	[int],
	@Question11		[varchar](100),
	@QuestionState12 	[int],
	@Question12		[varchar](100),
	@QuestionState13 	[int],
	@Question13		[varchar](100),
	@QuestionState14 	[int],
	@Question14	 	[varchar](100),
	@QuestionState15 	[int],
	@Question15 		[varchar](100),
	@QuestionState16 	[int],
	@Question16		[varchar](100),
	@QuestionState17 	[int],
	@Question17	 	[varchar](100),
	@QuestionDefault1 	[int], 
	@QuestionDefault2 	[int], 
	@QuestionDefault3 	[int], 
	@QuestionDefault4 	[int], 
	@QuestionDefault5 	[int], 
	@QuestionDefault6 	[int], 
	@QuestionDefault7 	[int], 
	@QuestionDefault8 	[int], 
	@QuestionDefault9 	[int], 
	@QuestionDefault10 	[int], 
	@QuestionDefault11 	[int], 
	@QuestionDefault12 	[int], 
	@QuestionDefault13 	[int], 
	@QuestionDefault14 	[varchar](10), 
	@QuestionDefault15 	[varchar](10), 
	@QuestionDefault16 	[varchar](10), 
	@QuestionDefault17 	[varchar](10),
	@HospitalID		    [int],
    @LUText 		    [varchar](255),
	@Question18	 	    [varchar](100),
	@QuestionState18 	[int],
	@QuestionDefault18 	[varchar](10),
	@Question19	 	    [varchar](100),
	@QuestionState19 	[int],
	@QuestionDefault19 	[varchar](10),
	@Question20	 	    [varchar](100),
	@QuestionState20 	[int],
	@QuestionDefault20 	[varchar](10),
	@Question21	 	    [varchar](100),
	@QuestionState21 	[int],
	@QuestionDefault21 	[varchar](10),
	@Question22	 	    [varchar](100),
	@QuestionState22 	[int],
	@QuestionDefault22 	[varchar](10),
	@Question23	 	    [varchar](100),
	@QuestionState23 	[int],
	@QuestionDefault23 	[varchar](10),
	@Question24	 	    [varchar](100),
	@QuestionState24 	[int],
	@QuestionDefault24 	[varchar](10)
)
AS 
update LU_Project 
set 
	[DisplayCode] 		= @DisplayCode,
	[UserDescription] 	= @UserDescription,
	[DefaultDescription] 	= @DefaultDescription,
	[CIHIValue]		= @CIHIValue,
	[ValidFrom]		= @ValidFrom,
	[ValidTo]		= @ValidTo,
    [LUText] = @LUText, 
	[InterfaceIn]		= @InterfaceIn,
	[HospitalID]		= @HospitalID,
	[QuestionState1]		= @QuestionState1, 	
	[Question1]		= @Question1,
	[QuestionState2]		= @QuestionState2 ,
	[Question2]		= @Question2,
	[QuestionState3]		= @QuestionState3 ,
	[Question3]		= @Question3,
	[QuestionState4]		= @QuestionState4 ,
	[Question4]		= @Question4,
	[QuestionState5]		= @QuestionState5,
	[Question5]		= @Question5,
	[QuestionState6]		= @QuestionState6,
	[Question6]		= @Question6,
	[QuestionState7]		= @QuestionState7,
	[Question7]		= @Question7,
	[QuestionState8]		= @QuestionState8,
	[Question8]		= @Question8,	
	[QuestionState9]		= @QuestionState9,
	[Question9]		= @Question9,
	[QuestionState10]	= @QuestionState10,
	[Question10]		= @Question10,
	[QuestionState11]	= @QuestionState11,
	[Question11] 		= @Question11,
	[QuestionState12]	= @QuestionState12,
	[Question12]		= @Question12,
	[QuestionState13] 	= @QuestionState13,
	[Question13]		= @Question13,
	[QuestionState14]	= @QuestionState14,
	[Question14]		= @Question14,
	[QuestionState15]	= @QuestionState15,
	[Question15]		= @Question15,
	[QuestionState16]	= @QuestionState16,
	[Question16]		= @Question16,
	[QuestionState17]	= @QuestionState17,
	[Question17]		= @Question17,
	[QuestionDefault1] 	= @QuestionDefault1, 
	[QuestionDefault2]	= @QuestionDefault2, 
	[QuestionDefault3]	= @QuestionDefault3, 
	[QuestionDefault4] 	= @QuestionDefault4, 
	[QuestionDefault5] 	= @QuestionDefault5, 
	[QuestionDefault6] 	= @QuestionDefault6, 
	[QuestionDefault7] 	= @QuestionDefault7, 
	[QuestionDefault8] 	= @QuestionDefault8, 
	[QuestionDefault9] 	= @QuestionDefault9, 
	[QuestionDefault10] 	= @QuestionDefault10, 
	[QuestionDefault11] 	= @QuestionDefault11, 
	[QuestionDefault12] 	= @QuestionDefault12, 
	[QuestionDefault13] 	= @QuestionDefault13, 
	[QuestionDefault14] 	= @QuestionDefault14, 
	[QuestionDefault15] 	= @QuestionDefault15, 
	[QuestionDefault16]	= @QuestionDefault16, 
	[QuestionDefault17] 	= @QuestionDefault17,
	
	[QuestionState18]	= @QuestionState18,
	[Question18]		= @Question18,
	[QuestionDefault18] = @QuestionDefault18, 
	[QuestionState19]	= @QuestionState19,
	[Question19]		= @Question19,
	[QuestionDefault19] = @QuestionDefault19, 
	[QuestionState20]	= @QuestionState20,
	[Question20]		= @Question20,
	[QuestionDefault20] = @QuestionDefault20, 
	[QuestionState21]	= @QuestionState21,
	[Question21]		= @Question21,
	[QuestionDefault21] = @QuestionDefault21, 
	[QuestionState22]	= @QuestionState22,
	[Question22]		= @Question22,
	[QuestionDefault22] = @QuestionDefault22, 
	[QuestionState23]	= @QuestionState23,
	[Question23]		= @Question23,
	[QuestionDefault23] = @QuestionDefault23, 
	[QuestionState24]	= @QuestionState24,
	[Question24]		= @Question24,
	[QuestionDefault24] = @QuestionDefault24 

where [Code] = @Code


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE    PROCEDURE [U_LU_Provider]
	(@Code 		[int],
	@DisplayCode		[varchar](50),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@CIHIValue		[varchar](20),
	@ValidFrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](50),
	@ProvdrAddress		[varchar](255),
	@ProvdrCity		[varchar](35),
	@ProvdrProvince		[varchar](35),
	@ProvdrPostal		[varchar](7),
	@ProvdrHomePhone	[varchar](15),
	@ProvdrCellPhone	[varchar](15),
	@ProvdrOfficePhone	[varchar](15),
	@ProvdrHospitalPhone	[varchar](15),
	@ProvdrFax		[varchar](15),
	@ProvdrEMail		[varchar](50),
	@ProvdrResident		[integer],
	@ProvdrMaxLetter	[integer],
	@ProvdrCredentials	[varchar](255),
	@ProvdrTitle		[varchar](255), 	
	@ProvdrState		[varchar](10),
	@ProvdrLanguage		[int],
	@ProvdrBorrower		[int],
	@ProvdrChiefOfStaff	[int],
	@ProvdrLastVisitDate	[datetime],
	@ProvdrMISCode		[int],
	@TransInitials		[varchar](10),
	@ProvdrBillSpecialty	[int],
	@MoHCode 		[varchar](50), 
	@ProgramCode		[int],
	@HospitalID		[int],
	@ProvdrRequestor 	[int], 
	@MinDeficiency 	 	[int],
	@ProvdrAuthent 	 	[int],
    	@LUText 		[varchar](255),
	@InterfaceIn2	 	[varchar](50),
	@InterfaceIn3	 	[varchar](50),
	@PrefReciept		[int],
	@ProvdrSurName 		[varchar](50), 
	@ProvdrFirstName 	[varchar](50), 
	@ProvdrMiddleName 	[varchar](50), 
	@HCPProgramCode 	[int], 
	@HCPStatus 		[int],
	@CJRRSurgeonID		[varchar](50))
AS 

declare @BCount AS int

set @Displaycode = replace(@displaycode, '''''',  '''') --PR-02563
set @UserDescription = replace(@UserDescription, '''''',  '''') --PR-02563

update [LU_Provider] 
set  	[DisplayCode]	 	= @DisplayCode,
	[UserDescription]	= @UserDescription,
	[DefaultDescription]	= @DefaultDescription,
	[CIHIValue]	 	= @CIHIValue,
	[ValidFrom]	 	= @ValidFrom,
	[ValidTo]	 	= @ValidTo,
    	[LUText] 		= @LUText, 
	[InterfaceIn]	 	= @InterfaceIn,
	[InterfaceIn2]	 	= @InterfaceIn2,
	[InterfaceIn3]	 	= @InterfaceIn3,
	[HospitalID]		= @HospitalID,
	[PrefReciept]		= @PrefReciept,
	[ProvdrAddress]		= @ProvdrAddress,
	[ProvdrCity]		= @ProvdrCity,
	[ProvdrProvince]	= @ProvdrProvince,
	[ProvdrPostal]		= @ProvdrPostal,
	[ProvdrHomePhone]	= @ProvdrHomePhone,
	[ProvdrCellPhone]	= @ProvdrCellPhone,
	[ProvdrOfficePhone]	= @ProvdrOfficePhone,
	[ProvdrHospitalPhone]	= @ProvdrHospitalPhone,
	[ProvdrFax]		= @ProvdrFax,
	[ProvdrEMail]		= @ProvdrEMail,
	[ProvdrResident]	= @ProvdrResident,
	[ProvdrMaxLetter]	= @ProvdrMaxLetter,
	[ProvdrCredentials]	= @ProvdrCredentials,
	[ProvdrTitle]		= @ProvdrTitle,
	[ProvdrState]		= @ProvdrState,
	[ProvdrLanguage]	= @ProvdrLanguage,
	[ProvdrBorrower]	= @ProvdrBorrower,
	[ProvdrChiefOfStaff]	= @ProvdrChiefOfStaff,
	[ProvdrLastVisitDate]	= @ProvdrLastVisitDate,
	[ProvdrMISCode]		= @ProvdrMISCode,
	[TransInitials]		= @TransInitials,
	[ProvdrBillSpecialty]	= @ProvdrBillSpecialty,
	[MoHCode]		= @MoHCode, 
	[ProgramCode]		= @ProgramCode,
	[ProvdrRequestor]	= @ProvdrRequestor,
	[MinDeficiency]		= @MinDeficiency,
	[ProvdrAuthent]		= @ProvdrAuthent,
	[ProvdrSurName]		= @ProvdrSurName,
	[ProvdrFirstName]	= @ProvdrFirstName,
	[ProvdrMiddleName]	= @ProvdrMiddleName,
	[HCPProgramCode]	= @HCPProgramCode,
	[HCPStatus]		= @HCPStatus,
	[CJRRSurgeonID]		= @CJRRSurgeonID
where 
	([Code]	 		= @Code)

--If there is a Borrower Code
if @ProvdrBorrower > 0
	update [LoanLU_Borrower] set [UserDescription] = @UserDescription, [BorrowerAddress] = @ProvdrAddress, [BorrowerCity] = @ProvdrCity, [ValidFrom] = @ValidFrom, [ValidTo] = @ValidTo, [BorrowerProvince] = @ProvdrProvince, [BorrowerPostal] = @ProvdrPostal, [BorrowerPhone] = @ProvdrOfficePhone, [HospitalID] = @HospitalID where ([Code] = @ProvdrBorrower)

--If there is a ROI Requestor
if @ProvdrRequestor > 0
	update [LU_ROI_Requesters] set [UserDescription] = @UserDescription, [ValidFrom] = @ValidFrom, [ValidTo] = @ValidTo,  [Address] = @ProvdrAddress, [PostalCode] = @ProvdrPostal, [Phone] = @ProvdrOfficePhone, [Fax] = @ProvdrFax, [City] = @ProvdrCity, [HospitalID] = @HospitalID where Code = @ProvdrRequestor -- [Province] = @ProvdrProvince,
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE  PROCEDURE [U_LU_Reports]
	(@Code			[int],
	 @UserDescription	[varchar](50),
	 @ReportPath		[varchar](255),
	 @AppID		[int],
	 @RoleID		[int],
	 @ValidFrom		[datetime],
	 @ValidTo	 	[datetime],
	 @EMailFormat 		[int],
	 @HospitalID		[int],
	 @InstitutionNumber 	[int], 
	 @AutoLaunch 		[int],
	 @AutoLaunchLoad	[int],
	 @DistributeKey 		[int],
	 @IsInterface 		[int], 
	 @InterfaceID 		[int])
AS 
UPDATE [dbo].[LU_Reports] 
SET  	 [UserDescription]	= @UserDescription,
	 [ReportPath]	 	= @ReportPath,
	 [AppID]	 		= @AppID,
	 [RoleID]	 	= @RoleID,
	 [ValidFrom]	 	= @ValidFrom,
	 [ValidTo]	 	= @ValidTo,
	 [HospitalID]		= @HospitalID,
	 [EMailFormat]		= @EMailFormat,
	 [InstitutionNumber]	= @InstitutionNumber, 
	 [AutoLaunch]		= @AutoLaunch,
	 [AutoLaunchLoad]	= @AutoLaunchLoad,
	 [DistributeKey]		= @DistributeKey,
	 [IsInterface]		= @IsInterface,
	 [InterfaceID]		= @InterfaceID
WHERE 
	([Code]	 		= @Code)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE  PROCEDURE [U_LU_RequestPriority]
	(@Code 		[int],
	@DisplayCode		[varchar](50),
	@UserDescription	[varchar](255),
	@ValidFrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](50),
	@HospitalID		[int],
    @Rate int
)
AS 

UPDATE [LoanLU_RequestPriority] 
SET  	[DisplayCode]	 	= @DisplayCode,
	[UserDescription]	= @UserDescription,
	[ValidFrom]	 	= @ValidFrom,
	[ValidTo]	 	= @ValidTo,
	[InterfaceIn]	 	= @InterfaceIn,
	[HospitalID]		= @HospitalID,
    [PriorityRate]= @Rate
WHERE 
	([Code]	 		= @Code)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE    PROCEDURE [U_LU_ResidenceCode]
	(@Code 		[int],
	@DisplayCode		[varchar](50),
	@UserDescription	[varchar](255),
	@DefaultDescription	[varchar](255),
	@CIHIValue		[varchar](50),
	@ValidFrom 		[datetime],
	@ValidTo 		[datetime],
	@InterfaceIn	 	[varchar](50),
	@HospitalID		[int],
    	@LUText [varchar](255),
	@ProvinceCode 		[int],
	@RegionCode		[int])
AS 

update LU_ResidenceCode set
	[DisplayCode]  		= @DisplayCode,
	[UserDescription]	= @UserDescription,
	[DefaultDescription]	= @DefaultDescription,
	[CIHIValue]		= @CIHIValue, 
	[ValidFrom]		= @ValidFrom,
	[ValidTo]		= @ValidTo,
    	[LUText] 		= @LUText, 
	[InterfaceIn]		= @InterfaceIn,
	[HospitalID]		= @HospitalID,
	[ProvinceCode]		= @ProvinceCode,	
	[RegionCode]		= @RegionCode

where [Code] 			= @Code



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE  PROCEDURE [U_LU_ROI_AuthTypes]
	(@Code		 	[int],
	 @DisplayCode	 	[varchar](50),
	 @UserDescription 	[varchar](255),
	 @ValidFrom		[datetime],
	 @ValidTo	 	[datetime],
	 @ReportPath		[varchar](255),
	 @InterfaceIn	 	[varchar](50),
	 @HospitalID		[int],
     @LUText [varchar](255))
AS 
update [dbo].[LU_ROI_AuthorizationType] 
set  	 [DisplayCode]	 	= @DisplayCode,
	 [UserDescription]	= @UserDescription,
	 [ReportPath]	 	= @ReportPath,
	 [ValidFrom]	 	= @ValidFrom,
	 [ValidTo]	 	= @ValidTo,
     [LUText] = @LUText, 
	 [InterfaceIn]	 	= @InterfaceIn,
	 [HospitalID]		= @HospitalID
where 
	([Code]	 = @Code)


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO



CREATE  PROCEDURE [U_LU_ROI_Contacts]
	(@AssociationID 	[int],
	 @Code		 	[int],
	 @DisplayCode	 	[varchar](50),
	 @UserDescription 	[varchar](255),
	 @ValidFrom	 	[datetime],
	 @ValidTo		[datetime],
	 @Phone		[varchar](20),
	 @PhoneExt	 	[varchar](10),
	 @Fax		 	[varchar](20),
	 @InterfaceIn	 	[varchar](50),
	 @EMail		[varchar](50),
	 @HospitalID		[int],
     	 @LUText [varchar](255))
AS 
update [dbo].[LU_ROI_Contacts] 
set  	 [DisplayCode]	 	= @DisplayCode,
	 [UserDescription]	= @UserDescription,
	 [ValidFrom]	 	= @ValidFrom,
	 [ValidTo]	 	= @ValidTo,
     	 [LUText] 		= @LUText, 
	 [EMail]			= @EMail,
	 [Phone]	 	= @Phone,
	 [PhoneExt]	 	= @PhoneExt,
	 [Fax]	 		= @Fax,
	 [InterfaceIn]	 	= @InterfaceIn,
	 [HospitalID]		= @HospitalID
where 
	([Code]	= @Code AND [AssociationID] = @AssociationID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [U_LU_ROI_Requesters]
	(@Code 		[int],
	 @DisplayCode		[varchar](50),
	 @UserDescription	[varchar](255),
	 @ValidFrom	 	[datetime],
	 @ValidTo		[datetime],
	 @Address		[varchar](255),
	 @PostalCode	 	[varchar](20),
	 @BillingAddress	 	[varchar](255),
	 @BillingPostalCode	[varchar](20),
	 @Phone		[varchar](20),
	 @Fax		 	[varchar](20),
	 @MaxTaxLevel 	[int],
	 @RequesterType 	[int],
	 @InterfaceIn	 	[varchar](50),
	 @CostLevel		[int],
	 @City 			[varchar](30), 
	 @Province 		[int], 
	 @Country 		[int],
	 @BillingCity 		[varchar](30), 
	 @BillingProvince 	[int], 
	 @BillingCountry 	[int],
	 @HospitalID		[int],
     @LUText 		[varchar](255),
	 @PhoneExt		[varchar](6))
AS 
update [dbo].[LU_ROI_Requesters] 
set  	 [DisplayCode]	 	= @DisplayCode,
	 [UserDescription]	= @UserDescription,
	 [ValidFrom]	 	= @ValidFrom,
	 [ValidTo]	 	= @ValidTo,
     	 [LUText] 		= @LUText, 
	 [Address]	 	= @Address,
	 [City]			= @City,
	 [Province]		= @Province,
	 [Country]		= @Country,
	 [PostalCode]	 	= @PostalCode,
	 [BillingAddress]	 	= @BillingAddress,
	 [BillingCity]		= @BillingCity,
	 [BillingProvince]		= @BillingProvince,
	 [BillingCountry]		= @BillingCountry,
	 [BillingPostalCode]	= @BillingPostalCode,
	 [Phone]	 	= @Phone,
	 [PhoneExt]		= @PhoneExt,
	 [Fax]	 		= @Fax,
	 [RequesterType]	= @RequesterType,
	 [CostLevel]		= @CostLevel,
	 [MaxTaxLevel]	 	= @MaxTaxLevel,
	 [InterfaceIn]	 	= @InterfaceIn,
	 [HospitalID]		= @HospitalID
where 
	([Code]	 = @Code)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [U_LU_ROI_RequestTypes]
	(@Code		 	[int],
	 @DisplayCode	 	[varchar](50),
	 @UserDescription 	[varchar](255),
	 @ValidFrom		[datetime],
	 @ValidTo	 	[datetime],
	 @Chargeable		[int],
	 @AuthRequired		[int],
	 @InterfaceIn	 	[varchar](50),
	 @HospitalID		[int],
     @LUText [varchar](255))
AS 
update [dbo].[LU_ROI_RequestTypes] 
set  	 [DisplayCode]	 	= @DisplayCode,
	 [UserDescription]	= @UserDescription,
	 [Chargeable]	 	= @Chargeable,
	 [AuthRequired]		= @AuthRequired,
	 [ValidFrom]	 	= @ValidFrom,
	 [ValidTo]	 	= @ValidTo,
     [LUText] = @LUText, 
	 [InterfaceIn]	 	= @InterfaceIn,
	 [HospitalID]		= @HospitalID
where 
	([Code]	 = @Code)

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [U_LU_ROI_SentItemTypes]
	(@Code		 	[int],
	 @DisplayCode	 	[varchar](50),
	 @UserDescription 	[varchar](255),
	 @ValidFrom		[datetime],
	 @ValidTo	 	[datetime],
	 @ROIPrice		[money],
	 @TaxType	 	[tinyint],
	 @InterfaceIn	 	[varchar](50),
	 @ROIPrice2		[money],
	 @ROIPrice3		[money],
	 @ROIPrice4		[money],
	 @ROIPrice5		[money],
	 @HospitalID		[int],
     @LUText [varchar](255))
AS 
update [dbo].[LU_ROI_SentItemTypes] 
set  	 [DisplayCode]	 	= @DisplayCode,
	 [UserDescription]	= @UserDescription,
	 [ROIPrice]	 	= @ROIPrice,
	 [ROIPrice2]	 	= @ROIPrice2,
	 [ROIPrice3]	 	= @ROIPrice3,
	 [ROIPrice4]	 	= @ROIPrice4,
	 [ROIPrice5]	 	= @ROIPrice5,
	 [TaxType]	 	= @TaxType,
	 [ValidFrom]	 	= @ValidFrom,
	 [ValidTo]	 	= @ValidTo,
     [LUText] = @LUText, 
     [InterfaceIn]	 	= @InterfaceIn,
	 [HospitalID]		= @HospitalID
where 
	([Code]	 = @Code)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE     PROCEDURE [U_LU_TR_DocumentType]
	(@Code			[int],
	@DisplayCode 		[varchar](50),
	@UserDescription 	[varchar](250),
	@DefaultDescription	[varchar](250),
	@CIHIValue		[varchar](50),
	@ValidFrom		[datetime],
	@ValidTo		[datetime], 
	@InterfaceIn		[varchar](12),
	@TemplatePath		[varchar](255),
	@HospitalID		[int],
    @DefCode int,
    @LUText [varchar](255))
AS 

update LU_TranscriptDocument set 
	[DisplayCode] 		= @DisplayCode,
	[UserDescription]	= @UserDescription,
	[DefaultDescription]	= @DefaultDescription,
	[CIHIValue]		= @CIHIValue, 
	[ValidFrom]		= @ValidFrom,
	[ValidTo]		= @ValidTo, 
    [LUText] = @LUText, 
	[InterfaceIn]		= @InterfaceIn,
	[TemplatePath]		= @TemplatePath,
	[HospitalID]		= @HospitalID,
    DefCode = @DefCode
where [Code] = @Code



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE   PROCEDURE [U_NU_CrossReference]
	(@Code			[int],
	 @EntryValue		[varchar](50),
	 @SearchValue	 	[varchar](50),
	 @LangID as int)

AS 

-- EBV Added @LangID as int parameter

if @LangId=0
begin
	UPDATE [dbo].[NU_CrossReference] 
	SET 	[EntryValue]	= @EntryValue,
		[SearchValue]	= @SearchValue 
	WHERE 
		([Code]	 	= @Code)
end

if @LangId=10000
begin
	UPDATE [dbo].[NU_CrossReferenceFr] 
	SET 	[EntryValue]	= @EntryValue,
		[SearchValue]	= @SearchValue 
	WHERE 
		([Code]	 	= @Code)

end






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO









-- This is called by the Save Method of the General Look Up Maint Sub-Form
CREATE   PROCEDURE [U_NU_LookUps]
	(@TableName 		AS VARCHAR(50),
	@Code			AS VARCHAR(50),
	@CIHIValue 	AS VARCHAR(255),
    	@PublicNote        as varchar(255))
AS 

---- EBV PR-01850 FIX QUOTATION PROBLEM
DECLARE @NOTES VARCHAR(500)
DECLARE @PT INT
DECLARE @STMP AS VARCHAR(50)

SET @NOTES = @PublicNote


SET @PT=1
SET @STMP=''
WHILE @PT<=LEN(@NOTES)
BEGIN
	SET @STMP=@STMP+SUBSTRING(@NOTES,@PT,1)
	IF SUBSTRING(@NOTES,@PT,1)=CHAR(39)
	BEGIN
		
		WHILE SUBSTRING(@NOTES,@PT+1,1)=CHAR(39) AND @PT<LEN(@NOTES)
		BEGIN
			SET @PT=@PT+1
		END
		
			
	END
	SET @PT=@PT+1
END


SET @STMP=REPLACE(@STMP,CHAR(39),CHAR(39)+CHAR(39))
SET @NOTES=@STMP
SET @PublicNote = @NOTES
--- ends EBV PR-01850

	declare @SQL varchar(500)

	select @SQL = 'update ' + @TableName + ' set [ICDNotes] = ''' + @PublicNote + ''' where [Code] = ' + @Code
	execute (@SQL)
	
	if @TableName = 'NU_IntCodes'
		update ICD_ProcFile10 set ICDNotes = @PublicNote where CIHIValue =  @CIHIValue
	
	else if @TableName = 'NU_Codes'
		update ICD_DiagFile10 set ICDNotes = @PublicNote where CIHIValue =  @CIHIValue


	return 0


GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO





CREATE  PROCEDURE [U_NU_Users] -----PR-01753
	(@UserCode	[int],
	 @FolioView 	[varchar](250),
	 @FolioNfo 	[varchar](250),
	 @FolioType	[int])   -- 1= ICD; 2=CCI
AS 

if exists (SELECT * FROM NU_Users WHERE UserCode = @UserCode) 
   begin
        if @FolioType = 1  
	   begin  
		UPDATE [NU_Users] 
		SET 	[FoloiviewICDEn]= @FolioView,
			[FolioNfoICDEn]	= @FolioNfo
		WHERE 	([UserCode]	= @UserCode)
	   end 
	else if @FolioType = 2
	 begin  
		UPDATE [NU_Users] 
		SET	[FoloiviewCCIEn]= @FolioView,
			[FolioNfoCCIEn]	= @FolioNfo
		WHERE 	([UserCode]	= @UserCode)
	   end 
   end
else 
   begin 
	if @FolioType = 1  
	   begin  
		INSERT INTO [NU_Users] 
			([UserCode],[FoloiviewICDEn], [FolioNfoICDEn]) 
		VALUES  (@UserCode,  @FolioView,      @FolioNfo)
	   end 
	else if @FolioType = 2
	 begin  
		INSERT INTO [NU_Users] 
			([UserCode],[FoloiviewCCIEn],[FolioNfoCCIEn]) 
		VALUES 	(@UserCode, @FolioView,      @FolioNfo)
         end 
	
   end






GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [U_OMHRS_SecAA]
	(
	@AppID		[int],
	@AbstractID 	[int],
    @LinkID        	[int],
	@CareType  	[int],
	@HospitalID	[int],
	@Z1 		[int],
	@X2 		[int],
	@X1 		[int],
	@AdmitDate	[datetime],
	@AdmitTime 	[datetime], 
	@LastName 	[varchar] (40), 
	@FirstName 	[varchar] (35), 
	@MiddleName 	[varchar] (15), 
	@X10 		[int],
    @HCNProvince 	[int], 
    @HealthCareNumber 	[varchar] (12), 
	@ChartNumber 	[varchar] (12), 
	@AA3 		[varchar](12),
	@InstitutionNumber 	[int],
	@AA5 		[int],
    @SignOff   	[int],
    @SignDate  	[datetime],
    @SignCoder 	[int],
    @ASignOff 	[int],
    @ASignDate 	[datetime] ,
	@ASignCoder 	[int],
	@EncounterNumber 	[varchar](50), 
	@RegisterNumber 	[varchar](50), 
	@SecondChartRegNumber 	[varchar](50), 
	@MISCode 	[int], 
	@AttendingPhysician 	[int], 
	@RefPhysician 	[int], 
	@AdmittingNurseArea 	[int],
	@X4			[int],
	@FixedChartNumber	[varchar](50),
	@UniversalEpisodeIdentifier	[varchar](50),
    @HospitalAccountRecord varchar(50)
)
AS 

if len(isnull(@EncounterNumber, '')) = 0 set @EncounterNumber = @AA3 --PR-04840

--PR - 07455 not sure why z1 is blank
if isnull(@Z1, 0) = 0 and @AppID > 0
	set @Z1 = (case @AppID when 650 then 200373 
	                       when 651 then 200377 
	                       when 652 then 200374 
	                       when 653 then 200376 
	                       when 654 then 200375 
	                       else @Z1 end) 


UPDATE [OMHRS_SecAA] 
SET  
	[Z1]	 		= @Z1,
	[X2]	 		= @X2,
	[X1]	 		= (case when isnull(X1, 0) = 0 then @X1 else X1 end),  --PR - 05117 I suspect the X1 is updated in WinRecs
	--[X1]	 		= @X1,  --PR - 05117
	[HospitalID]	= @HospitalID,		-- PR-00599
	[AdmitDate] 	= @AdmitDate,
	[AdmitTime]		= @AdmitTime, 
	[LastName] 		= @LastName , 
	[FirstName] 	= @FirstName, 
	[MiddleName] 	= @MiddleName, 
	[X10]	 		= @X10,
    [HCNProvince] 		= @HCNProvince, 
    [HealthCareNumber] 	= @HealthCareNumber, 
	[ChartNumber] 		= @ChartNumber, 
	[AA3]	 		= @AA3,
	[InstitutionNumber]	= @InstitutionNumber,
	[AA5]	 		= @AA5,
    [SignOff]  		= @SignOff,
    [SignDate] 		= @SignDate,
    [SignCoder] 		= @SignCoder,
    [ASignOff] 		= @ASignOff ,
    [ASignDate] 		= @ASignDate,
	[ASignCoder]		= @ASignCoder,
	[EncounterNumber]	= @EncounterNumber,
	[RegisterNumber]	= @RegisterNumber,
	[SecondChartRegNumber]	= @SecondChartRegNumber,
	[MISCode]		= @MISCode,
	[AttendingPhysician]	= @AttendingPhysician,
	[RefPhysician]		= @RefPhysician,
	[AdmittingNurseArea]	= @AdmittingNurseArea,
	[X4]				= @X4,
	[FixedChartNumber]	= @FixedChartNumber,
	[UniversalEpisodeIdentifier] = @UniversalEpisodeIdentifier,
    [HospitalAccountRecord] = @HospitalAccountRecord
WHERE 
	( [AbstractID]	 = @AbstractID)

if @Z1 = 200373
begin
    update [OMHRS_SecAA] 
    set          
        --[HospitalID]	   	= @HospitalID,
        [AdmitDate] 		= @AdmitDate,
        [AdmitTime]		    = @AdmitTime, 
        [LastName] 		    = @LastName , 
        [FirstName] 		= @FirstName, 
        [MiddleName] 		= @MiddleName, 
        [X10]	 		    = @X10,
        [HCNProvince] 		= @HCNProvince, 
        [HealthCareNumber] 	= @HealthCareNumber, 
        [AA3]	 		    = @AA3,
        [InstitutionNumber]	= @InstitutionNumber,
        [AA5]               = @AA5,
	    [X4]				= @X4,
		[UniversalEpisodeIdentifier] = @UniversalEpisodeIdentifier ,
        [HospitalAccountRecord] = @HospitalAccountRecord
    where [LinkID] 		    = @LinkID

    update [AB_Main] 
    set 
        [InstitutionNumber]     = @InstitutionNumber,
        [LastName] 		        = @LastName, 
        [FirstName] 		    = @FirstName, 
        [MiddleName] 		    = @MiddleName, 
        [AdmitDate] 		    = @AdmitDate,
        [AdmitTime]		        = @AdmitTime, 
        [HealthCareNumber] 	    = @HealthCareNumber,
		[UniversalEpisodeIdentifier] = @UniversalEpisodeIdentifier ,
        [HospitalAccountRecord] = @HospitalAccountRecord
    from OMHRS_SecAA AA inner join AB_Main M on AA.AbstractID = M.AbstractID 
    and M.AppID between 650 and 654
    where AA.LinkID             = @LinkID
end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE PROCEDURE [U_REC_Notes]
	(@LogID 	[int],
	 @AppID 	[int],
	 @FldID		[int],
	 @RecordID 	[int],
	 @LogNote 	[varchar](2500),
	 @LogDate 	[datetime],
	 @LogTime 	[datetime],
	 @LogCoder 	[int])

AS UPDATE [dbo].[REC_Notes] 

SET  	 [AppID]	 	 = @AppID,
	 [FieldID]	 = @FldID,
	 [RecordID]	 = @RecordID,
	 [LogNote]	 = @LogNote,
	 [LogDate]	 = @LogDate,
	 [LogTime]	 = @LogTime,
	 [LogCoder]	 = @LogCoder

WHERE 
	([LogID]	 	= @LogID)

RETURN @LogID



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [U_RH_ClientInfo]
	(@AbstractID 		[int],
	 @ICDType 		[char](1), 
	 @CareType 		[int],
	 @HospitalID		[int], 
	 @LinkID		[int],
	 @InstitutionNumber 	[int],
	 @AssessmentType 	[int],
	 @ProgramType 	[int],
	 @ChartNumber	 	[varchar](10),
	 @HealthCareNumber 	[varchar](12),
	 @HCNProvince		[int],
	 @AdmitDate	 	[datetime],
	 @DischargeDate 	[datetime],
	 @FollowUpDate 	[datetime],
	 @RespondentType 	[int],
	 @IsCompleted 		[int], 
	 @IsValidated 		[int], 
	 @IsSubmited 		[int], 
	 @IsCorrected 		[int], 
	 @IsDeleted 		[int], 
	 @CIHIDateSent 	[datetime], 
	 @BatchYear 		[int], 
	 @BatchPeriod 		[int], 
	 @AbstractNumber 	[int],
	 @EncounterNumber 	[varchar](20), 
	 @RegisterNumber 	[varchar](8),
	 @SiteNumber 		[int], 
	 @CoderNumber 	[int],
	 @LOSDays 		[int],
	 @HCNVersion 		[varchar](2),
	 @InterfaceDate 	[datetime], 
	 @InterfaceTime 	[datetime], 
	 @InterfaceCoder 	[int], 
	 @InputDate 		[datetime], 
	 @InputTime 		[datetime], 
	 @DataEntryCoder 	[int], 
	 @FinishDate 		[datetime], 
	 @FinishTime 		[datetime], 
	 @Secret 		[int], 
	 @TSIDate 		[datetime], 
	 @TSITime 		[datetime], 
	 @TSICoder 		[int],
	 @NextAssessDate	[datetime],
	 @SecondChartRegNumber [varchar](50), 
	 @MISCode 		[int], 
	 @AttendingPhysician 	[int], 
	 @RefPhysician 		[int], 
	 @AdmittingNurseArea 	[int],
	 @FixedChartNumber	[varchar](50),
	 @UniversalEpisodeIdentifier [varchar](50),
	 @HospitalAccountRecord varchar(50)
	)
AS 
If isnull(@IsDeleted, 0) = 0   set @IsDeleted = 2   -- PR - 03723
If isnull(@IsCorrected, 0) = 0 set @IsCorrected = 1 -- PR - 03723
If isnull(@IsSubmited, 0) = 0  set @IsSubmited = 2  -- PR - 03723

--PR - 04347
declare @ChartNumber_Old varchar(50)
declare @Institution_Old int
declare @HealthCareNumber_Old varchar(50)
declare @AdmitDate_Old datetime

if @IsDeleted = 2 and @IsSubmited = 1 and @IsCorrected = 2
begin
    select @ChartNumber_Old = ChartNumber, @Institution_Old = InstitutionNumber,
           @HealthCareNumber_Old = HealthCareNumber, @AdmitDate_Old = AdmitDate
    from [dbo].[RH_ClientInfo]
    where AbstractID = @AbstractID
    if isnull(@ChartNumber_OLD, '') <> isnull(@ChartNumber, '') or 
        isnull(@Institution_Old, 0) <> isnull(@InstitutionNumber, 0) or
        isnull(@HealthCareNumber_Old, '') <> isnull(@HealthCareNumber, '') or 
        isnull(@AdmitDate_Old, '1900/01/01') <> isnull(@AdmitDate , '1900/01/01')
    begin
        exec dbo.P_Rehab_KeyFieldUpdated @AbstractID 
        set @IsSubmited = 2 
        set @IsCorrected = 1
        update  [dbo].[RH_ClientInfo] 
        set IsSubmited = 2, IsCorrected = 1
        where LinkID = @LinkID and AbstractID <> @AbstractID
    end
end
--end PR - 04347

UPDATE [dbo].[RH_ClientInfo] 
SET  	 [HospitalID]		= @HospitalID,
	 [InstitutionNumber]	= @InstitutionNumber,
	 [SiteNumber]		= @SiteNumber, 
	 [CoderNumber]		= @CoderNumber,
	 [AssessmentType]	= @AssessmentType,
	 [ProgramType]	 	= @ProgramType,
	 [ChartNumber]	 	= @ChartNumber,
	 [HealthCareNumber]	= @HealthCareNumber,
	 [HCNVersion]		= @HCNVersion,
	 [HCNProvince]	 	= @HCNProvince,
	 [AdmitDate]	 	= @AdmitDate,
	 [DischargeDate]	= @DischargeDate, 
	 [FollowUpDate]	 	= @FollowUpDate, 
	 [LOSDays]		= @LOSDays,	
	 [RespondentType]	= @RespondentType,
	 [IsCorrected] 		= @IsCorrected, 
	 [IsSubmited]		= @IsSubmited, 
	 [IsValidated]		= @IsValidated, 
	 [IsCompleted]		= @IsCompleted,
	 [EncounterNumber]	= @EncounterNumber, 
	 [RegisterNumber]	= @RegisterNumber,
	 [InterfaceDate]		= @InterfaceDate,
	 [InterfaceTime]		= @InterfaceTime,
	 [InterfaceCoder]		= @InterfaceCoder,
	 [InputDate]		= @InputDate,
	 [InputTime]		= @InputTime,
	 [DataEntryCoder]	= @DataEntryCoder,
	 [FinishDate]		= @FinishDate,
	 [FinishTime]		= @FinishTime,
	 [Secret]		= @Secret,
	 [TSIDate]		= @TSIDate,
	 [TSITime]		= @TSITime,
	 [TSICoder]		= @TSICoder,
	 [NextAssessDate]	= @NextAssessDate,
	 [SecondChartRegNumber]	= @SecondChartRegNumber,
	 [MISCode]		= @MISCode,
	 [AttendingPhysician]	= @AttendingPhysician, 
	 [RefPhysician]		= @RefPhysician,
	 [AdmittingNurseArea]	= @AdmittingNurseArea,
	 [FixedChartNumber]		= @FixedChartNumber,
	 [UniversalEpisodeIdentifier] = @UniversalEpisodeIdentifier,
	 [HospitalAccountRecord] 	= @HospitalAccountRecord

WHERE 
	([AbstractID]		= @AbstractID)
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [U_RH_SyncRecords]
   (@AppID         [int],
    @LinkID                [int],
    @InstitutionNumber     [int],
    @SiteNumber            [int],
    @ProgramType   [int],
    @ChartNumber           [varchar](10),
    @EncounterNumber       [varchar](20), 
    @RegisterNumber        [varchar](8),   
    @HealthCareNumber      [varchar](12),
    @HCNVersion            [varchar](2),
    @HCNProvince           [int],
    @AdmitDate             [datetime],
    @DischargeDate         [datetime],
    @FollowUpDate  [datetime],
    @MaidenName            [varchar](35),
    @LastName              [varchar](40),
    @MiddleName            [varchar](15),
    @FirstName             [varchar](35),
    @Gender                [int],
    @BirthDate             [datetime],
    @BirthDateEstimated    [int],
    @LanguageCode  [int],
    @ResidenceCountry      [int],
    @PostalCode            [varchar](7),
    @Province              [int],
    @ResidenceCode         [int],
    @RP_ProvincePlan	[int],
    @RP_WCB_WSIB 	[int], 
    @RP_OtherProvince 	[int],
    @RP_Fed_DVA	[int], 
    @RP_Fed_FNIHB	[int], 
    @RP_Fed_Other	[int], 
    @RP_CanadaSelf	[int], 
    @RP_CanadaInsure	[int], 
    @RP_OtherSelf	[int], 
    @RP_ProvinceDefinition [int],
    @WalkMode [int],
    @ComprehensionMode [int],
    @ExpressionMode [int],
	@UniversalEpisodeIdentifier [varchar](50),
    @HospitalAccountRecord varchar(50)
	)

AS

DECLARE @DID AS INT
DECLARE @FID AS INT
declare @IID as int --0699
declare @PID as int --0699

SELECT @DID = AbstractID FROM [dbo].[RH_ClientInfo] WHERE [LinkID] = @LinkID AND [AssessmentType] = 135
SELECT @FID = AbstractID FROM [dbo].[RH_ClientInfo] WHERE [LinkID] = @LinkID AND [AssessmentType] = 136
SELECT @IID = AbstractID FROM [dbo].[RH_ClientInfo] WHERE [LinkID] = @LinkID AND [AssessmentType] = 156
SELECT @PID = AbstractID FROM [dbo].[RH_ClientInfo] WHERE [LinkID] = @LinkID AND [AssessmentType] = 157

IF @AppID = 250 --ADMISSION
   BEGIN
	   update [dbo].[RH_ClientInfo] 
	   set    [InstitutionNumber]    = @InstitutionNumber,
	            [SiteNumber]           = @SiteNumber,
	            [ProgramType]          = @ProgramType,
	            [ChartNumber]          = @ChartNumber,
	            [EncounterNumber]      = @EncounterNumber, 
	            [RegisterNumber]       = @RegisterNumber,
	            [HealthCareNumber]     = @HealthCareNumber,
	            [HCNVersion]           = @HCNVersion,
	            [HCNProvince]          = @HCNProvince,
	            [AdmitDate]            = @AdmitDate,
				[UniversalEpisodeIdentifier] = @UniversalEpisodeIdentifier,
                [HospitalAccountRecord] = @HospitalAccountRecord
	   where [AbstractID] = @DID OR [AbstractID] = @FID or AbstractID = @IID or AbstractID = @PID

	   update [dbo].[RH_Demographic] 
	   set    [MaidenName]           = @MaidenName,
	            [LastName]             = @LastName, 
	            [MiddleName]           = @MiddleName,
	            [FirstName]            = @FirstName,           
	            [Gender]               = @Gender,
	            [BirthDate]            = @BirthDate,
	            [BirthDateEstimated]   = @BirthDateEstimated,
	            [LanguageCode] = @LanguageCode,
	            [ResidenceCountry]     = @ResidenceCountry,
	            [PostalCode]           = @PostalCode,
	            [Province]             = @Province,
	            [ResidenceCode]        = @ResidenceCode
	where [AbstractID] = @DID OR [AbstractID] = @FID or AbstractID = @IID or AbstractID = @PID

	update [dbo].[RH_Administrative]
	set 	[RP_ProvincePlan]	= @RP_ProvincePlan, 
		[RP_WCB_WSIB]	= @RP_WCB_WSIB, 
		[RP_OtherProvince]	= @RP_OtherProvince, 
		[RP_Fed_DVA]		= @RP_Fed_DVA, 
		[RP_Fed_FNIHB]	= @RP_Fed_FNIHB, 
		[RP_Fed_Other]		= @RP_Fed_Other, 
		[RP_CanadaSelf]	= @RP_CanadaSelf, 
		[RP_CanadaInsure]	= @RP_CanadaInsure, 
		[RP_OtherSelf]		= @RP_OtherSelf, 
		[RP_ProvinceDefinition]	= @RP_ProvinceDefinition
	where [AbstractID] = @DID OR [AbstractID] = @FID or AbstractID = @IID or AbstractID = @PID
    -- PR - 03938
    update dbo.RH_Activity
    set ComprehensionMode = @ComprehensionMode,
        ExpressionMode = @ExpressionMode
        --WalkMode = @WalkMode, --PR - 04270 Remove WalkMode default to admission assessment.
	where [AbstractID] = @DID OR [AbstractID] = @FID or AbstractID = @IID or AbstractID = @PID

   END 

ELSE IF @AppID = 251 --DISCHARGE
begin
    UPDATE [dbo].[RH_ClientInfo] SET [DischargeDate] = @DischargeDate WHERE [AbstractID] = @FID  
end
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [U_ROI_Main]
   (@HospitalID	[int],
    @ROIID         [int],
    @RequestNumber         [varchar](15),
    @ChartNumber           [varchar](10),
    @RequestDate   [datetime],
    @RequestReceivedTime   [datetime],
    @RequestCoder  [int],
    @RequesterID           [int],
    @RequesterType         [int],
    @RequestMethod         [int],
    @RequestReceived       [datetime],
    @RequestType   [int],
    @RequestChargeable     [int],
    @RequestDuration       [int],
    @ContactID             [int],
    @ContactEMail  [varchar](50),
    @ContactPhone  [varchar](15),
    @ContactExtention      [varchar](20),
    @ContactFax            [varchar](15),
    @AuthRequired  [int],
    @AuthReceived  [int],
    @AuthSignedID  [int],
    @ROIStatus             [int],
    @SentDate              [datetime],
    @SentTime              [datetime],
    @SentCoder             [int],
    @SentBy                [int],
    @TrackingNumber        [varchar](75),
    @SpecialHandling       [varchar](1000),
    @InvoiceNumber         [varchar](30),
    @InvoiceDate           [datetime],
    @InvoiceTime           [datetime],
    @InvoiceTotal          [money],
    @AccountNumber         [varchar](30),
    @GSTNumber             [varchar](30),
    @AmountPaid            [money],
    @AmountOwed    [money],
    @DueDate               [datetime],
    @AuthType              [int],
    @CostLevel             [int],
    @Comment               [varchar](255),
    @LastName              [varchar](40), 
    @FirstName             [varchar](35),
    @RequestUrgency 	[int],
    @SiteNumber 	[int],
    @ROITaxRate1 	[int], 
    @ROITaxRate2 	[int],
    @Confidential	[int],
    @ExtensionNoticeRequired int,
    @ExtensionDays int,
    @AgeCode int,
    @AgeNumber int,
    @Birthdate datetime  )

AS UPDATE [ROI_Main] 
SET         
[HospitalID] 	=@HospitalID,
[RequestNumber]         = @RequestNumber,
[SiteNumber]		= @SiteNumber,
[ChartNumber]           = @ChartNumber,
[LastName]              = @LastName,
[FirstName]             = @FirstName,
[RequestDate]           = @RequestDate,
[RequestReceivedTime]   = @RequestReceivedTime,
[RequestCoder]          = @RequestCoder,
[RequesterID]           = @RequesterID,
[RequesterType]         = @RequesterType,
[RequestMethod]         = @RequestMethod,
[RequestReceived]       = @RequestReceived,
[RequestType]           = @RequestType,
[RequestChargeable]     = @RequestChargeable,
[CostLevel]             = @CostLevel,
[RequestDuration]       = @RequestDuration,
[ContactID]             = @ContactID,
[ContactEMail]          = @ContactEMail,
[ContactPhone]          = @ContactPhone,
[ContactExtention]      = @ContactExtention,
[ContactFax]            = @ContactFax,
[AuthorizationRequired]         = @AuthRequired,
[AuthorizationReceived]         = @AuthReceived,
[AuthorizationType]     = @AuthType,
[AuthorizationSignedID]         = @AuthSignedID,
[ROIStatus]             = @ROIStatus,
[SentDate]              = @SentDate,
[SentTime]              = @SentTime,
[SentCoder]             = @SentCoder,
[SentBy]                = @SentBy,
[TrackingNumber]        = @TrackingNumber,
[SpecialHandling]       = @SpecialHandling,
[InvoiceNumber]         = @InvoiceNumber,
[InvoiceDate]           = @InvoiceDate,
[InvoiceTime]           = @InvoiceTime,
[InvoiceTotal]          = @InvoiceTotal,
[AccountNumber]         = @AccountNumber,
[GSTNumber]             = @GSTNumber,
[AmountPaid]            = @AmountPaid,
[AmountOwed]            = @AmountOwed,
[DueDate]               = @DueDate,
[RequestComments]       = @Comment,
[RequestUrgency]	= @RequestUrgency,
[ROITaxRate1]		= @ROITaxRate1,
[ROITaxRate2]		= @ROITaxRate2 ,
[Confidential]		= @Confidential,
[ExtensionNoticeRequired] = @ExtensionNoticeRequired,
[ExtensionDays]     = @ExtensionDays,
[AgeCode]           = @AgeCode,
[AgeNumber]         = @AgeNumber,
[Birthdate]         = @Birthdate
WHERE 
   ([ROIID]                        = @ROIID)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO




CREATE PROCEDURE [U_SH_Appointments]
	(@AppointmentID 	[int],
	 @PatientID	 	[int],
	 @ProviderNumber	[int],
	 @AppointmentDate 	[datetime],
	 @AppointmentTime 	[datetime],
	 @Duration	 	[int],
	 @AppointmentReason	[int],
	 @VisitType	 	[int],
	 @Location	 	[int],
	 @Room	 	[int],
	 @Status		[int],
	 @ArrivalTime		[datetime],
	 @CancelReason	[int])
AS 
	
UPDATE [dbo].[SH_Appointments] 
SET  	 [AppointmentID]	 	= @AppointmentID,
	 [PatientID]	 	= @PatientID,
	 [ProviderNumber]	= @ProviderNumber,
	 [AppointmentDate]	= @AppointmentDate,
	 [AppointmentTime]	= @AppointmentTime,
	 [Duration]	 	= @Duration,
	 [AppointmentReason]	= @AppointmentReason,
	 [VisitType]	 	= @VisitType,
	 [Location]	 	= @Location,
	 [Room]	 		= @Room,
	 [Status]			= @Status,
	 [ArrivalTime]		= @ArrivalTime,
	 [CancelReason]		= @CancelReason	
WHERE 
	([AppointmentID]	 	= @AppointmentID AND ISNULL([Status], 0) <> 11735)

IF @Status = 11735 
	BEGIN
		DECLARE @RetVal	[int]
		DECLARE @ChrtNum	[varchar](10)
	 	DECLARE @HCN	[varchar](12)
	 	DECLARE @HCNVer	[varchar](2)
	 	DECLARE @MaName	[varchar](35)
	 	DECLARE @LName	[varchar](35)
	 	DECLARE @MiName 	[varchar](15)
	 	DECLARE @FName	[varchar](35)
	 	DECLARE @Gender 	[int]
	 	DECLARE @DOB	[datetime]
		DECLARE @EncNum 	[varchar](20)
	
		SELECT @ChrtNum = ChartNumber, @HCN = HealthCareNumber, @HCNVer = HCNVersion, @MaName = MaidenName, @LName = LastName, @MiName = MiddleName, @FName = FirstName, @Gender = Gender, @DOB = BirthDate FROM CM_CPI WHERE PatientID = @PatientID

		EXEC P_UpdateClinicEncNum @EncNum OUTPUT	
		EXEC @RetVal = I_CR_Demographic 0,  @ChrtNum, @HCN, @HCNVer, @MaName, @LName, @MiName, @FName, @Gender, @DOB, 1, 1, 1, 1, 2, NULL, '', 0
		EXEC I_CR_Visit @RetVal, 0, @ProviderNumber, @EncNum, '001', @AppointmentDate, @AppointmentTime, @ArrivalTime, NULL, NULL, 0, @VisitType, 0, 0, NULL, NULL, NULL, NULL, 0, 0, 0, NULL, 0, 0, NULL, NULL, NULL		
	END

RETURN @AppointmentID



GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO




CREATE      PROCEDURE [U_Transcription]
	(@HospitalID		[int],
	 @TranscriptionID 	[int],
	 @AbstractID 	[int],
	 @PatientID 	[int],
	 @DictatingPhysician 	[int],
	 @DictationDate 	[datetime],
	 @DictationTime 	[datetime],
	 @DocumentType 	[int],
	 @DocumentName 	[varchar](100),
	 @TranscriptionDate 	[datetime],
	 @TranscriptionTime 	[datetime],
	 @Transcriptionist 	[int],
	 @StartWordCount 	[int],
	 @LastWordCount 	[int],
	 @TranscriptionLength 	[int],
	 @SignDate		[datetime],
	 @SignTime		[datetime],
	 @SignPhysician	[int],
	 @CareType		[int],
	 @UpdateCPI	VarChar(1) Output)

AS

	If isnull((select DocumentName from TR_Main where TranscriptionID = @TranscriptionID), '') = ''
		Update [TR_Main]  Set 
			HospitalID 		= @HospitalID,
			AbstractID 		= @AbstractID, 
			PatientID 		= @PatientID, 
			CareType 		= @CareType,
			DictatingPhysician 	= @DictatingPhysician,
			DictationDate 		= @DictationDate, 
			DictationTime 		= @DictationTime, 
			SignPhysician 		= @SignPhysician,
			SignDate 		= @SignDate, 
			SignTime 		= @SignTime, 
			DocumentType 		= @DocumentType,
			DocumentName 	= @DocumentName, 
			TranscriptionDate 	= @TranscriptionDate, 
			TranscriptionTime 	= @TranscriptionTime,
			Transcriptionist 		= @Transcriptionist, 
			StartWordCount 		= @StartWordCount, 
			[LastWordCount] 	= @LastWordCount, 
			[TranscriptionLength] 	= @TranscriptionLength
		Where TranscriptionID 		= @TranscriptionID
	Else
		Update [TR_Main] Set 
			SignPhysician 		= @SignPhysician,
			SignDate 		= @SignDate, 
			SignTime 		= @SignTime, 
			[LastWordCount] = @LastWordCount, 
			[TranscriptionLength] = @TranscriptionLength
		Where TranscriptionID = @TranscriptionID
 
	Set @UpdateCPI = 'N'

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO






-- This is called by the Save Method of the 
CREATE   PROCEDURE [U_U_UserFields]
	(@AppID 	[int],
	 @UserID 	[int],
	 @FieldID 	[int],
	 @MandatoryStatus 	[int],
	 @Header_User 	[varchar](50),
	 @FieldEnabled 	[int],
	 @FieldVisible 	[int],
	 @DefaultValue 	[varchar](50))
AS 

	UPDATE [U_UsersFields] 
	SET [MandatoryStatus]	 = @MandatoryStatus,
		 [Header_User]	 = @Header_User,
		 [FieldEnabled]	 = @FieldEnabled,
		 [FieldVisible]	 = @FieldVisible,
		 [DefaultValue]	 = @DefaultValue 
	WHERE 
		( [AppID]	 = @AppID AND
		 [UserID]	 = @UserID AND
		 [FieldID]	 = @FieldID)




GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO





CREATE  PROCEDURE [U_U_UserFieldsClone] 
	@UserID as int,
	@BasedOn as int = 1,
	@AppID as int
AS 

	IF EXISTS (SELECT UserID FROM dbo.U_UsersFields WHERE UserID = @UserID and AppID = @AppID)
	DELETE dbo.U_UsersFields WHERE UserID = @UserID and AppID = @AppID
	
	INSERT INTO dbo.U_UsersFields 
		(AppID,
		RoleID, 
		UserID, 
		FieldID, 
		SortOrder, 
		GroupID, 
		MultipleIndex, 
		MandatoryStatus, 
		Needed, 
		FieldSize, 
		DataType, 
		SubAppID, 
		LookUpTable, 
		CIHI_ID,
		Header_CIHI_English, 
		Header_CIHI_French, 
		Header_CIHI_Spanish, 
		Header_User, 
		FieldEnabled, 
		FieldVisible, 
		DefaultValue, 
		ParamProcID,
		ParamOrder,
		ParamName,
		ParamDataType,
		ParamSize,
		NeedForUserDef,
		UNoteCode)	
	SELECT
		AppID,
		RoleID, 
		@UserID, 
		FieldID, 
		SortOrder, 
		GroupID, 
		MultipleIndex, 
		MandatoryStatus, 
		Needed, 
		FieldSize, 
		DataType, 
		SubAppID, 
		LookUpTable, 
		CIHI_ID,
		Header_CIHI_English, 
		Header_CIHI_French, 
		Header_CIHI_Spanish, 
		Header_User, 
		FieldEnabled, 
		FieldVisible, 
		DefaultValue, 
		ParamProcID,
		ParamOrder,
		ParamName,
		ParamDataType,
		ParamSize,
		NeedForUserDef,
		UNoteCode
	FROM         dbo.U_UsersFields
	WHERE (UserID = @BasedOn AND AppID = @AppID)
	RETURN 0



GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is called by the Save Method of the User Profile Control.
CREATE    PROCEDURE [U_U_Users]
	(@BasedOn		[int],
	 @Code			[int],
	 @DisplayCode 		[varchar](12),
	 @UserDescription	[varchar](50),
	 @DefaultDescription	[varchar](50),
	 @CIHIValue		[varchar](12),
	 @ValidFrom		[varchar](10),
	 @ValidTo		[varchar](10),
	 @InterfaceIn		[varchar](12),
	 @UserName 		[varchar](50),
	 @UserPassword 		[varchar](50),
	 @PasswordChanged	[datetime],
	 @ChangePassword	[int],
	 @LastName		[varchar](50),
	 @MiddleName 		[varchar](50),
	 @FirstName 		[varchar](50),
	 @IsAdmin		[int],
	 @CanSubmitI 		[int],
	 @CanSubmitS 		[int],
	 @CanSubmitA 		[int],
	 @LanguageID 		[int],
	 @DisplayMessages 	[int],
	 @PermitCPI		[int],
	 @PermitChartLoc 	[int],
	 @PermitChartDef 	[int],
	 @PermitTranscription 	[int],
	 @PermitROI		[int],
	 @PermitCCR	 	[int],
	 @PermitInPat	 	[int],
	 @PermitSDS	 	[int],
	 @PermitAmcare 		[int],
	 @PermitBatchGrouper 	[int],
	 @PermitCareMap 	[int],
	 @PermitReportGen 	[int],
	 @PermitCIHISubmit 	[int],
	 @PermitCIHICorrect 	[int],
	 @PermitBatchInterface 	[int],
	 @PermitHL7Interface 	[int],
	 @PermitUndelete 	[int],
	 @PermitHospProf 	[int],
	 @PermitInstProf 	[int],
	 @PermitUserProf 	[int],
	 @PermitLookUpMaint 	[int],
	 @PermitControlFile 	[int],
	 @RoleID		[int],
	 @PermitCCR10	 	[int],
	 @PermitInPat10 	[int],
	 @PermitSDS10	 	[int],
	 @PermitAmcare10 	[int],
	 @CanSubmitI10		[int],
	 @CanSubmitS10		[int],
	 @CanSubmitA10		[int],
	 @PermitRehab10 	[int],
	 @CanSubmitR10 		[int],
	 @PermitClinic 		[int], 
	 @PermitBilling 	[int], 
	 @PermitScheduler 	[int], 
	 @CanSubmitCL 		[int],
	 @TransInitials		[varchar](10),
	 @AutoShowLookUp 	[int],
	 @AutoShowClone 	[int],
	 @CanSubmitC10 		[int],
	 @PermitCCRS10 		[int],
	 @EnableQuickSearch 	[int],
	 @SearchChartPrefix 	[varchar](3),
	 @ShowVIP		[int],
	 @CanModifyCharts 	[int],
	 @FlyCalcGrouper	[int],
	 @UserDateFormat 	[int],
	 @ChangePasswordDate 	[datetime],
	 @FontSize 		[int],
	 @DisplayMultUser 	[int],
	 @HospitalID		[int],
	 @CanReSetA 		[int], 
	 @CanReSetR 		[int], 
	 @CanReSetC 		[int],
	 @PermitVisitHist 	[int], 
	 @PermitDAS 		[int],
	 @FlyCalcCACS 		[int], 
	 @FlyCalcDPG 		[int], 
	 @FlyCalcFIM 		[int], 
	 @FlyCalcRUG 		[int],
	 @DefaultHospID 	[int],
	 @CanSubmitM10		[int],
	 @PermitOMHRS10 	[int],
     @LUText 		[varchar](255), 
	 @CanReSetM 		[int],
	 @NTAuthority 		[varchar](100) ,
	 @PermitProvdrMaint 	[int],
	 @PermitRegionProf	[int],
	 @DisplayChrtLinks 	[int],
	 @AccessLockChart 	[int], 
	 @PromptLoc 		[int], 
	 @PromptDef 		[int], 
	 @AmCareFacFile  	[int], 
	 @CCRSFacFile 		[int], 
	 @RehabFacFile 		[int], 
	 @OMHRSFacFile 		[int], 
	 @DADSepFile 		[int], 
	 @CCRSAuditFile 	[int], 
	 @ImportDADErrors 	[int], 
	 @ExecTermChrt 		[int], 
	 @ShowAllRegion 	[int], 
	 @PermitViewChartAct 	[int], 
	 @PermitViewChartDef 	[int], 
	 @PermitChartVolume 	[int], 
	 @PermitWRUUpdates 	[int],
	 @PermitMDASLayer 	[int], 
	 @PermitMDASPrivacy 	[int],
	 @MDASRecordLock 	[int],
	 @MDASSensitvity	[int],
	 @CanPurgeVolQue 	[int],
	 @PermitAdapCS		[int],
	 @PermitCCM 		[int],
	 @CanSubmitCCM 		[int],
     @ImportOMHRSErrors 	[int],
	 @CanViewWho		[int],
	 @FlyCalcSCIPP 		[int],
	 @CanLaunchSolCom 	[int],
	 @CanPurgeLog		[int],
	 @CanDADInstFile    [int],
	 @CanClearCPILock   [int],
	 @PermitCodeSmart	[int],
	 @SetLevelOneCorrection [int],
	 @ShowConfidentialRequest [int],
	 @ModifyRegionalID [int],
	 @CanSubmitCJRR		[int],
	 @PermitCJRR		[int],
	 @CanReSetCJRR		[int],
	 @FolioCAFile       [varchar](250),
	 @FolioCCIFile      [varchar](250),
	 @SkipLoginScreen   [int],
	 @codeSmartFile     [varchar](250),
	 @PermitEditEngine  [int],
	 @EditEngineFile     [varchar](250),
	 @SelectQueue		[int]
)
AS 

--2.x-1491 
declare @i as int   
set @UserPassword = rtrim(@UserPassword)    
set @i = len(@UserPassword)
set @UserPassword = replace(isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 1, 1)) - 10), '') +
isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 2, 1)) - 11), '') +
isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 3, 1)) - 12), '') +
isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 4, 1)) - 13), '') +
isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 5, 1)) - 14), '') +
isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 6, 1)) - 15), '') +
isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 7, 1)) - 16), '') +
isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 8, 1)) - 17), '') +
isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 9, 1)) - 18), '') +
isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 10, 1)) - 19), '') +
isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 11, 1)) - 20), '') +
isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 12, 1)) - 21), '') +
isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 13, 1)) - 22), '') +
isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 14, 1)) - 23), '') +
isnull(char(ASCII(SUBSTRING(reverse(@UserPassword), 15, 1)) - 24), ''), '               ', '')
if @i > 0 set @UserPassword = left(@UserPassword, @i)   --2.x-1491 

exec I_U_Users_password @Code, @UserPassword	--2.x-0205

update [U_Users] set  	
	[UserName]	 	= @UserName,
	[DisplayCode]		= @DisplayCode,
	[UserDescription]	= @UserDescription,
	[DefaultDescription]	= @DefaultDescription,
	[ValidFrom]		= @ValidFrom,
	[ValidTo]		= @ValidTo,
	[InterfaceIn]		= @InterfaceIn,
	[HospitalID]		= @HospitalID,
	[DefaultHospID]		= @DefaultHospID,
	[UserPassword]	 	= @UserPassword,
	[PasswordChanged]	= @PasswordChanged,
	[ChangePasswordDays] 	= @ChangePassword,
	[ChangePasswordDate] 	= @ChangePasswordDate,
	[ShowVIP]		= @ShowVIP,
	[CanModifyCharts]	= @CanModifyCharts, 
	[LastName]	 	= @LastName,
	[MiddleName]	 	= @MiddleName,
	[FirstName]	 	= @FirstName,
	[TransInitials]		= @TransInitials,
	[IsAdmin]		= @IsAdmin,
	[CanSubmitI]	 	= @CanSubmitI,
	[CanSubmitS]	 	= @CanSubmitS,
	[CanSubmitA]	 	= @CanSubmitA,
	[CanSubmitI10]	 	= @CanSubmitI10,
	[CanSubmitS10]	 	= @CanSubmitS10,
	[CanSubmitA10]	 	= @CanSubmitA10,
	[CanSubmitC10]		= @CanSubmitC10,
	[CanSubmitR10] 		= @CanSubmitR10,
	[CanSubmitM10]		= @CanSubmitM10,
	[CanSubmitCL]		= @CanSubmitCL,
	[LanguageID]	 	= @LanguageID,
	[DisplayMessages]	= @DisplayMessages,
	[AutoShowLookUp]	= @AutoShowLookUp,
	[AutoShowClone]		= @AutoShowClone,	
	[PermitCPI]	 	= @PermitCPI,	
	[PermitChartLoc]	= @PermitChartLoc,
	[PermitChartDef]	= @PermitChartDef,
	[PermitTranscription]	= @PermitTranscription,
	[PermitROI]	 	= @PermitROI,
	[PermitCCR]	 	= @PermitCCR,
	[PermitInPat]	 	= @PermitInPat,
	[PermitSDS]	 	= @PermitSDS,
	[PermitAmcare]	 	= @PermitAmcare,
	[PermitCCR10]	 	= @PermitCCR10,
	[PermitInPat10]	 	= @PermitInPat10,
	[PermitSDS10]	 	= @PermitSDS10,
	[PermitAmcare10]	= @PermitAmcare10,
	[PermitCCRS10]		= @PermitCCRS10, 
	[PermitRehab10]		= @PermitRehab10,
	[PermitOMHRS10]		= @PermitOMHRS10,
	[PermitClinic]		= @PermitClinic, 
	[PermitBatchGrouper]	= @PermitBatchGrouper,
	[PermitCareMap]	 	= @PermitCareMap,
	[PermitScheduler]	= @PermitScheduler, 
	[PermitReportGen]	= @PermitReportGen,
	[PermitCIHISubmit]	= @PermitCIHISubmit,
	[PermitCIHICorrect]	= @PermitCIHICorrect,
	[PermitBilling]		= @PermitBilling, 
	[PermitBatchInterface]	= @PermitBatchInterface,
	[PermitHL7Interface]	= @PermitHL7Interface,
	[PermitUndelete]	= @PermitUndelete,
	[PermitHospProf]	= @PermitHospProf,
	[PermitInstProf]	= @PermitInstProf,
	[PermitUserProf]	= @PermitUserProf,
	[PermitLookUpMaint]	= @PermitLookUpMaint,
	[PermitControlFile]	= @PermitControlFile,
	[RoleID]		= @RoleID,
	[PasswordAttempt]	= 0,
	[EnableQuickSearch]	= @EnableQuickSearch,
	[SearchChartPrefix]	= @SearchChartPrefix,
	[FlyCalcGrouper]	= @FlyCalcGrouper,
	[UserDateFormat]	= @UserDateFormat,
	[FontSize]		= @FontSize,
	[DisplayMultUser]	= @DisplayMultUser ,
	[CanReSetA]		= @CanReSetA,
	[CanReSetR]		= @CanReSetR,
	[CanReSetC]		= @CanReSetC,
	[PermitVisitHist]	= @PermitVisitHist,
	[PermitDAS]		= @PermitDAS,
	[FlyCalcCACS]		= @FlyCalcCACS, 
	[FlyCalcDPG]		= @FlyCalcDPG, 
	[FlyCalcFIM]		= @FlyCalcFIM, 
	[FlyCalcRUG]		= @FlyCalcRUG,
 	[LUText]  		= @LUText,
 	[CanReSetM] 		= @CanReSetM,
 	[NTAuthority] 		= @NTAuthority,
 	[PermitProvdrMaint] 	= @PermitProvdrMaint,
 	[PermitRegionProf]	= @PermitRegionProf,
	[DisplayChrtLinks] 	= @DisplayChrtLinks,
	[AccessLockChart] 	= @AccessLockChart,
	[PromptLoc] 		= @PromptLoc,
	[PromptDef] 		= @PromptDef,
	[AmCareFacFile]  	= @AmCareFacFile,
	[CCRSFacFile] 		= @CCRSFacFile,
	[RehabFacFile] 		= @RehabFacFile,
	[OMHRSFacFile] 		= @OMHRSFacFile,
	[DADSepFile] 		= @DADSepFile,
	[CCRSAuditFile] 	= @CCRSAuditFile,
	[ImportDADErrors] 	= @ImportDADErrors,
	[ExecTermChrt] 		= @ExecTermChrt,
	[ShowAllRegion] 	= @ShowAllRegion,
	[PermitViewChartAct] 	= @PermitViewChartAct,
	[PermitViewChartDef] 	= @PermitViewChartDef,
	[PermitChartVolume] 	= @PermitChartVolume,
	[PermitWRUUpdates] 	= @PermitWRUUpdates,
	[PermitMDASLayer] 	= @PermitMDASLayer,
	[PermitMDASPrivacy] 	= @PermitMDASPrivacy,
	[MDASRecordLock] 	= @MDASRecordLock,
	[MDASSensitvity]	= @MDASSensitvity,
	[CanPurgeVolQue] 	= @CanPurgeVolQue,
	[PermitAdapCS]		= @PermitAdapCS,
	[PermitCCM]		= @PermitCCM,
	[CanSubmitCCM]		= @CanSubmitCCM,
    [ImportOMHRSErrors] 	= @ImportOMHRSErrors,
	[CanViewWho]		= @CanViewWho,
	[FlyCalcSCIPP]		= @FlyCalcSCIPP,
	[CanLaunchSolCom]	= @CanLaunchSolCom,
	[CanPurgeLog]		= @CanPurgeLog,
    [DADInstFile]       = @CanDADInstFile,
    [CanClearCPILock]   = @CanClearCPILock,
    [PermitCodeSmart]	= @PermitCodeSmart,
    [SetLevelOneCorrection] = @SetLevelOneCorrection,
    [ShowConfidentialRequest] = @ShowConfidentialRequest,
    [ModifyRegionalID] = @ModifyRegionalID,
    [CanSubmitCJRR]		= @CanSubmitCJRR,
	[PermitCJRR]		= @PermitCJRR,
	[CanReSetCJRR]		= @CanReSetCJRR,
	[FolioCAFile]       = @FolioCAFile,
	[FolioCCIFile]      = @FolioCCIFile,
	[SkipLoginScreen]   = @SkipLoginScreen,
	[codeSmartFile]     = @codeSmartFile,
	[PermitEditEngine]	= @PermitEditEngine,
	[EditEngineFile]	= @EditEngineFile,
	[SelectQueue]		= @SelectQueue
where [Code] = @Code

--Add or Change Role (@BasedOn stores the RoleID that was loaded)
if @RoleID <> 0 AND (@BasedOn = 0 OR (@RoleID <> @BasedOn)) and @Code > 0 --PR - 05811 add @Code > 0
begin
	-- Change the Role ID for any potential Users that are linked to this record.
	update U_Users set RoleID = @RoleID where RoleID = @Code 
	delete U_UsersFields where UserID = @Code and UserID <> 1   --PR - 05374 Add UserID <> 1  
	exec U_UsersRoles @RoleID
end

--Remove Role
if @RoleID = 0 and @BasedOn <> 0 and @Code > 0 --PR - 05811 add @Code > 0
begin
	exec I_U_UserFields @Code, @BasedOn
end

--Wasn't based on a Role, but might be a Master of others
if @RoleID = 0 and @BasedOn = 0 and @Code > 0 --PR - 05811 add @Code > 0
begin
	update [U_Users] set
		[IsAdmin]		= @IsAdmin,
		[CanSubmitI]	 	= @CanSubmitI,
		[CanSubmitS]	 	= @CanSubmitS,
		[CanSubmitA]	 	= @CanSubmitA,
		[CanSubmitI10]	 	= @CanSubmitI10,
		[CanSubmitS10]	 	= @CanSubmitS10,
		[CanSubmitA10]	 	= @CanSubmitA10,
		[CanSubmitC10]		= @CanSubmitC10,
		[CanSubmitR10] 		= @CanSubmitR10,
		[CanSubmitM10]		= @CanSubmitM10,
		[CanSubmitCL]		= @CanSubmitCL,
		[CanReSetA]		= @CanReSetA,
		[CanReSetR]		= @CanReSetR,
		[CanReSetC]		= @CanReSetC,
		[LanguageID]	 	= @LanguageID,
		[UserDateFormat]	= @UserDateFormat,
		[DisplayMessages]	= @DisplayMessages,
		[DisplayMultUser]	= @DisplayMultUser,
		[AutoShowLookUp]	= @AutoShowLookUp,
		[AutoShowClone]		= @AutoShowClone,
		[FlyCalcGrouper]	= @FlyCalcGrouper,
		[EnableQuickSearch]	= @EnableQuickSearch,
		[SearchChartPrefix]	= @SearchChartPrefix,
		[ShowVIP]		= @ShowVIP,
		[CanModifyCharts]	= @CanModifyCharts,
		[PermitCPI]	 	= @PermitCPI,
		[PermitChartLoc]	= @PermitChartLoc,
		[PermitChartDef]	= @PermitChartDef,
		[PermitTranscription]	= @PermitTranscription,
		[PermitROI]	 	= @PermitROI,
		[PermitCCR]	 	= @PermitCCR,
		[PermitInPat]	 	= @PermitInPat,
		[PermitSDS]	 	= @PermitSDS,
		[PermitAmcare]	 	= @PermitAmcare,
		[PermitCCR10]	 	= @PermitCCR10,
		[PermitInPat10]	 	= @PermitInPat10,
		[PermitSDS10]	 	= @PermitSDS10,
		[PermitAmcare10] 	= @PermitAmcare10,
		[PermitCCRS10]		= @PermitCCRS10, 
		[PermitRehab10]		= @PermitRehab10,
		[PermitOMHRS10]		= @PermitOMHRS10,
		[PermitClinic]		= @PermitClinic,
		[PermitBatchGrouper]	= @PermitBatchGrouper,
		[PermitCareMap]	 	= @PermitCareMap,
		[PermitScheduler]	= @PermitScheduler,
		[PermitReportGen]	= @PermitReportGen,
		[PermitCIHISubmit]	= @PermitCIHISubmit,
		[PermitCIHICorrect]	= @PermitCIHICorrect,
		[PermitBilling]		= @PermitBilling,
		[PermitBatchInterface]	= @PermitBatchInterface,
		[PermitHL7Interface]	= @PermitHL7Interface,
		[PermitUndelete]	= @PermitUndelete,
		[PermitHospProf]	= @PermitHospProf,
		[PermitInstProf]	= @PermitInstProf,
		[PermitUserProf]	= @PermitUserProf,
		[PermitLookUpMaint]	= @PermitLookUpMaint,
		[PermitControlFile]	= @PermitControlFile,
		[PermitVisitHist]	= @PermitVisitHist,
		[PermitDAS]		= @PermitDAS,
		[FlyCalcCACS] 		= @FlyCalcCACS, 
		[FlyCalcDPG] 		= @FlyCalcDPG, 
		[FlyCalcFIM] 		= @FlyCalcFIM, 
		[FlyCalcRUG] 		= @FlyCalcRUG,	
		[DefaultHospID]  	= @DefaultHospID,
	 	[CanReSetM] 		= @CanReSetM,
	 	[PermitProvdrMaint] 	= @PermitProvdrMaint,
	 	[PermitRegionProf]	= @PermitRegionProf,
		[DisplayChrtLinks] 	= @DisplayChrtLinks,
		[AccessLockChart] 	= @AccessLockChart,
		[PromptLoc] 		= @PromptLoc,
		[PromptDef] 		= @PromptDef,
		[AmCareFacFile]  	= @AmCareFacFile,
		[CCRSFacFile] 		= @CCRSFacFile,
		[RehabFacFile] 		= @RehabFacFile,
		[OMHRSFacFile] 		= @OMHRSFacFile,
		[DADSepFile] 		= @DADSepFile,
		[CCRSAuditFile] 	= @CCRSAuditFile,
		[ImportDADErrors] 	= @ImportDADErrors,
		[ExecTermChrt] 		= @ExecTermChrt,
		[ShowAllRegion] 	= @ShowAllRegion,
		[PermitViewChartAct] 	= @PermitViewChartAct,
		[PermitViewChartDef] 	= @PermitViewChartDef,
		[PermitChartVolume] 	= @PermitChartVolume,
		[PermitWRUUpdates] 	= @PermitWRUUpdates,
		[PermitMDASLayer] 	= @PermitMDASLayer,
		[PermitMDASPrivacy] 	= @PermitMDASPrivacy,
		[MDASRecordLock] 	= @MDASRecordLock,
		[MDASSensitvity]	= @MDASSensitvity,
		[CanPurgeVolQue] 	= @CanPurgeVolQue,
		[PermitAdapCS]		= @PermitAdapCS,	
		[PermitCCM]		= @PermitCCM,
		[CanSubmitCCM]		= @CanSubmitCCM,
		[CanViewWho]		= @CanViewWho,
		[FlyCalcSCIPP]		= @FlyCalcSCIPP,
		[CanLaunchSolCom]	= @CanLaunchSolCom,
		[CanPurgeLog]		= @CanPurgeLog,
		[DADInstFile]       = @CanDADInstFile,
		[CanClearCPILock]   = @CanClearCPILock,
		[PermitCodeSmart]   = @PermitCodeSmart,
		[SetLevelOneCorrection] = @SetLevelOneCorrection,
		[ShowConfidentialRequest] = @ShowConfidentialRequest,
		[ModifyRegionalID] = @ModifyRegionalID,
		[CanSubmitCJRR]		= @CanSubmitCJRR,
		[PermitCJRR]		= @PermitCJRR,
		[CanReSetCJRR]		= @CanReSetCJRR,
		[FolioCAFile]       = @FolioCAFile,
		[FolioCCIFile]      = @FolioCCIFile,
		[SkipLoginScreen]   = @SkipLoginScreen,
		[codeSmartFile]     = @codeSmartFile,
		[PermitEditEngine]	= @PermitEditEngine,
		[EditEngineFile]	= @EditEngineFile,
		[SelectQueue]		= @SelectQueue
	
-- 		UPDATE [U_Users] 
-- 		SET  	[IsAdmin]		= @IsAdmin,
-- 			[CanSubmitI]	 	= @CanSubmitI,
-- 			[CanSubmitS]	 	= @CanSubmitS,
-- 			[CanSubmitA]	 	= @CanSubmitA,
-- 			[CanSubmitI10]	 	= @CanSubmitI10,
-- 			[CanSubmitS10]	 	= @CanSubmitS10,
-- 			[CanSubmitA10]	 	= @CanSubmitA10,
-- 			[CanSubmitC10]		= @CanSubmitC10,
-- 			[CanSubmitR10] 	= @CanSubmitR10,
-- 			[CanSubmitM10]		= @CanSubmitM10,
-- 			[CanReSetA]		= @CanReSetA,
-- 			[CanReSetR]		= @CanReSetR,
-- 			[CanReSetC]		= @CanReSetC,
-- 			[LanguageID]	 	= @LanguageID,
-- 			[UserDateFormat]	= @UserDateFormat,
-- 			[DisplayMessages]	= @DisplayMessages,
-- 			[DisplayMultUser]	= @DisplayMultUser,
-- 			[AutoShowLookUp]	= @AutoShowLookUp,
-- 			[AutoShowClone]	= @AutoShowClone,
-- 			[FlyCalcGrouper]		= @FlyCalcGrouper,
-- 			[EnableQuickSearch]	= @EnableQuickSearch,
-- 			[SearchChartPrefix]	= @SearchChartPrefix,
-- 			[ShowVIP]		= @ShowVIP,
-- 			[CanModifyCharts]	= @CanModifyCharts, 
-- 			[PermitCPI]	 	= @PermitCPI,
-- 			[PermitChartLoc]	 	= @PermitChartLoc,
-- 			[PermitChartDef]	 	= @PermitChartDef,
-- 			[PermitTranscription]	= @PermitTranscription,
-- 			[PermitROI]	 	= @PermitROI,
-- 			[PermitCCR]	 	= @PermitCCR,
-- 			[PermitInPat]	 	= @PermitInPat,
-- 			[PermitSDS]	 	= @PermitSDS,
-- 			[PermitAmcare]	 	= @PermitAmcare,
-- 			[PermitCCR10]	 	= @PermitCCR10,
-- 			[PermitInPat10]	 	= @PermitInPat10,
-- 			[PermitSDS10]	 	= @PermitSDS10,
-- 			[PermitAmcare10]	= @PermitAmcare10,
-- 			[PermitCCRS10]		= @PermitCCRS10, 			
-- 			[PermitRehab10]		= @PermitRehab10,
-- 			[PermitOMHRS10]	= @PermitOMHRS10,
-- 			[PermitClinic]		= @PermitClinic, 
-- 			[PermitBatchGrouper]	= @PermitBatchGrouper,
-- 			[PermitCareMap]	 	= @PermitCareMap,
-- 			[PermitScheduler]	= @PermitScheduler, 
-- 			[PermitReportGen]	= @PermitReportGen,
-- 			[PermitCIHISubmit]	= @PermitCIHISubmit,
-- 			[PermitCIHICorrect]	= @PermitCIHICorrect,
-- 			[PermitBilling]		= @PermitBilling, 
-- 			[PermitBatchInterface]	= @PermitBatchInterface,
-- 			[PermitHL7Interface]	= @PermitHL7Interface,
-- 			[PermitUndelete]	 	= @PermitUndelete,
-- 			[PermitHospProf]	 	= @PermitHospProf,
-- 			[PermitInstProf]		= @PermitInstProf,
-- 			[PermitUserProf]	 	= @PermitUserProf,
-- 			[PermitLookUpMaint]	= @PermitLookUpMaint,
-- 			[PermitControlFile]	= @PermitControlFile,
-- 			[PermitVisitHist]		= @PermitVisitHist,
-- 			[PermitDAS]		= @PermitDAS,
-- 			[FlyCalcCACS]		= @FlyCalcCACS, 
-- 			[FlyCalcDPG]		= @FlyCalcDPG, 
-- 			[FlyCalcFIM]		= @FlyCalcFIM, 
-- 			[FlyCalcRUG]		= @FlyCalcRUG,
-- 			[PermitCCM]		= @PermitCCM,
-- 			[CanSubmitCCM]	= @CanSubmitCCM,
-- 			[CanViewWho]		= @CanViewWho
	where [RoleID] = @Code
end

GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
-- This is called by the Save Method of the User Profile Control.
CREATE     PROCEDURE [U_UsersRoles]
	(@RoleID		[int])
AS 

 DECLARE @IsAdmin AS INT
 DECLARE @CanSubmitI AS INT
 DECLARE @CanSubmitS AS INT
 DECLARE @CanSubmitA AS INT
 DECLARE @CanSubmitI10 AS INT
 DECLARE @CanSubmitS10 AS INT
 DECLARE @CanSubmitA10 AS INT
 DECLARE @CanSubmitC10 AS INT
 DECLARE @CanSubmitR10 AS INT
 DECLARE @CanSubmitM10 AS INT
 DECLARE @CanSubmitCL AS INT
 DECLARE @CanReSetA AS INT
 DECLARE @CanReSetR AS INT
 DECLARE @CanReSetC AS INT 
 DECLARE @LanguageID AS INT
 DECLARE @UserDateFormat AS INT
 DECLARE @DisplayMessages AS INT
 DECLARE @DisplayMultUser AS INT
 DECLARE @AutoShowLookUp AS INT
 DECLARE @AutoShowClone AS INT
 DECLARE @FlyCalcGrouper AS INT
 DECLARE @EnableQuickSearch AS INT
 DECLARE @SearchChartPrefix 	AS VARCHAR(3)
 DECLARE @ShowVIP AS INT
 DECLARE @CanModifyCharts AS INT
 DECLARE @PermitCPI AS INT
 DECLARE @PermitChartLoc AS INT
 DECLARE @PermitChartDef AS INT
 DECLARE @PermitTranscription AS INT
 DECLARE @PermitROI AS INT
 DECLARE @PermitCCR	 AS INT
 DECLARE @PermitInPat AS INT
 DECLARE @PermitSDS	 AS INT
 DECLARE @PermitAmcare AS INT
 DECLARE @PermitCCR10 AS INT
 DECLARE @PermitInPat10 AS INT
 DECLARE @PermitSDS10 AS INT
 DECLARE @PermitAmcare10 AS INT
 DECLARE @PermitCCRS10 AS INT 
 DECLARE @PermitRehab10 AS INT
 DECLARE @PermitOMHRS10 AS INT
 DECLARE @PermitClinic AS INT
 DECLARE @PermitBatchGrouper AS INT
 DECLARE @PermitCareMap AS INT
 DECLARE @PermitScheduler AS INT
 DECLARE @PermitReportGen AS INT
 DECLARE @PermitCIHISubmit AS INT
 DECLARE @PermitCIHICorrect AS INT
 DECLARE @PermitBilling AS INT
 DECLARE @PermitBatchInterface AS INT
 DECLARE @PermitHL7Interface AS INT
 DECLARE @PermitUndelete AS INT
 DECLARE @PermitHospProf AS INT
 DECLARE @PermitInstProf AS INT
 DECLARE @PermitUserProf AS INT
 DECLARE @PermitLookUpMaint AS INT
 DECLARE @PermitControlFile AS INT
 declare @PermitVisitHist as int
 declare @PermitDAS as int 
 declare @FlyCalcCACS as int
 declare @FlyCalcDPG as int
 declare @FlyCalcFIM as int
 declare @FlyCalcRUG as int
  
 declare @DefaultHospID  	as int
-- declare @CanSubmitM10 	as int
-- declare @PermitOMHRS10 	as int
-- declare @LUText  		as varchar(255)
 declare @CanReSetM 		as int
-- declare @NTAuthority 		as varchar(100) 
 declare @PermitProvdrMaint 	as int
 declare @PermitRegionProf	as int
 declare @DisplayChrtLinks 	as int
 declare @AccessLockChart 	as int
 declare @PromptLoc 		as int
 declare @PromptDef 		as int
 declare @AmCareFacFile  	as int
 declare @CCRSFacFile 		as int
 declare @RehabFacFile 	as int
 declare @OMHRSFacFile 	as int
 declare @DADSepFile 		as int
 declare @CCRSAuditFile 	as int
 declare @ImportDADErrors 	as int
 declare @ExecTermChrt 	as int
 declare @ShowAllRegion 	as int
 declare @PermitViewChartAct 	as int
 declare @PermitViewChartDef 	as int
 declare @PermitChartVolume 	as int
 declare @PermitWRUUpdates 	as int
 declare @PermitMDASLayer 	as int
 declare @PermitMDASPrivacy 	as int
 declare @MDASRecordLock 	as int
 declare @MDASSensitvity	as int
 declare @CanPurgeVolQue 	as int
 declare @PermitAdapCS	as int
 declare @PermitCCM as int 
 declare @CanSubmitCCM as int 
 declare @CanViewWho	as int
 declare @FlyCalcSCIPP as int 
 declare @CanLaunchSolCom as int
 declare @CanPurgeLog as int 
 declare @CanDADInstFile int
 declare @CanClearCPILock int
 declare @CanSubmitCJRR int
 declare @PermitCJRR int
 declare @CanReSetCJRR int
 declare @FolioCAFile  varchar(250)
 declare @FolioCCIFile varchar(250)
 declare @SelectQueue int

SELECT 
	@IsAdmin 		= [IsAdmin],
	@CanSubmitI 		= [CanSubmitI],
	@CanSubmitS		= [CanSubmitS],
	@CanSubmitA		= [CanSubmitA],
	@CanSubmitI10		= [CanSubmitI10],
	@CanSubmitS10	= [CanSubmitS10],
	@CanSubmitA10	= [CanSubmitA10],
	@CanSubmitC10 	= [CanSubmitC10],	
	@CanSubmitR10 	= [CanSubmitR10],
	@CanSubmitM10 	= [CanSubmitM10],
	@CanSubmitCL 		= [CanSubmitCL],
	@CanReSetA 		= [CanReSetA],
	@CanReSetR 		= [CanReSetR],
	@CanReSetC		= [CanReSetC],
	@LanguageID	 	= [LanguageID],
	@UserDateFormat 	= [UserDateFormat],
	@DisplayMessages	= [DisplayMessages],
	@DisplayMultUser 	= [DisplayMultUser],
	@AutoShowLookUp	= [AutoShowLookUp],
	@AutoShowClone	= [AutoShowClone],
	@FlyCalcGrouper	= [FlyCalcGrouper],
	@EnableQuickSearch	= [EnableQuickSearch],
	@SearchChartPrefix 	= [SearchChartPrefix],
	@ShowVIP		= [ShowVIP],
	@CanModifyCharts 	= [CanModifyCharts], 
	@PermitCPI		= [PermitCPI],
	@PermitChartLoc	= [PermitChartLoc],
	@PermitChartDef	= [PermitChartDef],
	@PermitTranscription	= [PermitTranscription],
	@PermitROI		= [PermitROI],
	@PermitCCR		= [PermitCCR],
	@PermitInPat		= [PermitInPat],
	@PermitSDS		= [PermitSDS],
	@PermitAmcare		= [PermitAmcare],
	@PermitCCR10		= [PermitCCR10],
	@PermitInPat10		= [PermitInPat10],
	@PermitSDS10		= [PermitSDS10],
	@PermitAmcare10	= [PermitAmcare10],
	@PermitCCRS10 	= [PermitCCRS10], 
	@PermitRehab10	= [PermitRehab10],
	@PermitOMHRS10 	= [PermitOMHRS10],
	@PermitClinic		= [PermitClinic],
	@PermitBatchGrouper	= [PermitBatchGrouper],
	@PermitCareMap	= [PermitCareMap],
	@PermitScheduler 	= [PermitScheduler],
	@PermitReportGen	= [PermitReportGen],
	@PermitCIHISubmit	= [PermitCIHISubmit],
	@PermitCIHICorrect	= [PermitCIHICorrect],
	@PermitBilling 		= [PermitBilling],
	@PermitBatchInterface	= [PermitBatchInterface],
	@PermitHL7Interface	= [PermitHL7Interface],	
	@PermitUndelete	= [PermitUndelete],
	@PermitHospProf	= [PermitHospProf]	,
	@PermitInstProf		= [PermitInstProf],
	@PermitUserProf	= [PermitUserProf],
	@PermitLookUpMaint	= [PermitLookUpMaint],
	@PermitControlFile	= [PermitControlFile],
	@PermitVisitHist		= [PermitVisitHist],
	@PermitDAS		= [PermitDAS],
	@FlyCalcCACS 		= [FlyCalcCACS], 
	@FlyCalcDPG 		= [FlyCalcDPG], 
	@FlyCalcFIM 		= [FlyCalcFIM], 
	@FlyCalcRUG 		= [FlyCalcRUG],

	@DefaultHospID  	= [DefaultHospID],
 	--@LUText  		= [LUText],
 	@CanReSetM 		= [CanReSetM],
 	--@NTAuthority 		= [NTAuthority],
 	@PermitProvdrMaint 	= [PermitProvdrMaint],
 	@PermitRegionProf	= [PermitRegionProf],
	@DisplayChrtLinks 	= [DisplayChrtLinks],
	@AccessLockChart 	= [AccessLockChart],
	@PromptLoc 		= [PromptLoc],
	@PromptDef 		= [PromptDef],
	@AmCareFacFile  	= [AmCareFacFile],
	@CCRSFacFile 		= [CCRSFacFile],
	@RehabFacFile 	= [RehabFacFile],
	@OMHRSFacFile 	= [OMHRSFacFile],
	@DADSepFile 		= [DADSepFile],
	@CCRSAuditFile 	= [CCRSAuditFile],
	@ImportDADErrors 	= [ImportDADErrors],
	@ExecTermChrt 	= [ExecTermChrt],
	@ShowAllRegion 	= [ShowAllRegion],
	@PermitViewChartAct 	= [PermitViewChartAct],
	@PermitViewChartDef 	= [PermitViewChartDef],
	@PermitChartVolume 	= [PermitChartVolume],
	@PermitWRUUpdates 	= [PermitWRUUpdates],
	@PermitMDASLayer 	= [PermitMDASLayer],
	@PermitMDASPrivacy 	= [PermitMDASPrivacy],
	@MDASRecordLock 	= [MDASRecordLock],
	@MDASSensitvity	= [MDASSensitvity],
	@CanPurgeVolQue 	= [CanPurgeVolQue],
	@PermitAdapCS		= [PermitAdapCS],

	@PermitCCM 		= [PermitCCM],
	@CanSubmitCCM 	= [CanSubmitCCM],
	@CanViewWho		= [CanViewWho],
	@FlyCalcSCIPP 		= [FlyCalcSCIPP],
	@CanLaunchSolCom 	= [CanLaunchSolCom],
	@CanPurgeLog		= [CanPurgeLog],
	@CanDADInstFile = DADInstFile,
	@CanClearCPILock = CanClearCPILock,
	@CanSubmitCJRR		= [CanSubmitCJRR],
	@PermitCJRR			= [PermitCJRR],
	@CanReSetCJRR		= [CanReSetCJRR],
	@FolioCAFile        = [FolioCAFile],
	@FolioCCIFile       = [FolioCCIFile],
    @SelectQueue        = [SelectQueue]

FROM [U_Users] 
WHERE Code = @RoleID

UPDATE [U_Users] SET  	
	[IsAdmin]		= @IsAdmin,
	[CanSubmitI]	 	= @CanSubmitI,
	[CanSubmitS]	 	= @CanSubmitS,
	[CanSubmitA]	 	= @CanSubmitA,
	[CanSubmitI10]	 	= @CanSubmitI10,
	[CanSubmitS10]	 	= @CanSubmitS10,
	[CanSubmitA10]	 	= @CanSubmitA10,
	[CanSubmitC10]		= @CanSubmitC10,
	[CanSubmitR10] 	= @CanSubmitR10,
	[CanSubmitM10]		= @CanSubmitM10,
	[CanSubmitCL]		= @CanSubmitCL,
	[CanReSetA]		= @CanReSetA,
	[CanReSetR]		= @CanReSetR,
	[CanReSetC]		= @CanReSetC,
	[LanguageID]	 	= @LanguageID,
	[UserDateFormat]	= @UserDateFormat,
	[DisplayMessages]	= @DisplayMessages,
	[DisplayMultUser]	= @DisplayMultUser,
	[AutoShowLookUp]	= @AutoShowLookUp,
	[AutoShowClone]	= @AutoShowClone,
	[FlyCalcGrouper]		= @FlyCalcGrouper,
	[EnableQuickSearch]	= @EnableQuickSearch,
	[SearchChartPrefix]	= @SearchChartPrefix,
	[ShowVIP]		= @ShowVIP,
	[CanModifyCharts]	= @CanModifyCharts,
	[PermitCPI]	 	= @PermitCPI,
	[PermitChartLoc]	 	= @PermitChartLoc,
	[PermitChartDef]	 	= @PermitChartDef,
	[PermitTranscription]	= @PermitTranscription,
	[PermitROI]	 	= @PermitROI,
	[PermitCCR]	 	= @PermitCCR,
	[PermitInPat]	 	= @PermitInPat,
	[PermitSDS]	 	= @PermitSDS,
	[PermitAmcare]	 	= @PermitAmcare,
	[PermitCCR10]	 	= @PermitCCR10,
	[PermitInPat10]	 	= @PermitInPat10,
	[PermitSDS10]	 	= @PermitSDS10,
	[PermitAmcare10] 	= @PermitAmcare10,
	[PermitCCRS10]		= @PermitCCRS10, 
	[PermitRehab10]		= @PermitRehab10,
	[PermitOMHRS10]	= @PermitOMHRS10,
	[PermitClinic]		= @PermitClinic,
	[PermitBatchGrouper]	= @PermitBatchGrouper,
	[PermitCareMap]	 	= @PermitCareMap,
	[PermitScheduler]	= @PermitScheduler,
	[PermitReportGen]	= @PermitReportGen,
	[PermitCIHISubmit]	= @PermitCIHISubmit,
	[PermitCIHICorrect]	= @PermitCIHICorrect,
	[PermitBilling]		= @PermitBilling,
	[PermitBatchInterface]	= @PermitBatchInterface,
	[PermitHL7Interface]	= @PermitHL7Interface,
	[PermitUndelete]	 	= @PermitUndelete,
	[PermitHospProf]	 	= @PermitHospProf,
	[PermitInstProf]		= @PermitInstProf,
	[PermitUserProf]	 	= @PermitUserProf,
	[PermitLookUpMaint]	= @PermitLookUpMaint,
	[PermitControlFile]	= @PermitControlFile,
	[PermitVisitHist]		= @PermitVisitHist,
	[PermitDAS]		= @PermitDAS,
	[FlyCalcCACS] 		= @FlyCalcCACS, 
	[FlyCalcDPG] 		= @FlyCalcDPG, 
	[FlyCalcFIM] 		= @FlyCalcFIM, 
	[FlyCalcRUG] 		= @FlyCalcRUG,

	[DefaultHospID]  	= @DefaultHospID,
 	[CanReSetM] 		= @CanReSetM,
 	[PermitProvdrMaint] 	= @PermitProvdrMaint,
 	[PermitRegionProf]	= @PermitRegionProf,
	[DisplayChrtLinks] 	= @DisplayChrtLinks,
	[AccessLockChart] 	= @AccessLockChart,
	[PromptLoc] 		= @PromptLoc,
	[PromptDef] 		= @PromptDef,
	[AmCareFacFile]  	= @AmCareFacFile,
	[CCRSFacFile] 		= @CCRSFacFile,
	[RehabFacFile] 		= @RehabFacFile,
	[OMHRSFacFile] 	= @OMHRSFacFile,
	[DADSepFile] 		= @DADSepFile,
	[CCRSAuditFile] 		= @CCRSAuditFile,
	[ImportDADErrors] 	= @ImportDADErrors,
	[ExecTermChrt] 		= @ExecTermChrt,
	[ShowAllRegion] 	= @ShowAllRegion,
	[PermitViewChartAct] 	= @PermitViewChartAct,
	[PermitViewChartDef] 	= @PermitViewChartDef,
	[PermitChartVolume] 	= @PermitChartVolume,
	[PermitWRUUpdates] 	= @PermitWRUUpdates,
	[PermitMDASLayer] 	= @PermitMDASLayer,
	[PermitMDASPrivacy] 	= @PermitMDASPrivacy,
	[MDASRecordLock] 	= @MDASRecordLock,
	[MDASSensitvity]	= @MDASSensitvity,
	[CanPurgeVolQue] 	= @CanPurgeVolQue,
	[PermitAdapCS]		= @PermitAdapCS,

	[PermitCCM]		= @PermitCCM,
	[CanSubmitCCM]	= @CanSubmitCCM,
	[CanViewWho]		= @CanViewWho,
	[FlyCalcSCIPP]		= @FlyCalcSCIPP,
	[CanLaunchSolCom]	= @CanLaunchSolCom,
	[CanPurgeLog]		= @CanPurgeLog,
	DADInstFile = @CanDADInstFile,
	CanClearCPILock = @CanClearCPILock,
	[CanSubmitCJRR]		= @CanSubmitCJRR,
	[PermitCJRR]		= @PermitCJRR,
	[CanReSetCJRR]		= @CanReSetCJRR,
	[FolioCAFile]       = @FolioCAFile,
    [FolioCCIFile]      = @FolioCCIFile,
    [SelectQueue]       = @SelectQueue
WHERE ([RoleID] = @RoleID)

GO
