Skip to content

HRCM Procedure Schema

DataBase Name:HRCM

Procedure Name:CIRS_GetDocumentsToFormat

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[CIRS_GetDocumentsToFormat]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      SrinivasA
-- Create date: 05/02/2018
-- Description: Before Processing document we are formatting the document
-- =============================================
CREATE PROCEDURE [dbo].[CIRS_GetDocumentsToFormat]  
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try

            select top 26 hdd.DocumentID,
        (CASE WHEN mds.DocumentSourceID=3
          THEN
            (CASE WHEN CHARINDEX('base64^',hdd.Document,1)>0
              THEN (SUBSTRING(hdd.Document,CHARINDEX('base64^',hdd.Document) + LEN('base64^'),LEN(hdd.Document)))
              ELSE (hdd.Document)
            END)
          ELSE hdd.Document 
        END) as Document,mds.DocumentSourceID,hd.formatted
        from HIM_DocumentData hdd
        inner join HIM_Document hd on hdd.DocumentID=hd.DocumentID
        inner join MST_DocumentType mdt on mdt.DocumentTypeID=hd.DocumentTypeID
        inner join MST_DocumentSource mds on mds.DocumentSourceID=mdt.DocumentSourceID
        where mds.DocumentSourceID in (1,2,3) and hd.Formatted=0 and hd.DocumentID in(118535)

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo 'No Input Params','CIRS'
    End Catch
END

-- exec [CIRS_GetDocumentsToFormat]
--update HIM_Document set formatted=0 where documentid in(111890,40277133,40277124,40277022)
-- select * from him_DocumentData where documentid=111918
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:CIRS_GetDocumentsToProcess

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[CIRS_GetDocumentsToProcess]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 04/18/2018
-- Description: Get Pending Documents to Anlysis
-- =============================================
CREATE PROCEDURE [dbo].[CIRS_GetDocumentsToProcess]     
@RunningDocumentType varchar(15)
AS
Declare @InputParamQry varchar(200)
SET @InputParamQry='@RunningDocumentType: '+''+@runningDocumentType+''
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON; 
    Begin Try
        select  hdd.DocumentID,1 hospitalId,hdd.Document,hd.DocumentTypeID,mdt.DocumentAliasName,hd.TranscriptionDateTime,hd.AccountNumber,
        hv.PatientClass,DATEDIFF(MONTH,hp.DOB,hv.AdmitDate)/12 as Age,DATEDIFF(DAY,hp.DOB,hv.AdmitDate) as AgeInDays,hp.Gender,hd.HospitalDay
        from HIM_DocumentData hdd
        inner join HIM_Document hd on hdd.DocumentID=hd.DocumentID
        inner join MST_DocumentType mdt on mdt.DocumentTypeID=hd.DocumentTypeID
        inner join HIM_Visit hv on hv.AccountNumber=hd.AccountNumber
        inner join HIM_Patient hp on hp.PatientId=hv.PatientID
        where (
        (@runningDocumentType='O' and mdt.InternalDocumentTypeID=4) or
        (@runningDocumentType='RAD' and mdt.InternalDocumentTypeID=7) or
        (@runningDocumentType='RESQRY' and mdt.InternalDocumentTypeID=8) or
        (@runningDocumentType='H' and mdt.InternalDocumentTypeID in (1,2,3,5,6,99))) and
        -- hd.DocumentRunningStatusID=0 and hd.Formatted=1 and hd.HospitalDay is not null and
        -- hv.patientclass='I' and 
        -- hv.HospitalService not in ('13','16','30','40','71','94','96','97','VE','VB') and
         hv.admitdate is not NULL and hv.admitdate<=GETDATE() --and hv.LocationRoom!='' 
         and hdd.DocumentID in(40263862)        
    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo @InputParamQry,'CIRS'
    End Catch    
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:CIRS_RunPCSCodeExclusion

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[CIRS_RunPCSCodeExclusion]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 05/22/2018
-- Description: Excludes the Procedure Codes based on PCSCode,PCSContent(Operation)
-- =============================================
CREATE PROCEDURE [dbo].[CIRS_RunPCSCodeExclusion] 
    @AccountNumber varchar(20)  
AS

/**** To exclude the codes, which has low priority by changing its rstatus field at TotalOperationInfo table ****/ 
BEGIN
    Begin Try
    /******** PCSCode Elimination By Code********/  
      update NLP_PCSCodeByDocument set [RStatus]=1 where PcsCode in(  
      select distinct fcode from (  
      select i.AccountNumber,d.Proccode fcode,d.Priority dis_priority,d.GroupId dis_Groupid,  
      DENSE_RANK() over(PARTITION by AccountNumber,d.groupid order by d.groupid,d.Priority desc) Rank1  
      from NLP_PCSCodeByDocument i  
      inner join MasterHRCM.dbo.MST_PCSExclusionByCode d on i.PcsCode = d.ProcCode  
      where AccountNumber=@AccountNumber 
      and i.rstatus=0  
      ) a where Rank1 <> 1     
    )  
    and AccountNumber = @AccountNumber and rStatus=0 

     /******** PCSOperation Elimination By Content********/
    update NLP_PCSCodeByDocument set [Rstatus] = 1 where PcsDesc in (
    select distinct dis_operation from (  
    select p.AccountNumber,pe.Content dis_operation,pe.Priority dis_priority,pe.GroupId dis_Groupid,  
    DENSE_RANK() over(PARTITION by AccountNumber,pe.groupid order by pe.groupid,pe.Priority desc) Rank1  
    from NLP_PCSCodeByDocument p  
    inner join MasterHRCM.dbo.MST_PCSExclusionByContent pe on p.PcsDesc = pe.content  
    where AccountNumber=@AccountNumber
    and p.rstatus=0
    ) a where Rank1 <> 1     
    )
    and AccountNumber = @AccountNumber and rstatus=0

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo @AccountNumber,'CIRS'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:CIRS_UpdateDocumentContent

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[CIRS_UpdateDocumentContent]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      SrinivasA
-- Create date: 05/02/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[CIRS_UpdateDocumentContent]     
@DocumentID int,
@Document varchar(MAX)
AS
Declare @InputParamQry varchar(200)
SET @InputParamQry='@DocumentID: '+''+cast(@DocumentID as varchar(15))+''

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

    Update HIM_DocumentData set Document=@Document where DocumentID=@DocumentID
    Update HIM_Document set Formatted=1 where DocumentID=@DocumentID

    End Try
    Begin Catch 
         Exec usp_GetDBErrorInfo @InputParamQry,'CIRS'
    End Catch
END

--exec CIRS_UpdateDocumentContent 111918,
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:CRI_InsertDRG

Description:

Schema:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[CRI_InsertDRG]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[CRI_InsertDRG]
    @PathFileName varchar(100),
    @ReportDate varchar(25)
As
Declare @Qry varchar(2000)
declare @reimbdrgendTime datetime
Declare @InputParamQry varchar(200)
SET @InputParamQry='PathFileName: '+''+@PathFileName+''+'|'+'ReportDate: '+''+@ReportDate+''
Begin
Begin Try

    Begin Transaction

    CREATE TABLE #ReimburseTemp(
    [AccountNo] [varchar](50) NOT NULL,[TotalCharges] [varchar](50) NULL,[TotalCost] [varchar](50) NULL,[VarianceCharges] [varchar](50) NULL,
    [VarianceCosts] [varchar](50) NULL,[ExpectedReimbursement] [varchar](50) NULL,[TotalExpected] [varchar](50) NULL,[ActualPrimary] [varchar](50) NULL,
    [ActualSecondary] [varchar](50) NULL,[CompleteForBilling] [datetime] NULL,[DRG] [varchar](50) NULL,[DRGDesc] [varchar](250) NULL,
    [MDC] [varchar](50) NULL,[MDCDesc] [varchar](250) NULL,[DRGWeight] [varchar](50) NULL,[AMLOS] [varchar](50) NULL,[GMLOS] [varchar](50) NULL,
    [LOS] [varchar](50) NULL,[APR] [varchar](50) NULL,[APRDesc] [varchar](120) NULL,[APRWeight] [varchar](50) NULL,[SvrtyCode] [varchar](50) NULL,
    [SvrtyDesc] [varchar](100) NULL,[MortalityCode] [varchar](50) NULL,[MortalityDesc] [varchar](100) NULL,[DiagCode] [varchar](50) NULL,
    [DiagDesc] [varchar](250) NULL,[DiagType] [varchar](50) NULL,[PresentAtAdmit] [varchar](10) NULL,[ProCode] [varchar](50) NULL,
    [ProDesc] [varchar](250) NULL,[APR_MDC] [varchar](50) NULL,[APR_MDC_Desc] [varchar](150) NULL,[APR_AM_LOS] [varchar](50) NULL,
    [APR_GM_LOS] [varchar](50) NULL);

    --Step 1: Build Valid BULK INSERT Statement
    SET @Qry = 'BULK INSERT #ReimburseTemp
    FROM ''' + @PathFileName  + '''
    WITH
    ( 
    FIRSTROW = 2, 
    FIELDTERMINATOR = ''|'', 
    ROWTERMINATOR = ''\n''
    )'

    --Step 2: Execute BULK INSERT statement
    EXEC (@Qry)

    --Step 3:
    Insert Into TMP_DRG(AccountNo,TotalCharges,TotalCost,VarianceCharges,VarianceCosts,ExpectedReimbursement,TotalExpected,ActualPrimary,ActualSecondary,CompleteForBilling,DRG,DRGDesc,MDC,MDCDesc,DRGWeight,AMLOS,GMLOS,LOS,APR,APRDesc,APRWeight,SvrtyCode,SvrtyDesc,MortalityCode,MortalityDesc,DiagCode,DiagDesc,DiagType,PresentAtAdmit,ProCode,ProDesc,APR_MDC,APR_MDC_Desc,APR_AM_LOS,APR_GM_LOS)
    select AccountNo,TotalCharges,TotalCost,VarianceCharges,VarianceCosts,ExpectedReimbursement,TotalExpected,ActualPrimary,ActualSecondary,CompleteForBilling,DRG,DRGDesc,MDC,MDCDesc,DRGWeight,AMLOS,GMLOS,LOS,APR,APRDesc,APRWeight,SvrtyCode,SvrtyDesc,MortalityCode,MortalityDesc,DiagCode,DiagDesc,DiagType,PresentAtAdmit,ProCode,ProDesc,APR_MDC,APR_MDC_Desc,APR_AM_LOS,APR_GM_LOS 
    from #ReimburseTemp 

    delete from FTP_DRG where AccountNumber in (select distinct LTrim(RTrim(AccountNo)) from #ReimburseTemp)

    --Step 4: INSERT data into final table  
    Insert Into FTP_DRG(AccountNumber,MSDRG,MSDRGDesc,MSDRGWeight,MSDRGMDC,MSDRGGLOS,MSDRGALOS,
    APRDRG,APRDRGDesc,APRDRGWeight,APRDRGMDC,APRDRGGLOS,APRDRGALOS,SOI,ROM,TotalCharge,TotalCost,
    VarianceCharge,VarianceCost,ExpectedReimbursement,TotalExpected,ReportDate)
    Select distinct LTrim(RTrim(RT.AccountNo)),LTrim(RTrim(RT.DRG)),LTrim(RTrim(RT.DRGDesc)),LTrim(RTrim(RT.DRGWeight)),LTrim(RTrim(RT.MDC)),
    LTrim(RTrim(RT.GMLOS)),LTrim(RTrim(RT.AMLOS)),LTrim(RTrim(RT.APR)),LTrim(RTrim(RT.APRDesc)),LTrim(RTrim(RT.APRWeight)),
    LTrim(RTrim(RT.APR_MDC)),LTrim(RTrim(RT.APR_GM_LOS)),LTrim(RTrim(RT.APR_AM_LOS)),LTrim(RTrim(RT.SvrtyCode)),LTrim(RTrim(RT.MortalityCode)), 
    LTrim(RTrim(RT.TotalCharges)),LTrim(RTrim(RT.TotalCost)),LTrim(RTrim(RT.VarianceCharges)),LTrim(RTrim(RT.VarianceCosts)),   
    LTrim(RTrim(RT.ExpectedReimbursement)),LTrim(RTrim(RT.TotalExpected)),CAST(@ReportDate as datetime) as ReportDate
    from #ReimburseTemp RT left join FTP_DRG r
    on r.AccountNumber=LTrim(RTrim(RT.AccountNo))
    and r.TotalCharge=LTrim(RTrim(RT.TotalCharges))
    and r.TotalCost=LTrim(RTrim(RT.TotalCost))
    and r.VarianceCharge=LTrim(RTrim(RT.VarianceCharges))
    and r.VarianceCost=LTrim(RTrim(RT.VarianceCosts))
    and r.ExpectedReimbursement=LTrim(RTrim(RT.ExpectedReimbursement))
    and r.TotalExpected=LTrim(RTrim(RT.TotalExpected))  
    and r.MSDRG=LTrim(RTrim(RT.DRG))
    and r.MSDRGDesc=LTrim(RTrim(RT.DRGDesc))
    and r.MSDRGMDC=LTrim(RTrim(RT.MDC)) 
    and r.MSDRGWeight=LTrim(RTrim(RT.DRGWeight))
    and r.MSDRGALOS=LTrim(RTrim(RT.AMLOS))
    and r.MSDRGGLOS=LTrim(RTrim(RT.GMLOS))  
    and ISNULL(LTrim(RTrim(r.APRDRG)),0)=ISNULL(LTrim(RTrim(RT.APR)),0)
    and ISNULL(LTrim(RTrim(r.APRDRGDesc)),0)=ISNULL(LTrim(RTrim(RT.APRDesc)),0)
    and r.APRDRGWeight=LTrim(RTrim(RT.APRWeight))
    and ISNULL(LTrim(RTrim(r.SOI)),0)=ISNULL(LTrim(RTrim(RT.SvrtyCode)),0)  
    and ISNULL(LTrim(RTrim(r.ROM)),0)=ISNULL(LTrim(RTrim(RT.MortalityCode)),0)  
    and r.APRDRGMDC=LTrim(RTrim(RT.APR_MDC))    
    and r.APRDRGALOS=LTrim(RTrim(RT.APR_AM_LOS))
    and r.APRDRGGLOS=LTrim(RTrim(RT.APR_GM_LOS))
    where r.DRGID is null

    --FTP_DXCode
    insert into FTP_DXCode(AccountNumber,DXCode,DXDesc,POA,DXType,DXPriority)
    Select distinct LTrim(RTrim(RT.AccountNo)),
    case when LEN(LTrim(RTrim(RT.DiagCode)))>3 then LEFT(LTrim(RTrim(RT.DiagCode)),3)+'.'+RIGHT(LTrim(RTrim(RT.DiagCode)),LEN(LTrim(RTrim(RT.DiagCode)))-3) else LTrim(RTrim(RT.DiagCode)) end,
    LTrim(RTrim(RT.DiagDesc)),LTrim(RTrim(RT.PresentAtAdmit)),LTrim(RTrim(RT.DiagType)),
    case LTrim(RTrim(RT.DiagType)) when 'A' then 1 when 'P' then 2 when 'S' then 3 else 4 end
    from #ReimburseTemp RT left join FTP_DXCode fdx
    on fdx.AccountNumber=LTrim(RTrim(RT.AccountNo))
    and fdx.DXCode=case when LEN(LTrim(RTrim(RT.DiagCode)))>3 then LEFT(LTrim(RTrim(RT.DiagCode)),3)+'.'+RIGHT(LTrim(RTrim(RT.DiagCode)),LEN(LTrim(RTrim(RT.DiagCode)))-3) else LTrim(RTrim(RT.DiagCode)) end
    and fdx.DXDesc=LTrim(RTrim(RT.DiagDesc))
    where fdx.DXCode is null

    --FTP_PCSCode
    insert into FTP_PCSCode(AccountNumber,PCSCode,PCSDesc)
    Select distinct LTrim(RTrim(RT.AccountNo)),LTrim(RTrim(RT.ProCode)),LTrim(RTrim(RT.ProDesc))
    from #ReimburseTemp RT left join FTP_PCSCode fpcs
    on fpcs.AccountNumber=LTrim(RTrim(RT.AccountNo))
    and fpcs.PCSCode=LTrim(RTrim(RT.ProCode))
    and fpcs.PCSDesc=LTrim(RTrim(RT.ProDesc))
    where fpcs.PCSCode is null  

    Commit Transaction  
End Try
Begin Catch
    IF(@@TRANCOUNT>0)
    Rollback Transaction    

    Exec usp_GetDBErrorInfo @InputParamQry,'CRI'    
End Catch
End
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:CRI_InsertIPMedication

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[CRI_InsertIPMedication]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[CRI_InsertIPMedication]
    @PathFileName varchar(100),
    @ReportDate varchar(25)
As
Declare @Qry varchar(2000)
Declare @InputParamQry varchar(200)
SET @InputParamQry='PathFileName: '+''+@PathFileName+''+'|'+'ReportDate: '+''+@ReportDate+''
Begin
    Begin Try

    Begin Transaction

    CREATE TABLE #MedicationsTemp(
    [Encounter] [varchar](20) NOT NULL,[MedicationDate] [datetime] NULL,[Dose] [varchar](100) NULL,[Route] [varchar](150) NULL,
    [MedicationMnemonic] [varchar](150) NULL,[MedicationName] [varchar](350) NULL,[Brand] [varchar](50) NULL,[OrderType] [varchar](150) NULL,
    [Category] [varchar](50) NULL,[MedStopDate] [datetime] NULL
    );

    --Step 1: Build Valid BULK INSERT Statement
    SET @Qry = 'BULK INSERT #MedicationsTemp
    FROM ''' + @PathFileName  + '''
    WITH
    ( 
    FIRSTROW = 2, 
    FIELDTERMINATOR = ''|'', 
    ROWTERMINATOR = ''\n''
    )'

    --Step 2: Execute BULK INSERT statement
    EXEC (@Qry)

    --Step 3:
    Insert Into TMP_IPMedication(Encounter,MedicationDate,Dose,Route,MedicationMnemonic,MedicationName,Brand,OrderType,Category,MedStopDate)
    select Encounter,MedicationDate,Dose,Route,MedicationMnemonic,MedicationName,Brand,OrderType,Category,MedStopDate from #MedicationsTemp     

    --Step 4: Deleting Duplicates between TempTable and MainTable   
    delete MCT from #MedicationsTemp MCT inner join FTP_IPMedication MC on
    LTrim(RTrim(MCT.Encounter))=MC.AccountNumber and 
    LTrim(RTrim(MCT.MedicationDate))=MC.StartDate and   
    ISNULL(LTrim(RTrim(MCT.Dose)),0)=ISNULL(MC.Dose,0) and 
    LTrim(RTrim(MCT.MedicationName))=MC.MedicationName

    --Step 5: INSERT data into final table
    Insert into FTP_IPMedication(AccountNumber,MedicationName,Dose,Route,StartDate,EndDate,GenericName,BrandName,MedicationType,ReportDate) 
    Select distinct LTrim(RTrim(MT.Encounter)),LTrim(RTrim(MT.MedicationName)),LTrim(RTrim(MT.Dose)),LTrim(RTrim(MT.[Route])),LTrim(RTrim(MT.MedicationDate)),LTrim(RTrim(MT.MedStopDate)),
    LTrim(RTrim(MT.MedicationMnemonic)),LTrim(RTrim(MT.Brand)),LTrim(RTrim(MT.Category)),CAST(@ReportDate as datetime) as ReportDate
    from #MedicationsTemp MT 

    --Step 6: ReviewDay Update Query
    update M set HospitalDay= case when DateAdd(day,Datediff(day,0,M.StartDate),0)<DateAdd(day,Datediff(day,0,V.AdmitDate),0) then 0
    when DATEDIFF(day,admissionday,M.StartDate)<1 then 1 else DATEDIFF(day,admissionday,M.StartDate)+1 end  from
    FTP_IPMedication M inner join HIM_Visit V on M.AccountNumber = v.accountnumber inner join #MedicationsTemp mt on LTrim(RTrim(mt.Encounter)) = v.accountnumber
    where V.AdmitDate is not null

    Commit Transaction

    End Try
    Begin Catch 
        IF(@@TRANCOUNT>0)
        Rollback Transaction    

        Exec usp_GetDBErrorInfo @InputParamQry,'CRI'
    End Catch
End
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:CRI_InsertLab

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[CRI_InsertLab]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[CRI_InsertLab]
    @PathFileName varchar(100),
    @ReportDate varchar(25)
As
--Step 1: Build Valid BULK INSERT Statement
Declare @Qry varchar(2000)
Declare @InputParamQry varchar(200)
SET @InputParamQry='PathFileName:'+''+@PathFileName+''+'|'+'ReportDate: '+''+@ReportDate+''
Begin

Begin Try

    Begin Transaction

    CREATE TABLE #LabResultsTemp(
    [Encounter] [varchar](20) NOT NULL,[LabDateTime] [datetime] NULL,[TestMnemonic] [varchar](50) NULL,[TestName] [varchar](150) NULL,
    [Result] [varchar](150) NULL,[ReferenceRange] [varchar](200) NULL,[Unit] [varchar](50) NULL,[Department] [varchar](50) NULL,
    [LabOrder] [varchar](50) NULL,[LastActivity] [datetime] NULL
    );

    --SET @PathFileName = 'D:\LABResults_20170122.txt'
    SET @Qry = 'BULK INSERT #LabResultsTemp
    FROM ''' + @PathFileName  + '''
    WITH
    ( 
    FIRSTROW = 2, 
    FIELDTERMINATOR = ''|'', 
    ROWTERMINATOR = ''\n''
    )'

    --Step 2: Execute BULK INSERT statement
    EXEC (@Qry) 

    --Step 3:
    Insert into TMP_Lab(Encounter,LabDateTime,TestMnemonic,TestName,Result,ReferenceRange,Unit,Department,LabOrder,LastActivity)
    select Encounter,LabDateTime,TestMnemonic,TestName,Result,ReferenceRange,Unit,Department,LabOrder,LastActivity from #LabResultsTemp

    --Step 4: Deleting Duplicates between Temptable and MainTable   
    update #LabResultsTemp set result = case when result like '%.%' then substring(result,0,charindex('.',result)+3) else result end

    delete LRT from #LabResultsTemp LRT inner join FTP_Lab LR on
    LTrim(RTrim(LRT.Encounter))=LR.AccountNumber and
    LTrim(RTrim(LRT.LabDateTime))=LR.LabTestDate and
    LTrim(RTrim(LRT.TestName))=LR.TestName and
    ISNULL(LTrim(RTrim(LRT.Result)),0)=ISNULL(LR.Result,0) and
    ISNULL(LTrim(RTrim(LRT.ReferenceRange)),0)=ISNULL(LR.ReferenceRange,0)
    where LTrim(RTrim(LRT.TestMnemonic)) not like 'RL**'

    --Step 5: INSERT data into final table
    Insert into FTP_Lab(AccountNumber,TestName,Result,Unit,ReferenceRange,LabTestDate,ReportDate)   
    Select distinct LTrim(RTrim(LT.Encounter)),LTrim(RTrim(LT.TestName)),LTrim(RTrim(LT.Result)),LTrim(RTrim(LT.Unit)),
    LTRIM(RTrim(LT.ReferenceRange)),LTrim(RTrim(LT.LabDateTime)),CAST(@ReportDate as datetime) as ReportDate
    from #LabResultsTemp LT Where (LT.Result is not null or (LT.Result is null and LT.TestName is not null)) 
    and LTrim(RTrim(LT.TestMnemonic)) not like 'RL**'

    --Step 6: To Update Nonnumeric values to NumericResult Column
    Update FTP_Lab set NumericResult=case when isnumeric(replace(replace(Result,'<',''),'>','')) = 1 then replace(replace(Result,'<',''),'>','') else NULL end
    where InsertedDate>=DATEADD(MINUTE,-10,GETDATE())

    --Step 7:   HospitalDay Update Query
    update l set HospitalDay= case when DateAdd(day,Datediff(day,0,l.LabTestDate),0)<DateAdd(day,Datediff(day,0,V.AdmitDate),0) then 0
    when DATEDIFF(day,admissionday,l.LabTestDate)<1 then 1 else DATEDIFF(day,admissionday,l.LabTestDate)+1 end  from
    FTP_Lab l inner join HIM_Visit V on l.AccountNumber = v.accountnumber inner join #LabResultsTemp lt on LTrim(RTrim(lt.Encounter)) = v.accountnumber
    where v.AdmitDate is not null

    Commit Transaction

End Try
Begin Catch

    IF(@@TRANCOUNT>0)
    Rollback Transaction

    Exec usp_GetDBErrorInfo @InputParamQry,'CRI'

End Catch
End
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:CRI_InsertNurseNote

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[CRI_InsertNurseNote]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[CRI_InsertNurseNote]
    @PathFileName varchar(100),
    @ReportDate varchar(25)
As
Declare @Qry varchar(2000)
Declare @InputParamQry varchar(200)
SET @InputParamQry='PathFileName: '+''+@PathFileName+''+'|'+'ReportDate: '+''+@ReportDate+''
Begin
    Begin Try

    Begin Transaction

    CREATE TABLE #NursingTemp(
    [AccNo] [varchar](50) NOT NULL,[DocumentDateTime] [datetime] NULL,[NursingDateTime] [datetime] NULL,[VSQuery] [varchar](50) NULL,
    [VSQueryDescription] [varchar](max) NULL,[VSQueryValue] [varchar](500) NULL);

    --Step 1: Build Valid BULK INSERT Statement
    SET @Qry = 'BULK INSERT #NursingTemp
    FROM ''' + @PathFileName  + '''
    WITH
    ( 
    FIRSTROW = 1, 
    FIELDTERMINATOR = ''|'', 
    ROWTERMINATOR = ''\n''
    )'

    --Step 2: Execute BULK INSERT statement
    EXEC (@Qry)

    --Step 3:
    Insert Into TMP_NurseNote(AccNo,DocumentDateTime,NursingDateTime,VSQuery,VSQueryDescription,VSQueryValue)
    select AccNo,DocumentDateTime,NursingDateTime,VSQuery,VSQueryDescription,VSQueryValue from #NursingTemp

    --Step 4: INSERT data into final table..
    Insert FTP_NurseNote(AccountNumber,EventType,EventDesc,EventResult,NurseNoteDate,ReportDate)
    Select distinct LTrim(RTrim(MT.AccNo)),LTrim(RTrim(MT.VSQuery)),LTrim(RTrim(MT.VSQueryDescription)),
    LTrim(RTrim(isnull(MT.VSQueryValue,'N/A'))),LTrim(RTrim(MT.NursingDateTime)),CAST(@ReportDate as datetime) as ReportDate
    from #NursingTemp MT left join FTP_NurseNote n
    on n.AccountNumber=LTrim(RTrim(MT.AccNo))
    and n.NurseNoteDate=LTrim(RTrim(MT.NursingDateTime))    
    and n.EventType=LTrim(RTrim(MT.VSQuery))
    and n.EventDesc=LTrim(RTrim(MT.VSQueryDescription))
    and n.EventResult=LTrim(RTrim(isnull(MT.VSQueryValue,'N/A')))
    where n.NurseNoteID is null

    --Step 5: ReviewDay Update Query    
    update N set HospitalDay= case when DateAdd(day,Datediff(day,0,N.NurseNoteDate),0)<DateAdd(day,Datediff(day,0,V.AdmitDate),0) then 0
    when DATEDIFF(day,admissionday,N.NurseNoteDate)<1 then 1 else DATEDIFF(day,admissionday,N.NurseNoteDate)+1 end  from
    FTP_NurseNote N inner join HIM_Visit V on N.AccountNumber = v.accountnumber inner join #NursingTemp NT on LTrim(RTrim(NT.AccNo)) = v.accountnumber
    where V.AdmitDate is not null

    Commit Transaction

End Try
Begin Catch
    IF(@@TRANCOUNT>0)
        Rollback Transaction    

    Exec usp_GetDBErrorInfo @InputParamQry,'CRI'
End Catch
End
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:CRI_InsertVitalSign

Description:

Schema:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[CRI_InsertVitalSign]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[CRI_InsertVitalSign]
    @PathFileName varchar(100),
    @ReportDate varchar(25)
As
Declare @Qry varchar(2000)
Declare @InputParamQry varchar(200)
SET @InputParamQry='PathFileName: '+''+@PathFileName+''+'|'+'ReportDate: '+''+@ReportDate+''
Begin
Begin Try

    Begin Transaction

    CREATE TABLE #VitalTemp(
    [AccountNo] [varchar](20) NOT NULL,[VitalDate] [datetime] NULL,[VitalName] [varchar](50) NULL,[Result] [varchar](250) NULL);

    --Step 1: Build Valid BULK INSERT Statement
    SET @Qry = 'BULK INSERT #VitalTemp
    FROM ''' + @PathFileName  + '''
    WITH
    ( 
    FIRSTROW = 2, 
    FIELDTERMINATOR = ''|'', 
    ROWTERMINATOR = ''\n''
    )'

    --Step 2: Execute BULK INSERT statement
    EXEC (@Qry)

    --Step 3:
    Insert Into TMP_VitalSign(AccountNo,VitalDate,VitalName,Result)
    select AccountNo,VitalDate,VitalName,Result from #VitalTemp

    --Step 3: Deleteting duplicates between Temptable and MainTable
    delete vtl from #VitalTemp vtl inner join FTP_VitalSign mtv on
    LTrim(RTrim(vtl.AccountNo))=mtv.AccountNumber and
    LTrim(RTrim(vtl.VitalDate))=mtv.VitalSignDate and
    LTrim(RTrim(vtl.VitalName))=mtv.VitalSign and
    LTrim(RTrim(vtl.Result))=mtv.Result

    select distinct LTrim(RTrim(AccountNo)) AccountNo,LTrim(RTrim(VitalDate)) VitalDate,LTrim(RTrim(VitalName)) VitalName,LTrim(RTrim(Result)) Result,
    null Result1,LTrim(RTrim(Result)) StandardValue into #Temp1 from #VitalTemp where Result is not null

    --Step 4: INSERT data into final table
    update #Temp1 set Result = case when result like'[A-Za-z]%'
    then case when substring(result,2,charindex(' ',result,charindex(' ',result)+1))='' then substring(result,charindex(' ',result),len(result))
    else substring(ltrim(rtrim(substring(result,charindex(' ',result),len(result)))),0,charindex(' ',ltrim(rtrim(substring(result,charindex(' ',result),len(result))))))end
    else case when substring(result,0,charindex(' ',result))='' then result else substring(result,0,charindex(' ',result))end end

    update #Temp1 set result = replace(result,'%','') where result like'%[%]%'

    update #Temp1 set Result=SUBSTRING(Result,1,CHARINDEX('/',Result)-1),Result1=SUBSTRING(Result,CHARINDEX('/',Result)+1,LEN(Result))
    where  Result like '%[/]%' and CHARINDEX('/',Result,1)>0

    --Step 5:
    CREATE TABLE #VTemp(
    [AccountNo] [varchar](20),[VitalDate] [datetime] NULL,[VitalName] [varchar](50) NULL,[Result] [numeric](18,2) NULL,
    [Result1] [varchar](250) NULL,[StandardValue] [varchar](250) NULL);

    --Step 6:
    Insert into #VTemp(AccountNo,VitalDate,VitalName,Result,Result1,StandardValue)
    select AccountNo,VitalDate,VitalName,Result,Result1,StandardValue from #Temp1 where result not like'*********'

    --Step 7: Convert C Temperature to F
    update #VTemp set Result=dbo.Convert_Temperature(Result,'C') from #VTemp where VitalName in ('Temp','Skin Temp') and Result<50.0

    --Step 8: Convert WT from LBS, GMS to KGS    
    update #VTemp set Result=cast(round(Result*0.45359237,2) as numeric(36,2)) from #VTemp where VitalName='WT' and Standardvalue like '% lbs%'    
    update #VTemp set Result=cast(round(Result/1000,2) as numeric(36,2)) from #VTemp where VitalName='WT' and Standardvalue like '% gms%'

    --Step 9: Convert Height to Inches
    update #VTemp set Result=cast(round(Result*2.54,2) as numeric(36,2)) from #VTemp where VitalName='HT' and Standardvalue like '% IN%'

    --Step 10: Inserting Final Temp table values into Real Table
    Insert Into FTP_VitalSign(AccountNumber,VitalSign,Result,NumericResult,NumericResult2,VitalSignDate,ReportDate)
    Select distinct VT.AccountNo,VT.VitalName,VT.StandardValue,VT.Result,VT.Result1,VT.VitalDate,CAST(@ReportDate as datetime) as ReportDate
    from #VTemp VT where VT.Result is not null

    Update FTP_VitalSign set NumericResult = cast(round(NumericResult,0) as int) where VitalSign not in ('TEMP','SKIN TEMP','HT','WT') 
    and InsertedDate>=DATEADD(MINUTE,-10,GETDATE())

  --Step 11:ReviewDay Update Query
    update mv set HospitalDay= case when DateAdd(day,Datediff(day,0,mv.VitalSignDate),0)<DateAdd(day,Datediff(day,0,V.AdmitDate),0) then 0
    when DATEDIFF(day,admissionday,mv.VitalSignDate)<1 then 1 else DATEDIFF(day,admissionday,mv.VitalSignDate)+1 end  from
    FTP_VitalSign mv inner join HIM_Visit V on mv.AccountNumber = v.accountnumber inner join #VTemp vt on vt.AccountNo = v.accountnumber
    where V.AdmitDate is not null

    Commit Transaction  
End Try
Begin Catch
    IF(@@TRANCOUNT>0)
    Rollback Transaction    

    Exec usp_GetDBErrorInfo @InputParamQry,'CRI'
End Catch
End
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_GetObgGestationalWeek

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_GetObgGestationalWeek]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/07/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_GetObgGestationalWeek] 
@AccountNumber varchar(30),
@trimester1 int,
@gestationalWeeks int,
@outweeks varchar(100) output
AS
Declare @InputParamQry varchar(200)
SET @InputParamQry='AccountNumber: '+''+@AccountNumber+''+'|'+
'Trimester1: '+''+cast(@trimester1 as varchar(15))+''+'|'+
'GestationalWeeks: '+''+cast(@gestationalWeeks as varchar(5))+''

BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try
        if not exists (select top 1 1 from NLP_DxFactor where AccountNumber=@AccountNumber and factorname='preg')       
        Insert into NLP_DxFactor(AccountNumber,FactorName)values(@AccountNumber,'preg')

        if(@trimester1 = 0)
        BEGIN
            if not exists (select top 1 1 from NLP_DxFactor where AccountNumber=@AccountNumber and FactorName like 'gestationalweeks%')
                set @outweeks=37
            else
            begin       
                select @outweeks = FactorName from  NLP_DxFactor where AccountNumber=@AccountNumber and FactorName like 'gestationalweeks%'
                set @outweeks =REPLACE(@outweeks,'gestationalweeks: ','')
            end
        END
        else if(@trimester1=2 and @gestationalWeeks=0)          
                begin
                    if not exists (select top 1 1 from NLP_DxFactor where AccountNumber=@AccountNumber and FactorName like 'gestationalweeks%')
                    begin                   
                        insert into NLP_DxFactor(AccountNumber,FactorName)values(@AccountNumber,'gestationalweeks: 27')
                        set @outweeks=27
                    end             
                    else
                    begin
                        select @outweeks= FactorName from NLP_DxFactor where AccountNumber=@AccountNumber and FactorName like 'gestationalweeks%'
                        set @outweeks =REPLACE(@outweeks,'gestationalweeks: ','')
                    end 
                end 
                else
                begin
                    if not exists (select top 1 1 from NLP_DxFactor where AccountNumber=@AccountNumber and FactorName like 'gestationalweeks%')
                    begin
                        delete from NLP_DxCodeByDocument where AccountNumber=@AccountNumber and DxCode like 'Z3A.37'                        
                        insert into NLP_DxFactor(AccountNumber,FactorName)values(@AccountNumber,'gestationalweeks: '+convert(varchar(4),@gestationalWeeks))
                        set @outweeks=convert(varchar(20),@gestationalWeeks)
                    end
                    else
                    begin
                        select @outweeks= FactorName from NLP_DxFactor where AccountNumber=@AccountNumber and FactorName like 'gestationalweeks%'
                        set @outweeks =REPLACE(@outweeks,'gestationalweeks: ','')
                    end 
                end 
    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo @InputParamQry,'NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_GetPriorityPCSDeviceQualifier

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_GetPriorityPCSDeviceQualifier]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/13/2018
-- Description: Getting More Priority Device and Qualifier here on based table contents
-- =============================================
CREATE PROCEDURE [dbo].[NLP_GetPriorityPCSDeviceQualifier] 
    @operation varchar(50),
    @qualifier varchar(250),
    @device varchar(250),
    --@priorityQualifier varchar(50) OUT,
    @priorityDevice varchar(50) OUT
AS
Declare @QryStr varchar(5000)
BEGIN
    Begin Try

            Set @QryStr='
            Declare @priorityDevice varchar(50)

            select top 1 @priorityDevice = st_Device from (  
            select distinct d.device dis_Device,p.device st_Device,d.Priority dis_priority,d.GroupId dis_Groupid,  
            DENSE_RANK() over(PARTITION by d.groupid order by d.groupid,d.Priority desc) Rank1  
            from MasterHRCM.dbo.MST_DeviceExclusion d  
            inner join MasterHRCM.dbo.MST_PCSDevice p on d.Device = p.Device1
            where d.Device in ('+@device+')  
            ) a order by RANK1 desc  

            '           
            --set @priorityDevice = (@QryStr)
            exec (@QryStr)

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo '<Input-Params>','NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertAllergyDxData

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertAllergyDxData]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/06/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertAllergyDxData] 
@AccountNumber varchar(30),
@DocumentId int,  
@allergiesdis varchar(200),  
@medicine varchar(50),  
@StartId int,  
@EndId int,
@DocumentType varchar(20)
AS
Declare @InputParamQry varchar(500)
SET @InputParamQry='AccountNumber: '+''+@AccountNumber+''+'|'+
'@DocumentId: '+''+cast(@DocumentId as varchar(15))+''+'|'+
'@Allergiesdis: '+''+@allergiesdis+''+'|'+
'@Medicine: '+''+@medicine+''+'|'+
'@StartId: '+''+cast(@StartId as varchar(15))+''+'|'+
'@EndId: '+''+cast(@EndId as varchar(15))+''+'|'+
'@DocumentType: '+''+@DocumentType+''

declare @disorderId int  
declare @code1 varchar(10)
declare @dischdate datetime
set @dischdate = null
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try

        select @dischdate = isnull(DischargeDate,getdate()) from HIM_Visit where AccountNumber = @AccountNumber

        insert into NLP_Allergy(DocumentId,Content,Medicine,StartId,EndId)
        values(@DocumentId,@allergiesdis,@medicine,@StartId,@EndId)

       if exists(select top 1 Disorder from MasterHRCM.dbo.KB_AllergiesDxCode where Disorder =@medicine and [Status]=0)  
        Begin       
            select @disorderId = disorderid,@code1=Icdcode1 from MasterHRCM.dbo.KB_AllergiesDxCode ia
            inner join MasterHRCM.dbo.CMS_DxCodeDesc d on ia.IcdCode1 = d.ICD10Code 
            where Disorder =@medicine and ia.Status=0 and d.Status = 1
            and @dischdate between d.EffectiveYearFrom and d.EffectiveYearTo  

            insert into NLP_DxCodeByDocument (AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
            values(@AccountNumber,@DocumentId,@code1,@medicine,'Y','Positive','False','KPAI',0,@StartId,@EndId,0,'AllergiesDis','Y')

        End

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo @InputParamQry,'NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertCodableDxCodesFromAllDxCode

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertCodableDxCodesFromAllDxCode]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/19/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertCodableDxCodesFromAllDxCode] 
-- Add the parameters for the stored procedure here
@AccountNumber varchar(30), 
@DocumentId int,
@DocumentType varchar(20)
AS
declare @finding varchar(10)
declare @days int
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try

        if((@DocumentType = 'D') or (@DocumentType = 'T') or (@DocumentType = 'TS') or (@DocumentType = 'ESUMMARY'))
        set @finding ='None'
        else
        set @finding = 'Unknown'

        if exists (select 1 from FTP_IPMedication where AccountNumber = @AccountNumber and (medicationname like 'HEPATITIS B VIRUS VACCINE%' or medicationname like 'INFLUENZA VAC%' or medicationname like 'INFLUENZA VIRUS VAC%'))
        begin           
            if not exists (select 1 from NLP_DxCodeByDocument where AccountNumber = @AccountNumber and DxCode like 'Z23')
            insert into NLP_DxCodeByDocument(AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,StartId,EndId,DxCodeSource,Codable)
            values(@AccountNumber,@DocumentId,'Z23','Encounter For Immunization','Y','Positive','False','KPAI',0,0,0,'FTP_IPMedication','Y')
        end 
        if exists (select 1 from FTP_IPMedication where AccountNumber = @AccountNumber and (GenericName like'insulin%'))
        begin           
            if not exists (select 1 from NLP_DxCodeByDocument where AccountNumber = @AccountNumber and DxCode like 'Z79.4')
            insert into NLP_DxCodeByDocument(AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,StartId,EndId,DxCodeSource,Codable)
            values(@AccountNumber,@DocumentId,'Z79.4','Long term use of insulin','Y','Positive','False','KPAI',0,0,0,'FTP_IPMedication','Y')
        end 

        --Updating Codable to Y For PMH,CC and HPI based on Chronic Condition
        Update NLP_DxCodeByDocument set Codable='Y' from NLP_DxCodeByDocument dcb
        inner join MasterHRCM.dbo.CMS_DxCodeDesc dcdesc on dcdesc.ICD10Code=dcb.DxCode
        where DocumentId=@DocumentId and dcb.Codable='N' and dcb.DxCode is not null and dcb.DxCode!='Unknown'
        and dcdesc.Chronic=1 and dcdesc.Status=1

        select distinct DocumentId,DxCode,RStatus,DxCodeSource into #tdis from NLP_DxCodeByDocument 
        where DocumentId=@DocumentId and Codable='Y' and DxCode is not null and DxCode!='unknown' and finding in('positive',@finding)
        group by DocumentId,DxCode,RStatus,DxCodeSource

        --Checking Code is Negative
        update #tdis set RStatus = 10 where DxCode in(select DxCode from NLP_DxCodeByDocument where AccountNumber = @AccountNumber 
        and Finding = 'Negative' and DxCode is not null and DxCode!='unknown' group by DxCode having count(*)>2)

        select @days=DATEDIFF(DAY,p.DOB,v.AdmitDate) from HIM_Visit v inner join HIM_Patient p on v.PatientID=p.PatientId
        where v.AccountNumber=@AccountNumber        

        if (@days != 0)
        Update NLP_DxCodeByDocument set RStatus=2,DxCodeSource='NeonatalPdxNeg' where AccountNumber=@AccountNumber
        and DxCode like 'Z38.0%'

        --Insertion to NLP_DxCode(ICD10ICDPriority)
        insert into NLP_DxCode(AccountNumber,DocumentId,DxCode,DxDesc,Poa,DxType,DxPriority,CcMcc,PhysicianId,DxDate,UserName,Source)
        select @AccountNumber,@DocumentId,DxCode,NULL as DxDesc,'Y','S',0,NULL as CcMcc,hd.PhysicianID ,hd.EditDateTime,'KPAI',DxCodeSource
        from #tdis td inner join HIM_Document hd on td.DocumentId=hd.DocumentID
        where DxCode not in (select DxCode from NLP_DxCode where AccountNumber=@AccountNumber) 
        and RStatus not in (2,10)

        drop table #tdis

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo '<Input-Params>','NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertDirectPCS

Description:

Schema:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertDirectPCS]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 05/17/2018
-- Description: To insert Procedure code into NLP_PcsCodeByDocument by using the all standard PCS Terms.
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertDirectPCS] 
    @accountnumber  varchar(30),   
    @documentId int,  
    @section    varchar(100),
    @bodySystem varchar(100),
    @operation varchar(100),  
    @bodyPart varchar(100),  
    @approach varchar(100),  
    @device varchar(100),   
    @qualifier varchar(100),  
    @userName varchar(50),
    @docOperation varchar(100),
    @docBodyPart varchar(100),
    @docDevice varchar(100),
    @docQualifier varchar(100),
    @opStartPos int,
    @opEndPos int,
    @bpStartPos int,
    @bpEndPos int,
    @devStartPos int,
    @devEndPos int,
    @quaStartPos int,
    @quaEndPos int,
    @finalCode varchar(20),
    @sectionHeader varchar(20),
    @finding varchar(20),
    @history varchar(20),
    @docApproach varchar(100),
    @approachStartPos int,
    @approachEndPos int
AS
DECLARE @code VARCHAR(10)
BEGIN
    SET NOCOUNT ON;
    Begin Try

    if(@finalCode='')
    begin
        SELECT @code = Code from MedmineMaster.dbo.pcstabular where [section]=@section and bodysystem=@bodySystem and operation=@operation and bodypart=@bodyPart 
        and approach=@approach and device=@device and qualifier=@qualifier  
    end
    else
        begin
           set @code = @finalCode
        end

    INSERT INTO dbo.NLP_PcsCodeByDocument (AccountNumber,documentId,PcsCode,PcsDesc,PhysicianID,PcsDate,UserName,SectionHeader,Finding,History)
    VALUES(@accountnumber,@documentId,@code,@docOperation,null,null,@userName,@sectionHeader,@finding,@history)

    if(@code is not null)
    begin

    INSERT INTO dbo.NLP_PcsCodeEvidance (AccountNumber,documentId,PcsCode,PcsTerm,PcsType,StartId,EndId,UserName)
    VALUES(@accountnumber,@documentId,@code,@docOperation,'Operation',@opStartPos,@opEndPos,@userName)

    INSERT INTO dbo.NLP_PcsCodeEvidance (AccountNumber,documentId,PcsCode,PcsTerm,PcsType,StartId,EndId,UserName)
    VALUES(@accountnumber,@documentId,@code,@docBodyPart,'BodyPart',@bpStartPos,@bpEndPos,@userName)

    if(@docDevice !='')
    begin

    INSERT INTO dbo.NLP_PcsCodeEvidance (AccountNumber,documentId,PcsCode,PcsTerm,PcsType,StartId,EndId,UserName)
    VALUES(@accountnumber,@documentId,@code,@docDevice,'Device',@devStartPos,@devEndPos,@userName)

    end 

    if(@docQualifier !='')
    begin

    INSERT INTO dbo.NLP_PcsCodeEvidance (AccountNumber,documentId,PcsCode,PcsTerm,PcsType,StartId,EndId,UserName)
    VALUES(@accountnumber,@documentId,@code,@docQualifier,'Qualifier',@quaStartPos,@quaEndPos,@userName)

    end 

    if(@docApproach !='')
    begin

    INSERT INTO dbo.NLP_PcsCodeEvidance (AccountNumber,documentId,PcsCode,PcsTerm,PcsType,StartId,EndId,UserName)
    VALUES(@accountnumber,@documentId,@code,@docApproach,'Approach',@approachStartPos,@approachEndPos,@userName)

    end 

    end 

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo '<Input-Params>','<Source-AppName>'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertDrugDxCombination

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertDrugDxCombination]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/06/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertDrugDxCombination] 
    -- Add the parameters for the stored procedure here
@AccountNumber varchar(30),
@DocumentId INT,
@DocumentType varchar(20),
@disorder VARCHAR(100),
@drug VARCHAR(100),
@disstartId int,
@disendId int,
@DrugStartId int,
@DrugEndId int,
@SectionHeader varchar(200)
AS
Declare @InputParamQry varchar(500)
SET @InputParamQry='AccountNumber: '+''+@AccountNumber+''+'|'+
'@DocumentID: '+''+cast(@DocumentID as varchar(15))+''+'|'+
'@DocumentType: '+''+@DocumentType+''+'|'+
'@Disorder: '+''+@disorder+''+'|'+
'@Drug: '+''+@drug+''+'|'+
'@DisstartId: '+''+cast(@disstartId as varchar(15))+''+'|'+
'@DisendId: '+''+cast(@disendId as varchar(15))+''+'|'+
'@DrugStartId: '+''+cast(@DrugStartId as varchar(15))+''+'|'+
'@DrugEndId: '+''+cast(@DrugEndId as varchar(15))+''+'|'+
'@SectionHeader: '+''+@SectionHeader+''

DECLARE @disorderid as INT
DECLARE @icdcode as VARCHAR(20)
DECLARE @disordername as VARCHAR(400)
declare @code1 as varchar(20)
declare @dischdate datetime

set @dischdate=null

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

        select @dischdate = isnull(DischargeDate,getdate()) from HIM_Visit where AccountNumber = @AccountNumber

        select @disorderid=DisorderId,@disordername=Disorder from MasterHRCM.dbo.KB_Disorder where Disorder=@disorder

        select @icdcode=icdcode4 from MasterHRCM.dbo.KB_DxCode ic
        inner join MasterHRCM.dbo.CMS_DxCodeDesc d on ic.Icdcode4 = d.ICD10Code
        where DisorderId=@disorderid and causeid=0 and siteid=0 
        and site1id=0 and site2id=0 and ManifestationId = 0 and stage = 9 and temporalconcept1 = 9
        and temporalconcept2 = 0 and history='false' and neonatal = 0 and ic.Status not in (1) and d.Status = 1
        and @dischdate between d.EffectiveYearFrom and d.EffectiveYearTo

        insert into NLP_DxCodeByDocument (AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
        values(@AccountNumber,@DocumentId,@icdcode,@disordername,'Y','Positive','False','KPAI',0,@disstartId,@disendId,0,'DrugDxCombination','Y')

        select @code1=Code from MasterHRCM.dbo.CMS_DrugDxCode where MainTerm=@drug and DrugType='Adverseeffect' and Level=0 and Code not like '--'

        insert into NLP_DxCodeByDocument (AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
        values(@AccountNumber,@DocumentId,@code1+'A',@drug,'Y','Positive','False','KPAI',0,@DrugStartId,@DrugEndId,0,'DrugDxCombination','Y')

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo @InputParamQry,'NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertDrugEffectData

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertDrugEffectData]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/06/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertDrugEffectData] 
    -- Add the parameters for the stored procedure here
    @AccountNumber varchar(30),
    @DocumentId int,
    @drugdose varchar(200),
    @drugcause varchar(200), 
    @drugname varchar(200),
    @docname varchar(10),
    @encounter varchar(200) 
AS
Declare @InputParamQry varchar(500)
SET @InputParamQry='@AccountNumber: '+''+@AccountNumber+''+'|'+
'@DocumentID: '+''+cast(@DocumentID as varchar(50))+''+'|'+
'@DrugDose: '+''+@drugdose+''+'|'+
'@DrugCause: '+''+@drugcause+''+'|'+
'@DrugName: '+''+@drugname+''+'|'+
'@DocName: '+''+@docname+''+'|'+
'@Encounter: '+''+@encounter+''

declare @code1 as varchar(15)
declare @priority as int
declare @tmpIntId as int
declare @code as varchar(50)
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try

    if exists(select Code from MasterHRCM.dbo.CMS_DrugDxCode where MainTerm=@drugname and DrugType=@drugcause and Level=0)
    Begin
        select @code1=Code from MasterHRCM.dbo.CMS_DrugDxCode where MainTerm=@drugname and DrugType=@drugcause and Level=0       
        if(@code1 is not null)
        Begin
            if not exists (
                select top 1 AccountNumber from NLP_DxCodeByDocument where AccountNumber = @AccountNumber and DxCode= @code1 and 
                Finding = 'Positive'
                )
            Begin               
                insert into NLP_DxCodeByDocument (AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
                values(@AccountNumber,@DocumentId,@code1+'A',@drugdose+' of '+@drugname+' '+@drugcause,'Y','Positive','False','KPAI',0,0,0,0,'DrugEffect','Y')
            End
        End     

    End
    else if(@drugname = 'unspecified substance' and @drugcause = 'Poisoning_Intentional')
    Begin
            if(@encounter = 'subsequent')           
            set @code = 'T65.92XD'          
            else
            set @code = 'T65.92XA'            
    End

    if(@code is not null)
    Begin
        if not exists (select top 1 AccountNumber from NLP_DxCodeByDocument where AccountNumber = @AccountNumber and
        DxCode = @code1 and Finding = 'Positive')
        Begin           
            insert into NLP_DxCodeByDocument (AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
            values(@AccountNumber,@DocumentId,@code,'Toxic effect of unspecified substance','Y','Positive','False','KPAI',0,0,0,0,'DrugEffect','Y')
        End
    End 

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo @InputParamQry,'NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertDxAnnotationByDocument

Description:

Schema:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertDxAnnotationByDocument]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 05/24/2018
-- Description: InsertingDxAnnotationFromDocument
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertDxAnnotationByDocument] 
    -- Add the parameters for the stored procedure here
@Disorder varchar(100),
@Cause varchar(100),
@Site varchar(100),
@Site1 varchar(100),
@Site2 varchar(100),
@Manifestation varchar(100),
@Type varchar(100),
@AnnotId int,
@DocumentId int,
@Content varchar(5000),
@Stage varchar(20),
@TConcept1 varchar(50),
@TConcept2 varchar(50),
@Finding varchar(50),
@History varchar(50),
@StartId int,
@EndId int,
@RuleName varchar(50),
@AccountNumber varchar(20),
@DocumentType varchar(20),
@Neonatal tinyint,
@Gender tinyint,
@SectionHeader varchar(200),
@Codable varchar(2)
AS
declare @Code1 varchar(20)
declare @Code2 varchar(20)
declare @Code3 varchar(20)
declare @DisorderId int
declare @CauseId int
declare @SiteId int
declare @Site1Id int
declare @Site2Id int
declare @ManifestationId int
declare @TConcept1Id int
declare @TConcept2Id int
declare @StageId int
declare @TypeId int
declare @NCauseId int
declare @Dischdate datetime
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try

        set @code1 = null
        set @code2 = null
        set @code3 = null
        set @causeId = null
        set @siteid = null
        set @site1Id = null
        set @site2Id = null
        set @manifestationId = null
        set @tconcept1Id=null
        set @tconcept2Id=null
        set @stageId=null
        set @typeId=null
        set @NCauseId=null
        set @dischdate=null

        insert into NLP_DxAnnotation (AnnotationId,AccountNumber,DocumentId,Disorder,Cause,Manifestation,Site,Site1,Site2,TConcept1,TConcept2,Type,Stage)
        values(@annotId,@AccountNumber,@DocumentId,@disorder,@cause,@manifestation,@site,@site1,@site2,@tconcept1,@tconcept2,@type,@stage)

        --Max Combination Query i.e cause and site and manifestation
        Select top 1 @disorderId = disorderid from MasterHRCM.dbo.KB_Disorder where disorder=@disorder and Status=0     
        Select top 1 @typeId = TypeId from MasterHRCM.dbo.KB_Type where Type=@type and Status=0 

        if (@typeId!=13 and not exists( select 1 from MasterHRCM.dbo.KB_DxCode where DisorderId = @disorderId and Status !=1 and Type=@typeId))     
        set @typeId=13

        select @dischdate = isnull(DischargeDate,getdate()) from HIM_Visit where AccountNumber = @AccountNumber     

        select ic.* into #DisIcds from MasterHRCM.dbo.KB_DxCode ic
        inner join MasterHRCM.dbo.CMS_DxCodeDesc d on ic.Icdcode4 = d.ICD10Code
        where DisorderId = @disorderId and ic.Status not in (1) and d.Status = 1
        and Neonatal = @Neonatal and Gender in(0, @Gender) and Type=@typeId and history=@history
        and @dischdate between d.EffectiveYearFrom and d.EffectiveYearTo

        Select top 1 @causeId = i.CauseId from MasterHRCM.dbo.KB_Cause i
        inner join #DisIcds d on i.CauseId = d.causeid where cause=ISNULL(@cause,'Blank') and i.Status=0-- and d.status!=1
        Select top 1 @siteId = s.SiteId from MasterHRCM.dbo.KB_Site s
        inner join #DisIcds d on s.siteid = d.siteid  where site=ISNULL(@site,'Blank') and s.Status=0-- and d.status!=1
        Select top 1 @site1Id = s1.Site1Id from MasterHRCM.dbo.KB_Site1 s1
        inner join #DisIcds d on s1.Site1Id = d.site1id  where Site=ISNULL(@site1,'Blank') and s1.Status=0-- and d.status!=1
        Select top 1 @site2Id = s2.Site2Id from MasterHRCM.dbo.KB_Site2 s2
        inner join #DisIcds d on s2.Site2Id = d.site2id  where Site=ISNULL(@site2,'Blank') and s2.Status=0-- and d.status!=1
        Select top 1 @manifestationId = ManifestationId from MasterHRCM.dbo.KB_Manifestation where manifestation=ISNULL(@manifestation,'Blank') and Status=0    
        select @stageId=stage from #DisIcds where stage=@stage  
        Select top 1 @tconcept1Id = t1.TConcept1Id from MasterHRCM.dbo.KB_TemporalConcept1 t1
        inner join #DisIcds d on t1.TConcept1Id = d.temporalconcept1   where tconcept1=@tconcept1  and t1.Status=0-- and d.status!=1    
        Select top 1 @tconcept2Id = t2.TConcept2Id from MasterHRCM.dbo.KB_TemporalConcept2 t2
        inner join #DisIcds d on t2.TConcept2Id = d.temporalconcept2  where TConcept2=ISNULL(@tconcept2,'Blank') and t2.Status=0-- and d.status!=1

        -- Need to check gender and nenonatal here
        --DisorderId gets NULL what will happen?
        if (@causeId is null)
        set @causeId = 0

        if(@siteId is null)
        set @siteId = 0

        if(@site1Id is null)
        set @site1Id = 0

        if(@site2Id is null)
        set @site2Id = 0

        if(@stageId is null)
        set @stage = 9

        if(@manifestationId is null)
        set @manifestationId = 0

        if (@tconcept1Id is null)
        set @tconcept1Id = 9 

        if (@tconcept2Id is null)
        set @tconcept2Id = 0 

        select top 1 @code1=icdcode4,@code2=icdcode5,@code3=icdcode6 from #DisIcds 
        where Disorderid=@disorderId and causeid=@causeId and siteid=@siteId 
        and site1id=@site1Id and site2id=@site2Id and 
        ManifestationId = @manifestationId and stage = @stage and 
        temporalconcept1 = @tconcept1Id and temporalconcept2 = @tconcept2Id

        if(@Code1 is not null)
        exec NLP_InsertDxCodeEvidence @AccountNumber,@DocumentId,@code1,@Disorder,@Cause,@Site,@Site1,@Site2,@Manifestation,@Content,@StartId,@EndId


        if(@code1 is null and @siteId!=0)   --site Only
        begin
            print 's and s1- and s2'                                        
            select top 1 @code1=icdcode4,@code2=icdcode5,@code3=icdcode6 from #DisIcds 
            where Disorderid=@disorderId and causeid=0 and siteid=ISNULL(@siteId,0) 
            and site1id=0 and site2id=ISNULL(@site2Id,0) and ManifestationId = ISNULL(@manifestationId,0)
            and stage=@stage and TemporalConcept1=@tconcept1Id and temporalconcept2=ISNULL(@tconcept2Id,0)

            if(@Code1 is not null)
            exec NLP_InsertDxCodeEvidence @AccountNumber,@DocumentId,@code1,@Disorder,@Cause,@Site,@Site1,@Site2,@Manifestation,@Content,@StartId,@EndId

            --NLP_insertDxCodeEvidance                      
            if(@code1 is null)
            begin
                print 's and s1- and s2-'   
                select top 1 @code1=icdcode4,@code2=icdcode5,@code3=icdcode6 from #DisIcds 
                where Disorderid=@disorderId and causeid=0 and siteid=ISNULL(@siteId,0) and site1id=0
                and site2id=0 and ManifestationId = ISNULL(@manifestationId,0) and stage=@stage 
                and TemporalConcept1=@tconcept1Id and temporalconcept2=ISNULL(@tconcept2Id,0)

                if(@Code1 is not null)
                exec NLP_InsertDxCodeEvidence @AccountNumber,@DocumentId,@code1,@Disorder,@Cause,@Site,@Site1,@Site2,@Manifestation,@Content,@StartId,@EndId
            end
        end 

        if(@code1 is null)  --disorder Only
        begin
                print 'D'                                                               
                select top 1 @code1=icdcode4,@code2=icdcode5,@code3=icdcode6 from #DisIcds 
                where Disorderid=@disorderId and causeid=0 and SiteId=0 and Site1Id=0 and Site2Id=0 
                and ManifestationId=0 and stage=@stage and TemporalConcept1=@tconcept1Id 
                and temporalconcept2=0 

                if(@Code1 is not null)
                exec NLP_InsertDxCodeEvidence @AccountNumber,@DocumentId,@code1,@Disorder,@Cause,@Site,@Site1,@Site2,@Manifestation,@Content,@StartId,@EndId

                --StartHere                                         
            if(@code1 is not null and @manifestationId!=0)
            begin                        
                 declare @mstartId int
                 declare @mendId int
                 declare @mcode1 varchar(50)
                 declare @mcode2 varchar(50)
                 declare @mcode3 varchar(50)
                 declare @manfestDisId int
                 declare @indexId int
                 declare @DisIndexId int


                 Select top 1 @manfestDisId = disorderid from MasterHRCM.dbo.KB_Disorder where disorder=@manifestation and Status=0

                 select top 1 @mcode1=icdcode4,@mcode2=IcdCode5,@mcode3=IcdCode6 from MasterHRCM.dbo.KB_DxCode ic
                 inner join MasterHRCM.dbo.CMS_DxCodeDesc d on ic.Icdcode4 = d.ICD10Code
                 where DisorderId=@manfestDisId and CauseId=0 and SiteId=0 and Site1Id=0 and Site2Id=0 and 
                 ManifestationId=0 and stage=@stage and type=@typeId and temporalconcept1=@tconcept1Id 
                 and temporalconcept2=0 and ic.Status != 1 and d.Status = 1 and history=@history 
                 and neonatal=@Neonatal and @dischdate between d.EffectiveYearFrom and d.EffectiveYearTo 

                    if(@mcode1 is not null)
                    begin                        
                        select @indexId=CHARINDEX(@manifestation, @content)
                        select @DisIndexId=CHARINDEX(@disorder, @content)
                        set @mstartId=@startId+@indexId
                        set @mendId = @mstartId+LEN(@manifestation)
                        set @endId=@startId+@DisIndexId+LEN(@disorder)                                                                      

                        ---Insereting Manifestattion as DisorderId in Tempdisease
                        print 'Manifestation as Disorder'                           
                        insert into NLP_DxCodeByDocument (AccountNumber, DocumentId, DxCode, AnnotationString,Poa,SectionHeader,Finding,History,UserName,AnnotationId,StartId, EndId,Rstatus,DxCodeSource,Codable)
                        values(@AccountNumber,@DocumentId,@mcode1,@manifestation,'Y',@sectionHeader,@finding,@history,'KPAI',@annotId,@mstartId,@mendId,0,@ruleName,@Codable)                                   

                        exec NLP_InsertDxCodeEvidence @AccountNumber,@DocumentId,@mcode1,@Disorder,@Cause,@Site,@Site1,@Site2,@Manifestation,@Content,@StartId,@EndId

                        if(@mcode2 is not null and @mcode2!='')
                        begin
                        insert into NLP_DxCodeByDocument (AccountNumber, DocumentId, DxCode, AnnotationString,Poa,SectionHeader,Finding,History,UserName,AnnotationId,StartId, EndId,Rstatus,DxCodeSource,Codable)
                        values(@AccountNumber,@DocumentId,@mcode2,@manifestation,'Y',@sectionHeader,@finding,@history,'KPAI',@annotId,@mstartId,@mendId,0,@ruleName,@Codable)

                        exec NLP_InsertDxCodeEvidence @AccountNumber,@DocumentId,@mcode2,@Disorder,@Cause,@Site,@Site1,@Site2,@Manifestation,@Content,@StartId,@EndId
                        end
                    end
            end                 
        end

    if (@disorderid is null)
    begin
        print 'Entry in disorder table only'
        select top 1 @disorderId=disorderid from MasterHRCM.dbo.KB_Disorder where disorder=@disorder
        insert into NLP_DxCodeByDocument (AccountNumber, DocumentId, DxCode, AnnotationString,Poa,SectionHeader,Finding,History,UserName,AnnotationId,StartId, EndId,Rstatus,DxCodeSource,Codable)
        values(@AccountNumber,@DocumentId,'unknown',@content,'Y',@sectionHeader,@finding,@history,'KPAI',@annotId,@startId,@endId,0,@ruleName,@Codable)     
    end
    else
    if(@code1 is not null and @code1!='')
    begin
        print 'Disorder id existed in icdcode1'
        insert into NLP_DxCodeByDocument (AccountNumber, DocumentId, DxCode, AnnotationString,Poa,SectionHeader,Finding,History,UserName,AnnotationId,StartId, EndId,Rstatus,DxCodeSource,Codable)
        values(@AccountNumber,@DocumentId,@code1,@content,'Y',@sectionHeader,@finding,@history,'KPAI',@annotId,@startId,@endId,0,@ruleName,@Codable)

        exec NLP_InsertDxCodeEvidence @AccountNumber,@DocumentId,@code1,@Disorder,@Cause,@Site,@Site1,@Site2,@Manifestation,@Content,@StartId,@EndId
    end

    if(@code2 is not null and @code2!='')       
    begin           
        insert into NLP_DxCodeByDocument (AccountNumber, DocumentId, DxCode, AnnotationString,Poa,SectionHeader,Finding,History,UserName,AnnotationId,StartId, EndId,Rstatus,DxCodeSource,Codable)
        values(@AccountNumber,@DocumentId,@code2,@content,'Y',@sectionHeader,@finding,@history,'KPAI',@annotId,@startId,@endId,0,@ruleName,@Codable)

        exec NLP_InsertDxCodeEvidence @AccountNumber,@DocumentId,@code2,@Disorder,@Cause,@Site,@Site1,@Site2,@Manifestation,@Content,@StartId,@EndId
    end                             

    drop table #DisIcds 

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo '<Input-Params>','NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertDxCodeByCodeCombination

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertDxCodeByCodeCombination]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/19/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertDxCodeByCodeCombination] 
-- Add the parameters for the stored procedure here
@AccountNumber varchar(30),
@DocumentId int,
@DocumentType varchar(20)
AS
declare @ipcount int
declare @priority int
declare @tmpIntId int
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try

        declare Patients cursor for
        select count(distinct ip.DxCode) as dxcount,dx.dxcomb,dx.count,dx.DisorderId,dx.Content,dx.groupid 
        from NLP_DxCode ip 
        inner join MasterHRCM.dbo.KB_DxCodeCombination dx on ip.DxCode = dx.dx
        where ip.AccountNumber =@AccountNumber and 
        dx.dxcomb not in(select distinct DxCode from NLP_DxCode where AccountNumber=@AccountNumber and ip.DxExclusionTypeId in (0,2,3,4))
        and ip.DxExclusionTypeId in (0,2,3,4)
        group by dx.dxcomb,dx.count,dx.DisorderId,dx.Content,dx.groupid

        declare @dxcomb varchar(10)
        declare @dxcount int
        declare @dxCombCount int
        declare @DisorderId int             
        declare @Content varchar(100)
        declare @dxgroupId int
        open Patients
        fetch next from Patients into @dxcount,@dxcomb,@dxCombCount,@DisorderId,@Content,@dxgroupId
        while (@@fetch_Status<>-1)
        begin
            if(@dxcount=@dxCombCount)
            begin           
                --Insertion to NLP_DxCode(ICD10ICDPriority)
                insert into NLP_DxCode(AccountNumber,DocumentId,DxCode,DxDesc,Poa,DxType,DxPriority,CcMcc,PhysicianId,DxDate,UserName,Source)   
                select @AccountNumber,@DocumentId,@dxcomb,NULL as DxDesc,'Y','S',0,NULL as CcMcc,PhysicianID,EditDateTime,
                'KPAI','DxCodeByCodeCombination' from HIM_Document where DocumentID=@DocumentId

                /*Inserting dxcombo log*/               
                insert into NLP_DxCodeCombination(AccountNumber,CombinationCode,RootCode,CombinationType)
                select distinct ip.AccountNumber,id.dxcomb,id.dx,'Combo' 
                from NLP_DxCode ip              
                inner join MasterHRCM.dbo.KB_DxCodeCombination id on id.dx = ip.DxCode
                where ip.AccountNumber = @AccountNumber and id.dxcomb = @dxcomb
            end
            fetch next from Patients into @dxcount,@dxcomb,@dxCombCount,@DisorderId,@Content,@dxgroupId
        end
        close Patients
        deallocate Patients

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo '<Input-Params>','NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertDxCodeByPcsCode

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertDxCodeByPcsCode]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/20/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertDxCodeByPcsCode] 
    -- Add the parameters for the stored procedure here
@AccountNumber varchar(30),
@DocumentId int,
@DocumentType varchar(20)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try

        declare ProcedureIcdCodes cursor for 
        select distinct PCSCode from dbo.NLP_PCSCode where AccountNumber=@AccountNumber and RStatus=0
        declare @code1 varchar(20)
        open ProcedureIcdCodes
        fetch next from ProcedureIcdCodes into @code1
        while (@@fetch_Status<>-1)
        begin
            select pcscode,PastCode into #temp from MasterHRCM.dbo.MST_ProcedureStatus where PCSCode=@code1 

            if not exists(select 1 from NLP_DxCodeByDocument where AccountNumber = @AccountNumber and 
            DxCode in (select PastCode from #temp ) and (@DocumentType='ERR' or @DocumentType='H' or @DocumentType='C'))
            begin           
                update NLP_DxCode set DxExclusionTypeId = 4 where AccountNumber=@AccountNumber 
                and DxCode in (select PastCode from #temp)and DxExclusionTypeId = 0
            end 
            drop table #temp
            fetch next from ProcedureIcdCodes into @code1
        end
        close ProcedureIcdCodes
        deallocate ProcedureIcdCodes

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo '<Input-Params>','NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertDxCodeEvidence

Description:

Schema:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertDxCodeEvidence]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 05/25/2018
-- Description: InsertDxCodeEvidence
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertDxCodeEvidence] 
@AccountNumber varchar(20),
@DocumentId int,
@DxCode varchar(20),
@Disorder varchar(100),
@Cause varchar(100),
@Site varchar(100),
@Site1 varchar(100),
@Site2 varchar(100),
@Manifestation varchar(100),
@Content varchar(5000),
@StartId int,
@EndId int
AS
Declare @InputParamQry varchar(500)
SET @InputParamQry='AccountNumber: '+''+@AccountNumber+''+'|'+
'DocumentID: '+''+cast(@DocumentID as varchar(50))+''+'|'+
'@DxCode: '+''+@DxCode+''+'|'+
'@Disorder: '+''+@Disorder+''+'|'+
'@Cause: '+''+@Cause+''+'|'+
'@Site: '+''+@Site+''+'|'+
'@Site1: '+''+@Site1+''+'|'+
'@Site2: '+''+@Site2+''+'|'+
'@Manifestation: '+''+@Manifestation+''+'|'+
'@Content: '+''+@Content+''+'|'+
'@StartId: '+''+cast(@StartId as varchar(15))+''+'|'+
'@EndId: '+''+cast(@EndId as varchar(15))+''

    declare @DisIndexId int
    declare @DisStartId int
    declare @DisEndId int
    declare @SiteIndexId int
    declare @SiteStartId int
    declare @SiteEndId int
    declare @Site1IndexId int
    declare @Site1StartId int
    declare @Site1EndId int
    declare @Site2IndexId int
    declare @Site2StartId int
    declare @Site2EndId int
    declare @ManifestationIndexId int
    declare @ManifestationStartId int
    declare @ManifestationEndId int
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try

        select @DisIndexId=CHARINDEX(@Disorder, @Content)
        set @DisStartId=@StartId+@DisIndexId
        set @DisEndId = @DisStartId+LEN(@Disorder)

        INSERT INTO NLP_DxCodeEvidence(AccountNumber,DocumentId,DxCode,AnnotationString,AnnotationType,StartId,EndId,UserName)
        values(@AccountNumber,@DocumentId,@DxCode,@Disorder,'Disease',@DisStartId,@DisEndId,'KPAI')

    if(@Site is not null)
    begin
        select @SiteIndexId=CHARINDEX(@Site, @Content)
        set @SiteStartId=@StartId+@SiteIndexId
        set @SiteEndId = @SiteStartId+LEN(@Site)

        INSERT INTO NLP_DxCodeEvidence(AccountNumber,DocumentId,DxCode,AnnotationString,AnnotationType,StartId,EndId,UserName)
        values(@AccountNumber,@DocumentId,@DxCode,@Site,'Site',@SiteStartId,@SiteEndId,'KPAI')  

    end

    if(@Site1 is not null)
    begin
        select @Site1IndexId=CHARINDEX(@Site1, @Content)
        set @Site1StartId=@StartId+@Site1IndexId
        set @Site1EndId = @Site1StartId+LEN(@Site1)

        INSERT INTO NLP_DxCodeEvidence(AccountNumber,DocumentId,DxCode,AnnotationString,AnnotationType,StartId,EndId,UserName)
        values(@AccountNumber,@DocumentId,@DxCode,@Site1,'Site1',@Site1StartId,@Site1EndId,'KPAI')  

    end

    if(@Site2 is not null)
    begin
        select @Site2IndexId=CHARINDEX(@Site2, @Content)
        set @Site2StartId=@StartId+@Site2IndexId
        set @Site2EndId = @Site2StartId+LEN(@Site2)

        INSERT INTO NLP_DxCodeEvidence(AccountNumber,DocumentId,DxCode,AnnotationString,AnnotationType,StartId,EndId,UserName)
        values(@AccountNumber,@DocumentId,@DxCode,@Site2,'Site2',@Site2StartId,@Site2EndId,'KPAI')  

    end

    if(@Manifestation is not null)
    begin
        select @ManifestationIndexId=CHARINDEX(@Manifestation, @Content)
        set @ManifestationStartId=@StartId+@ManifestationIndexId
        set @ManifestationEndId = @ManifestationStartId+LEN(@Manifestation)

        INSERT INTO NLP_DxCodeEvidence(AccountNumber,DocumentId,DxCode,AnnotationString,AnnotationType,StartId,EndId,UserName)
        values(@AccountNumber,@DocumentId,@DxCode,@Manifestation,'Manifestation',@ManifestationStartId,@ManifestationEndId,'KPAI')  

    end

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo @InputParamQry,'NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertDxKeywordCombination

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertDxKeywordCombination]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/06/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertDxKeywordCombination] 
@AccountNumber varchar(30),
@DocumentId int,
@keyword varchar(200),
@DocumentType varchar(20) 
AS
Declare @InputParamQry varchar(500)
SET @InputParamQry='AccountNumber: '+''+@AccountNumber+''+'|'+
'DocumentID: '+''+cast(@DocumentID as varchar(15))+''+'|'+
'@keyword: '+''+@keyword+''+'|'+
'@DocumentType: '+''+@DocumentType+''

declare @code1 as varchar(15)
declare @Tarcode as varchar(15)
declare @shortdesc as varchar(100)
declare @priority as int
declare @tmpIntId as int
declare @dischdate datetime
BEGIN
    set @dischdate=null
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try       
        select @dischdate = isnull(DischargeDate,getdate()) from HIM_Visit where AccountNumber = @AccountNumber         
        insert into NLP_DxFactor(AccountNumber,FactorName)values(@AccountNumber,@keyword)

        if exists(select top 1 DxCode from NLP_DxCodeByDocument where DxCode in (select distinct Icdcode from MasterHRCM.dbo.KB_DxFactorCombination) and AccountNumber=@AccountNumber and Finding='Positive')
        begin
            declare Patients cursor for     
            select distinct Dxcode from NLP_DxCodeByDocument where DxCode in (select distinct Icdcode from MasterHRCM.dbo.KB_DxFactorCombination) and AccountNumber=@AccountNumber and Finding='Positive'
            open Patients
            fetch next from Patients into @code1
            while (@@fetch_Status<>-1)
             begin
                if exists(select * from MasterHRCM.dbo.KB_DxFactorCombination where ICDCode=@code1 and FactorName=@keyword)
                begin
                    select @Tarcode=dc.TargetCode,@shortdesc=d.ShortDesc from MasterHRCM.dbo.KB_DxFactorCombination dc
                    inner join MasterHRCM.dbo.CMS_DxCodeDesc d on dc.TargetCode = d.ICD10Code
                    where dc.ICDCode=@code1 and FactorName=@keyword
                    and @dischdate between d.EffectiveYearFrom and d.EffectiveYearTo and d.Status = 1                   
                end 
                if(@Tarcode ! = null or @Tarcode ! = '')
                begin
                    if not exists (select top 1 AccountNumber from NLP_DxCodeByDocument where AccountNumber = @AccountNumber and DocumentId = @DocumentId and DxCode = @Tarcode)
                    begin                           
                        insert into NLP_DxCodeByDocument(AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
                        values(@AccountNumber,@DocumentId,@Tarcode,@shortdesc,'Y','Positive','False','KPAI',0,0,0,0,'DxKeyword','Y')
                    end             
                end
                fetch next from Patients into @code1                                

            end
            close Patients
            deallocate Patients     
        end 
    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo @InputParamQry,'NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertHabitDxData

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertHabitDxData]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/06/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertHabitDxData] 
@AccountNumber varchar(30),
@DocumentId int,
@HabitContent varchar(200),  
@HabitType varchar(50),  
@HabitCondition varchar(50),  
@History varchar(20),  
@Finding varchar(20),  
@StartId int,  
@EndId int,
@DocumentType varchar(20)  
AS
Declare @InputParamQry varchar(500)
SET @InputParamQry='AccountNumber: '+''+@AccountNumber+''+'|'+
'@DocumentId: '+''+cast(@DocumentId as varchar(15))+''+'|'+
'@HabitContent: '+''+@HabitContent+''+'|'+
'@HabitType: '+''+@HabitType+''+'|'+
'@HabitCondition: '+''+@HabitCondition+''+'|'+
'@History: '+''+@History+''+'|'+
'@Finding: '+''+@Finding+''+'|'+
'@StartId: '+''+cast(@StartId as varchar(15))+''+'|'+
'@EndId: '+''+cast(@EndId as varchar(15))+''+'|'+
'@DocumentType: '+''+@DocumentType+''

declare @disorderId int  
declare @code1 varchar(10)
declare @dischdate datetime 
BEGIN
    set @disorderId = 0  
    set @code1 = null
    set @dischdate=null    

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

        select @dischdate = isnull(DischargeDate,getdate()) from HIM_Visit where AccountNumber = @AccountNumber

        insert into NLP_Habit(DocumentId,Content,HabitType,Condition,History,Finding,StartId,EndId)
        values(@DocumentId,@HabitContent,@HabitType,@HabitCondition,@History,@Finding,@StartId,@EndId)

        if(@finding= 'Positive')
        begin  
            if(@habitContent is not null)  
            begin      
                select @disorderId = disorderid,@code1=Icdcode1 from MasterHRCM.dbo.KB_HabitsDxCode hi
                inner join MasterHRCM.dbo.CMS_DxCodeDesc d on hi.IcdCode1 = d.ICD10Code
                where Disorder =@habitContent and History = @history and hi.Status=0 and d.Status = 1
                and @dischdate between d.EffectiveYearFrom and d.EffectiveYearTo

               if(@disorderId !=0)  
               begin                            
                    insert into NLP_DxCodeByDocument (AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
                    values(@AccountNumber,@DocumentId,@code1,@HabitCondition,'Y',@Finding,@History,'KPAI',0,@StartId,@EndId,0,'HabitDis','Y')   
               end
            end             
            else  
            begin
                select @disorderId = disorderid,@code1=Icdcode1 from MasterHRCM.dbo.KB_HabitsDxCode hi
                inner join MasterHRCM.dbo.CMS_DxCodeDesc d on hi.IcdCode1 = d.ICD10Code
                where [Type] =@habitType and History = @history and hi.Status = 0 and d.Status = 1 and Disorder is null
                and @dischdate between d.EffectiveYearFrom and d.EffectiveYearTo

                if(@disorderId !=0)  
                begin                   
                    insert into NLP_DxCodeByDocument (AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
                    values(@AccountNumber,@DocumentId,@code1,@HabitType,'Y',@Finding,@History,'KPAI',0,@StartId,@EndId,0,'HabitDis','Y')
                end                     
            end
        end

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo @InputParamQry,'NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertLongTermDrugDxCode

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertLongTermDrugDxCode]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/18/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertLongTermDrugDxCode] 
    -- Add the parameters for the stored procedure here
@AccountNumber varchar(30),
@DocumentId int,
@DocumentType varchar(20)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try

        insert into NLP_DxCodeByDocument(AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,
        AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)        
        select distinct @AccountNumber,@DocumentId,ld.ICDCode,hm.HomeMedication,'Y','Positive','False','KPAI',0,hm.StartId,
        hm.EndId,0,'LongTermDrugDisease','Y' from CDA_HomeMedication hm 
        inner join MasterHRCM.dbo.KB_LongtermDrugDxCode ld on hm.HomeMedication = ld.DrugName
        where hm.AccountNumber = @AccountNumber and hm.DocumentID = @DocumentId 

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo '<Input-Params>','NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertObgAnnotationByDocument

Description:

Schema:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertObgAnnotationByDocument]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/06/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertObgAnnotationByDocument] 
@Disorder varchar(100),
@Cause varchar(100),
@Site varchar(100),
@Site1 varchar(100),
@Site2 varchar(100),
@Manifestation varchar(100),
@Type varchar(100),
@AnnotId int,
@DocumentId int,
@Content varchar(5000),
@Stage varchar(20),
@Tconcept1 varchar(50),
@Tconcept2 varchar(50),
@Finding varchar(50),
@History varchar(50),
@StartId int,
@EndId int,
@RuleName varchar(50),
@AccountNumber varchar(20),
@DocumentType varchar(20),
@Pstatus tinyint,
@Pstatus1 tinyint,
@Neonatal tinyint,
@Gender tinyint,
@SectionHeader varchar(200),
@Codable varchar(2)
AS
declare @code1 varchar(20)
declare @code2 varchar(20)
declare @code3 varchar(20)
declare @disorderId int
declare @disorderId1 int
declare @causeId int
declare @siteId int
declare @site1Id int
declare @site2Id int
declare @manifestationId int
declare @tconcept1Id int
declare @tconcept2Id int
declare @stageId int
declare @typeId int
declare @Trimester2 int
declare @Trimester1 int
declare @childbirth int
declare @trimtemp int
declare @deltemp int
declare @dischdate datetime
BEGIN
    set @code1 = null
    set @code2 = null
    set @code3 = null
    set @causeId = null
    set @siteid = null
    set @site1Id = null
    set @site2Id = null
    set @manifestationId = null
    set @tconcept1Id=null
    set @tconcept2Id=null
    set @stageId=null
    set @typeId=null
    set @dischdate=null
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try       
        insert into NLP_DxAnnotation (AnnotationId,AccountNumber,DocumentId,Disorder,Cause,Manifestation,Site,Site1,Site2,TConcept1,TConcept2,Type,Stage)
        values(@annotId,@AccountNumber,@DocumentId,@disorder,@cause,@manifestation,@site,@site1,@site2,@tconcept1,@tconcept2,@type,@stage)
        /*     
        if not exists(select top 1 1 from HIM_Visit where AccountNumber=@AccountNumber and PatientCTG='OBG')        
        update HIM_Visit set PatientCTG='OBG' where AccountNumber=@AccountNumber
        */
        --Max Combination Query i.e cause and site and manifestation
        Select top 1 @disorderId = disorderid from MasterHRCM.dbo.KB_ObgDisorder where disorder=@disorder and Status !=1
        Select top 1 @disorderId1 = disorderid from MasterHRCM.dbo.KB_Disorder where disorder=@disorder and Status !=1
        Select top 1 @typeId = TypeId from MasterHRCM.dbo.KB_Type where Type=@type and Status=0     
        select @dischdate = isnull(DischargeDate,getdate()) from HIM_Visit where AccountNumber = @AccountNumber

        select icd.* into #DisIcds from MasterHRCM.dbo.KB_ObgDxCode icd
        inner join MasterHRCM.dbo.CMS_DxCodeDesc d on icd.IcdCode1 = d.ICD10Code
        where DisorderId = @disorderId and icd.Status not in(1) and d.Status = 1
        and Type=@typeId and history=@history
        and @dischdate between d.EffectiveYearFrom and d.EffectiveYearTo        

        Select top 1 @causeId = i.CauseId from MasterHRCM.dbo.KB_Cause  i
        inner join #DisIcds d on i.CauseId = d.causeid where cause=ISNULL(@cause,'Blank') and i.Status=0 

        Select top 1 @siteId = s.SiteId from MasterHRCM.dbo.KB_Site s
        inner join #DisIcds d on s.siteid = d.siteid  where site=ISNULL(@site,'Blank') and s.Status=0-- and d.status!=1

        Select top 1 @site1Id = s1.Site1Id from MasterHRCM.dbo.KB_Site1 s1
        inner join #DisIcds d on s1.Site1Id = d.site1id  where Site=ISNULL(@site1,'Blank') and s1.Status=0-- and d.status!=1

        Select top 1 @site2Id = s2.Site2Id from MasterHRCM.dbo.KB_Site2 s2
        inner join #DisIcds d on s2.Site2Id = d.site2id  where Site=ISNULL(@site2,'Blank') and s2.Status=0-- and d.status!=1

        Select top 1 @manifestationId = m.ManifestationId from MasterHRCM.dbo.KB_Manifestation m
        inner join #DisIcds d on m.ManifestationId = d.ManifestationId  where manifestation=ISNULL(@manifestation,'Blank') and m.Status=0-- and d.status!=1

        select @stageId=stage from #DisIcds where stage=@stage

        Select top 1 @tconcept1Id = t1.TConcept1Id from MasterHRCM.dbo.KB_TemporalConcept1 t1
        inner join #DisIcds d on t1.TConcept1Id = d.temporalconcept1   where tconcept1=@tconcept1  and t1.Status=0-- and d.status!=1

        Select top 1 @tconcept2Id = t2.TConcept2Id from MasterHRCM.dbo.KB_TemporalConcept2 t2
        inner join #DisIcds d on t2.TConcept2Id = d.temporalconcept2  where TConcept2=ISNULL(@tconcept2,'Blank') and t2.Status=0-- and d.status!=1

        if (@causeId is null)
        set @causeId = 0

        if(@siteId is null)
        set @siteId = 0

        if(@site1Id is null)
        set @site1Id = 0

        if(@site2Id is null)
        set @site2Id = 0

        if(@manifestationId is null)
        set @manifestationId = 0

        if (@tconcept1Id is null)
        set @tconcept1Id = 9 

        if (@tconcept2Id is null)
        set @tconcept2Id = 0 

        if(@stageId is null)
        set @stage = 9

        if(@pstatus=4 or @pstatus=5)
        begin      
            select top 1 @code1=IcdCode1,@code2=IcdCode2,@code3=IcdCode3 from #DisIcds 
            where Disorderid=@disorderId and causeid=@causeId and siteid=@siteId and site1id=@site1Id 
            and site2id=@site2Id and ManifestationId = @manifestationId and stage = @stage 
            and temporalconcept1 = @tconcept1Id and temporalconcept2 = @tconcept2Id and Pstatus=@Pstatus

            if(@Code1 is not null)
            exec NLP_InsertDxCodeEvidence @AccountNumber,@DocumentId,@code1,@Disorder,@Cause,@Site,@Site1,@Site2,@Manifestation,@Content,@StartId,@EndId
        end

        if(@code1 is null or @code1='')
        begin
            --print 'code1 is null'
            select top 1 @code1=IcdCode1,@code2=IcdCode2,@code3=IcdCode3 from #DisIcds 
            where Disorderid=@disorderId and causeid=@causeId and siteid=@siteId 
            and site1id=@site1Id and site2id=@site2Id and 
            ManifestationId = @manifestationId and stage = @stage and 
            temporalconcept1 = @tconcept1Id and temporalconcept2 = @tconcept2Id and Pstatus=@Pstatus1

            if(@Code1 is not null)
            exec NLP_InsertDxCodeEvidence @AccountNumber,@DocumentId,@code1,@Disorder,@Cause,@Site,@Site1,@Site2,@Manifestation,@Content,@StartId,@EndId
        end

        if(@disorderid is null)
        begin
            print 'Entry in disorder table only'
            --select top 1 @disorderId=disorderid from MasterHRCM.dbo.KB_ObgDisorder where disorder=@disorder
            insert into NLP_DxCodeByDocument (AccountNumber,DocumentId,DxCode,AnnotationString,Poa,SectionHeader,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
            values(@AccountNumber,@DocumentId,'unknown',@Content,'Y',@SectionHeader,@Finding,@History,'KPAI',@AnnotId,@StartId,@EndId,0,@RuleName,@Codable)
        end
        else
        begin
            --print 'Disorder id existed in icdcode1'
            if(@code1 is not null and @code1!='')
            Begin
                insert into NLP_DxCodeByDocument (AccountNumber,DocumentId,DxCode,AnnotationString,Poa,SectionHeader,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
                values(@AccountNumber,@DocumentId,@code1,@Content,'Y',@SectionHeader,@Finding,@History,'KPAI',@AnnotId,@StartId,@EndId,0,@RuleName,@Codable)    
                exec NLP_InsertDxCodeEvidence @AccountNumber,@DocumentId,@code1,@Disorder,@Cause,@Site,@Site1,@Site2,@Manifestation,@Content,@StartId,@EndId
            End

            if(@code2 is not null and @code2!='')
            Begin
            insert into NLP_DxCodeByDocument (AccountNumber,DocumentId,DxCode,AnnotationString,Poa,SectionHeader,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
            values(@AccountNumber,@DocumentId,@code2,@Content,'Y',@SectionHeader,@Finding,@History,'KPAI',@AnnotId,@StartId,@EndId,0,@RuleName,@Codable)
            exec NLP_InsertDxCodeEvidence @AccountNumber,@DocumentId,@code2,@Disorder,@Cause,@Site,@Site1,@Site2,@Manifestation,@Content,@StartId,@EndId
            End
        end

        drop table #DisIcds 

        if(@code1 is not null and @code1!='')
        begin
            if(@Pstatus=4 or @Pstatus=5 )
            begin
                if not exists(select 1 from NLP_DxCodeByDocument where AccountNumber=@AccountNumber and DocumentId=@DocumentId and DxCode like 'Z37%')
                insert into NLP_DxCodeByDocument (AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
                values(@AccountNumber,@DocumentId,'Z37.0','Single Live Born','Y','Positive','False','KPAI',0,0,0,0,'OutcomeOfDelivery',@Codable)
            end         
        end
        else
        begin
            if exists(select * from MasterHRCM.dbo.KB_DxCode where DisorderId = @disorderId1 and Status not in(1)
            and Neonatal = @Neonatal and Gender in(0, @Gender) and Type=@typeId)
            exec NLP_InsertObgDxAnnotationByDocument @disorder,@cause,@site,@site1,@site2,@manifestation,@type,@annotId,@DocumentId,@content,@stage,@tconcept1,@tconcept2,@finding,@history,
            @startId,@endId,@ruleName,@AccountNumber,@DocumentType,@Neonatal,@Gender,@SectionHeader,@Pstatus,@Pstatus1,@Codable
        end

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo '<Input-Params>','NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertObgComplication

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertObgComplication]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/06/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertObgComplication] 
@Condition int,
@Condition2 int,
@AccountNumber varchar(30),
@DocumentId int,
@DocumentType varchar(20),
@IcdCode varchar(20)
AS
Declare @InputParamQry varchar(500)
SET @InputParamQry='AccountNumber: '+''+@AccountNumber+''+'|'+
'DocumentID: '+''+cast(@DocumentID as varchar(15))+''+'|'+
'@Condition: '+''+cast(@Condition as varchar(15))+''+'|'+
'@Condition2: '+''+cast(@Condition2 as varchar(15))+''+'|'+
'@DocumentType: '+''+@DocumentType+''+'|'+
'@IcdCode: '+''+@IcdCode+''

declare @obgCode varchar(30)
declare @content varchar(1000)
declare @history varchar(20)
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try
        if(@Condition=4 or @Condition=5)
        begin           
            if exists(select o.icd10code from MasterHRCM.dbo.KB_ObgInfectiousCrosswalk i
            inner join NLP_DxCodeByDocument t on i.icdcode = t.DxCode 
            inner join MasterHRCM.dbo.KB_ObgComplication o on i.obgcode=o.code
            where o.trimstatus =@Condition  and t.RStatus in (0,1,5) and t.DxCode=@icdcode)
            begin           
                select @obgCode = o.icd10code,@content = o.trimester,@history = t.history 
                from MasterHRCM.dbo.KB_ObgInfectiousCrosswalk i
                inner join NLP_DxCodeByDocument t on i.icdcode = t.DxCode and t.RStatus in(0,1,5)
                inner join MasterHRCM.dbo.KB_ObgComplication o on i.obgcode=o.code
                where o.trimstatus =@Condition and t.DxCode=@icdcode

                insert into NLP_DxCodeByDocument (AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
                values(@AccountNumber,@DocumentId,@obgCode,@content,'Y','Positive',@history,'KPAI',0,0,0,0,'obgcomplications','Y')
            end
        end
        else if exists(select o.icd10code from MasterHRCM.dbo.KB_ObgInfectiousCrosswalk i
                inner join NLP_DxCodeByDocument t on i.icdcode = t.DxCode
                inner join MasterHRCM.dbo.KB_ObgComplication o on i.obgcode=o.code
                where o.trimstatus =@Condition2 and t.RStatus in (0,1,5) and t.DxCode=@icdcode)
        begin
                select @obgCode = o.icd10code,@content = o.trimester,@history = t.history 
                from MasterHRCM.dbo.KB_ObgInfectiousCrosswalk i
                inner join NLP_DxCodeByDocument t on i.icdcode = t.DxCode 
                inner join MasterHRCM.dbo.KB_ObgComplication o on i.obgcode=o.code
                where o.trimstatus =@Condition2 and t.RStatus in(0,1,5) and t.DxCode=@icdcode

                insert into NLP_DxCodeByDocument (AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
                values(@AccountNumber,@DocumentId,@obgCode,@content,'Y','Positive',@history,'KPAI',0,0,0,0,'obgcomplications','Y')
        end
    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo @InputParamQry,'NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertObgDxAnnotationByDocument

Description:

Schema:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertObgDxAnnotationByDocument]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/06/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertObgDxAnnotationByDocument] 
@Disorder varchar(100),
@Cause varchar(100),
@Site varchar(100),
@Site1 varchar(100),
@Site2 varchar(100),
@Manifestation varchar(100),
@Type varchar(100),
@AnnotId int,
@DocumentId int,
@Content varchar(5000),
@Stage varchar(20),
@Tconcept1 varchar(50),
@Tconcept2 varchar(50),
@Finding varchar(50),
@History varchar(50),
@StartId int,
@EndId int,
@RuleName varchar(50),
@AccountNumber varchar(20),
@DocumentType varchar(20),
@Neonatal tinyint,
@Gender tinyint,
@SectionHeader varchar(200),
@Pstatus tinyint,
@Pstatus1 tinyint,
@Codable varchar(2)
AS
declare @code1 varchar(20)
declare @code2 varchar(20)
declare @code3 varchar(20)
declare @disorderId int
declare @causeId int
declare @siteId int
declare @site1Id int
declare @site2Id int
declare @manifestationId int
declare @tconcept1Id int
declare @tconcept2Id int
declare @stageId int
declare @typeId int
declare @NCauseId int
declare @dischdate datetime
BEGIN
    set @code1 = null
    set @code2 = null
    set @code3 = null
    set @causeId = null
    set @siteid = null
    set @site1Id = null
    set @site2Id = null
    set @manifestationId = null
    set @tconcept1Id=null
    set @tconcept2Id=null
    set @stageId=null
    set @typeId=null
    set @NCauseId=null
    set @dischdate=null
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try
        insert into NLP_DxAnnotation (AnnotationId,AccountNumber,DocumentId,Disorder,Cause,Manifestation,Site,Site1,Site2,TConcept1,TConcept2,Type,Stage)
        values(@annotId,@AccountNumber,@DocumentId,@disorder,@cause,@manifestation,@site,@site1,@site2,@tconcept1,@tconcept2,@type,@stage)

        --Max Combination Query i.e cause and site and manifestation
        Select top 1 @disorderId = disorderid from MasterHRCM.dbo.KB_Disorder where disorder=@disorder and Status=0     
        Select top 1 @typeId = TypeId from MasterHRCM.dbo.KB_Type where Type=@type and Status=0 

        if (@typeId!=13 and not exists( select 1 from MasterHRCM.dbo.KB_DxCode where DisorderId = @disorderId and Status !=1 and Type=@typeId))     
        set @typeId=13

        select @dischdate = isnull(DischargeDate,getdate()) from HIM_Visit where AccountNumber = @AccountNumber     

        select ic.* into #DisIcds from MasterHRCM.dbo.KB_DxCode ic
        inner join MasterHRCM.dbo.CMS_DxCodeDesc d on ic.Icdcode4 = d.ICD10Code
        where DisorderId = @disorderId and ic.Status not in (1) and d.Status = 1
        and Neonatal = @Neonatal and Gender in(0, @Gender) and Type=@typeId and history=@history
        and @dischdate between d.EffectiveYearFrom and d.EffectiveYearTo

        Select top 1 @causeId = i.CauseId from MasterHRCM.dbo.KB_Cause i
        inner join #DisIcds d on i.CauseId = d.causeid where cause=ISNULL(@cause,'Blank') and i.Status=0-- and d.status!=1
        Select top 1 @siteId = s.SiteId from MasterHRCM.dbo.KB_Site s
        inner join #DisIcds d on s.siteid = d.siteid  where site=ISNULL(@site,'Blank') and s.Status=0-- and d.status!=1
        Select top 1 @site1Id = s1.Site1Id from MasterHRCM.dbo.KB_Site1 s1
        inner join #DisIcds d on s1.Site1Id = d.site1id  where Site=ISNULL(@site1,'Blank') and s1.Status=0-- and d.status!=1
        Select top 1 @site2Id = s2.Site2Id from MasterHRCM.dbo.KB_Site2 s2
        inner join #DisIcds d on s2.Site2Id = d.site2id  where Site=ISNULL(@site2,'Blank') and s2.Status=0-- and d.status!=1
        Select top 1 @manifestationId = ManifestationId from MasterHRCM.dbo.KB_Manifestation where manifestation=ISNULL(@manifestation,'Blank') and Status=0    
        select @stageId=stage from #DisIcds where stage=@stage  
        Select top 1 @tconcept1Id = t1.TConcept1Id from MasterHRCM.dbo.KB_TemporalConcept1 t1
        inner join #DisIcds d on t1.TConcept1Id = d.temporalconcept1   where tconcept1=@tconcept1  and t1.Status=0-- and d.status!=1    
        Select top 1 @tconcept2Id = t2.TConcept2Id from MasterHRCM.dbo.KB_TemporalConcept2 t2
        inner join #DisIcds d on t2.TConcept2Id = d.temporalconcept2  where TConcept2=ISNULL(@tconcept2,'Blank') and t2.Status=0-- and d.status!=1

        -- Need to check gender and nenonatal here
        --DisorderId gets NULL what will happen?
        if (@causeId is null)
        set @causeId = 0

        if(@siteId is null)
        set @siteId = 0

        if(@site1Id is null)
        set @site1Id = 0

        if(@site2Id is null)
        set @site2Id = 0

        if(@stageId is null)
        set @stage = 9

        if(@manifestationId is null)
        set @manifestationId = 0

        if (@tconcept1Id is null)
        set @tconcept1Id = 9 

        if (@tconcept2Id is null)
        set @tconcept2Id = 0 

        select top 1 @code1=icdcode4,@code2=icdcode5,@code3=icdcode6 from #DisIcds 
        where Disorderid=@disorderId and causeid=@causeId and siteid=@siteId 
        and site1id=@site1Id and site2id=@site2Id and 
        ManifestationId = @manifestationId and stage = @stage and 
        temporalconcept1 = @tconcept1Id and temporalconcept2 = @tconcept2Id

        if(@Code1 is not null)
        exec NLP_InsertDxCodeEvidence @AccountNumber,@DocumentId,@code1,@Disorder,@Cause,@Site,@Site1,@Site2,@Manifestation,@Content,@StartId,@EndId


        if(@code1 is null and @siteId!=0)   --site Only
        begin
            print 's and s1- and s2'                                        
            select top 1 @code1=icdcode4,@code2=icdcode5,@code3=icdcode6 from #DisIcds 
            where Disorderid=@disorderId and causeid=0 and siteid=ISNULL(@siteId,0) 
            and site1id=0 and site2id=ISNULL(@site2Id,0) and ManifestationId = ISNULL(@manifestationId,0)
            and stage=@stage and TemporalConcept1=@tconcept1Id and temporalconcept2=ISNULL(@tconcept2Id,0)

            if(@Code1 is not null)
            exec NLP_InsertDxCodeEvidence @AccountNumber,@DocumentId,@code1,@Disorder,@Cause,@Site,@Site1,@Site2,@Manifestation,@Content,@StartId,@EndId

            --NLP_insertDxCodeEvidance                      
            if(@code1 is null)
            begin
                print 's and s1- and s2-'   
                select top 1 @code1=icdcode4,@code2=icdcode5,@code3=icdcode6 from #DisIcds 
                where Disorderid=@disorderId and causeid=0 and siteid=ISNULL(@siteId,0) and site1id=0
                and site2id=0 and ManifestationId = ISNULL(@manifestationId,0) and stage=@stage 
                and TemporalConcept1=@tconcept1Id and temporalconcept2=ISNULL(@tconcept2Id,0)

                if(@Code1 is not null)
                exec NLP_InsertDxCodeEvidence @AccountNumber,@DocumentId,@code1,@Disorder,@Cause,@Site,@Site1,@Site2,@Manifestation,@Content,@StartId,@EndId
            end
        end 

        if(@code1 is null)  --disorder Only
        begin
                print 'D'                                                               
                select top 1 @code1=icdcode4,@code2=icdcode5,@code3=icdcode6 from #DisIcds 
                where Disorderid=@disorderId and causeid=0 and SiteId=0 and Site1Id=0 and Site2Id=0 
                and ManifestationId=0 and stage=@stage and TemporalConcept1=@tconcept1Id 
                and temporalconcept2=0 

                if(@Code1 is not null)
                exec NLP_InsertDxCodeEvidence @AccountNumber,@DocumentId,@code1,@Disorder,@Cause,@Site,@Site1,@Site2,@Manifestation,@Content,@StartId,@EndId

                --StartHere                                         
            if(@code1 is not null and @manifestationId!=0)
            begin                        
                 declare @mstartId int
                 declare @mendId int
                 declare @mcode1 varchar(50)
                 declare @mcode2 varchar(50)
                 declare @mcode3 varchar(50)
                 declare @manfestDisId int
                 declare @indexId int
                 declare @DisIndexId int


                 Select top 1 @manfestDisId = disorderid from MasterHRCM.dbo.KB_Disorder where disorder=@manifestation and Status=0

                 select top 1 @mcode1=icdcode4,@mcode2=IcdCode5,@mcode3=IcdCode6 from MasterHRCM.dbo.KB_DxCode ic
                 inner join MasterHRCM.dbo.CMS_DxCodeDesc d on ic.Icdcode4 = d.ICD10Code
                 where DisorderId=@manfestDisId and CauseId=0 and SiteId=0 and Site1Id=0 and Site2Id=0 and 
                 ManifestationId=0 and stage=@stage and type=@typeId and temporalconcept1=@tconcept1Id 
                 and temporalconcept2=0 and ic.Status != 1 and d.Status = 1 and history=@history 
                 and neonatal=@Neonatal and @dischdate between d.EffectiveYearFrom and d.EffectiveYearTo 

                    if(@mcode1 is not null)
                    begin                        
                        select @indexId=CHARINDEX(@manifestation, @content)
                        select @DisIndexId=CHARINDEX(@disorder, @content)
                        set @mstartId=@startId+@indexId
                        set @mendId = @mstartId+LEN(@manifestation)
                        set @endId=@startId+@DisIndexId+LEN(@disorder)                                                                      

                        ---Insereting Manifestattion as DisorderId in Tempdisease
                        print 'Manifestation as Disorder'                           
                        insert into NLP_DxCodeByDocument (AccountNumber, DocumentId, DxCode, AnnotationString,Poa,SectionHeader,Finding,History,UserName,AnnotationId,StartId, EndId,Rstatus,DxCodeSource,Codable)
                        values(@AccountNumber,@DocumentId,@mcode1,@manifestation,'Y',@sectionHeader,@finding,@history,'KPAI',@annotId,@mstartId,@mendId,0,@ruleName,@Codable)                                   

                        exec NLP_InsertDxCodeEvidence @AccountNumber,@DocumentId,@mcode1,@Disorder,@Cause,@Site,@Site1,@Site2,@Manifestation,@Content,@StartId,@EndId

                        if(@mcode2 is not null and @mcode2!='')
                        begin
                        insert into NLP_DxCodeByDocument (AccountNumber, DocumentId, DxCode, AnnotationString,Poa,SectionHeader,Finding,History,UserName,AnnotationId,StartId, EndId,Rstatus,DxCodeSource,Codable)
                        values(@AccountNumber,@DocumentId,@mcode2,@manifestation,'Y',@sectionHeader,@finding,@history,'KPAI',@annotId,@mstartId,@mendId,0,@ruleName,@Codable)

                        exec NLP_InsertDxCodeEvidence @AccountNumber,@DocumentId,@mcode2,@Disorder,@Cause,@Site,@Site1,@Site2,@Manifestation,@Content,@StartId,@EndId
                        end
                    end
            end                 
        end

    if (@disorderid is null)
    begin
        print 'Entry in disorder table only'
        select top 1 @disorderId=disorderid from MasterHRCM.dbo.KB_Disorder where disorder=@disorder
        insert into NLP_DxCodeByDocument (AccountNumber, DocumentId, DxCode, AnnotationString,Poa,SectionHeader,Finding,History,UserName,AnnotationId,StartId, EndId,Rstatus,DxCodeSource,Codable)
        values(@AccountNumber,@DocumentId,'unknown',@content,'Y',@sectionHeader,@finding,@history,'KPAI',@annotId,@startId,@endId,0,@ruleName,@Codable)     
    end
    else
    if(@code1 is not null and @code1!='')
    begin
        print 'Disorder id existed in icdcode1'
        insert into NLP_DxCodeByDocument (AccountNumber, DocumentId, DxCode, AnnotationString,Poa,SectionHeader,Finding,History,UserName,AnnotationId,StartId, EndId,Rstatus,DxCodeSource,Codable)
        values(@AccountNumber,@DocumentId,@code1,@content,'Y',@sectionHeader,@finding,@history,'KPAI',@annotId,@startId,@endId,0,@ruleName,@Codable)

        exec NLP_InsertDxCodeEvidence @AccountNumber,@DocumentId,@code1,@Disorder,@Cause,@Site,@Site1,@Site2,@Manifestation,@Content,@StartId,@EndId
    end

    if(@code2 is not null and @code2!='')       
    begin           
        insert into NLP_DxCodeByDocument (AccountNumber, DocumentId, DxCode, AnnotationString,Poa,SectionHeader,Finding,History,UserName,AnnotationId,StartId, EndId,Rstatus,DxCodeSource,Codable)
        values(@AccountNumber,@DocumentId,@code2,@content,'Y',@sectionHeader,@finding,@history,'KPAI',@annotId,@startId,@endId,0,@ruleName,@Codable)

        exec NLP_InsertDxCodeEvidence @AccountNumber,@DocumentId,@code2,@Disorder,@Cause,@Site,@Site1,@Site2,@Manifestation,@Content,@StartId,@EndId
    end                             

    drop table #DisIcds 

    if(@finding='positive')
    begin
        exec NLP_InsertObgComplication @Pstatus,@Pstatus1,@AccountNumber,@DocumentId,@DocumentType,@code1
    end

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo '<Input-Params>','NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertObgHabitCode

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertObgHabitCode]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/07/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertObgHabitCode] 
@AccountNumber varchar(30),
@Trimester tinyint
AS
Declare @InputParamQry varchar(500)
SET @InputParamQry='AccountNumber: '+''+@AccountNumber+''+'|'+
'@Trimester: '+''+cast(@Trimester as varchar(15))+''
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try

        if exists(select top 1 AccountNumber from NLP_DxCodeByDocument where DxCode like 'O%' and AccountNumber=@AccountNumber)
        begin
            insert into NLP_DxCodeByDocument (AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,
            StartId,EndId,Rstatus,DxCodeSource,Codable)
            select i.AccountNumber,i.DocumentId,oc.Icd10code,oc.trimester,'Y',i.Finding,i.History,'KPAI',i.AnnotationId,
            i.StartId,i.EndId,0,'OBGHabitsdata','Y' 
            from MasterHRCM.dbo.KB_ObgComplication oc
            inner join MasterHRCM.dbo.KB_ObgInfectiousCrosswalk o on oc.code=o.obgcode
            inner join NLP_DxCodeByDocument i on o.icdcode = i.DxCode
            where AccountNumber=@AccountNumber and DxCode like 'F%' and oc.trimstatus=@trimester
            and oc.Icd10code not in(select distinct DxCode from NLP_DxCodeByDocument where AccountNumber=@AccountNumber)
        end 
    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo @InputParamQry,'NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertOutcomeOfDeliveryCode

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertOutcomeOfDeliveryCode]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/07/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertOutcomeOfDeliveryCode] 
@AccountNumber varchar(30),
@DocumentId int,
@Fetusno varchar(50),
@Stillborn varchar(500),
@DocumentType varchar(20)
AS
Declare @InputParamQry varchar(500)
SET @InputParamQry='AccountNumber: '+''+@AccountNumber+''+'|'+
'DocumentID: '+''+cast(@DocumentID as varchar(15))+''+'|'+
'@Fetusno: '+''+@Fetusno+''+'|'+
'@Stillborn: '+''+@Stillborn+''+'|'+
'@DocumentType: '+''+@DocumentType+''

declare @code as varchar(50)
declare @codedesc as varchar(700)
declare @priority as int
declare @tmpIntId as int
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try
        select @code=targetcode,@codedesc=codedescription from MasterHRCM.dbo.KB_ObgDeliveryStatus where FetusCount=@fetusno and StillBirthStatus=@stillborn
        if not exists (select top 1 AccountNumber from NLP_DxCodeByDocument where AccountNumber = @AccountNumber and DxCode = @code)
        begin           
            insert into NLP_DxCodeByDocument(AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
            values(@AccountNumber,@DocumentId,@code,@codedesc,'Y','Positive','False','KPAI',0,0,0,0,'OBGDeliveryStatus','Y')
        end                     
    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo @InputParamQry,'NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertStandardPcs

Description:

Schema:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertStandardPcs]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/12/2018
-- Description: To insert Procedure code into NLP_PcsCodeByDocument by using the all standard PCS Terms.(Fusion like PCS3 Procedures) 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertStandardPcs] 
    @accountnumber  varchar(30),   
    @documentId int,  
    @operation varchar(100), 
    @docOperation varchar(100), 
    @bodyPart varchar(100),  
    @device varchar(100),   
    @qualifier varchar(100),
    @approach varchar(100),
    @opStartPos int,
    @opEndPos int,
    @bpStartPos int,
    @bpEndPos int,
    @devStartPos int,
    @devEndPos int,
    @quaStartPos int,
    @quaEndPos int,
    @approachStartPos int, 
    @approachEndPos int,
    @finalCode varchar(20),
    @sectionHeader varchar(20),
    @userName varchar(30)
AS
DECLARE @code VARCHAR(10)
BEGIN

    SET NOCOUNT ON;
    Begin Try

    if(@finalCode='')
    Begin
    SELECT @code = Code from MasterHRCM.dbo.MST_PCSTabular where operation=@operation and bodypart=@bodyPart
        and approach=@approach and device=@device and qualifier=@qualifier  
    End     
    else
        Begin
           set @code = @finalCode
        End

    if(@code is not null)
    begin

    INSERT INTO dbo.NLP_PcsCodeByDocument (AccountNumber,documentId,PcsCode,PcsDesc,PhysicianID,PcsDate,UserName,SectionHeader,Finding,History)
    VALUES(@accountnumber,@documentId,@code,@operation,null,null,@userName,@sectionHeader,'Positive','False')

    INSERT INTO dbo.NLP_PcsCodeEvidance (AccountNumber,documentId,PcsCode,PcsTerm,PcsType,StartId,EndId,UserName)
    VALUES(@accountnumber,@documentId,@code,@docOperation,'Operation',@opStartPos,@opEndPos,@userName)

    INSERT INTO dbo.NLP_PcsCodeEvidance (AccountNumber,documentId,PcsCode,PcsTerm,PcsType,StartId,EndId,UserName)
    VALUES(@accountnumber,@documentId,@code,@bodyPart,'BodyPart',@bpStartPos,@bpEndPos,@userName)

    if(@device !='')
    begin

    INSERT INTO dbo.NLP_PcsCodeEvidance (AccountNumber,documentId,PcsCode,PcsTerm,PcsType,StartId,EndId,UserName)
    VALUES(@accountnumber,@documentId,@code,@device,'Device',@devStartPos,@devEndPos,@userName)

    end 

    if(@qualifier !='')
    begin

    INSERT INTO dbo.NLP_PcsCodeEvidance (AccountNumber,documentId,PcsCode,PcsTerm,PcsType,StartId,EndId,UserName)
    VALUES(@accountnumber,@documentId,@code,@qualifier,'Qualifier',@quaStartPos,@quaEndPos,@userName)

    end 

    if(@approach !='')
    begin

    INSERT INTO dbo.NLP_PcsCodeEvidance (AccountNumber,documentId,PcsCode,PcsTerm,PcsType,StartId,EndId,UserName)
    VALUES(@accountnumber,@documentId,@code,@approach,'Approach',@approachStartPos,@approachEndPos,@userName)

    end     
    end

    /*We are giving Transfusion code '30233_1' directly if LabResults Table contains ProductId(TestName) and PhysicianId,date are empty-- Venkatesh -- Harikrishna*/
            if exists (select top 1 Result from FTP_Lab where AccountNumber = @AccountNumber and (Testname like '%Product ID' or Testname like '%Product Code'))
            begin                   
                Insert into NLP_PcsCodeByDocument (AccountNumber,documentId,PcsDesc,PcsCode,PhysicianID,PcsDate,UserName,SectionHeader,Finding,History)   
                select distinct @AccountNumber,@documentId,'Transfusion',p.code,'','','KPAI','Transfusion from SP','Positive','False' from FTP_Lab l
                inner join MasterHRCM.dbo.MST_PCSFromReports p on l.Result=p.result and l.TestName like '%'+p.testname
                and l.AccountNumber=@AccountNumber and p.code not in (select PcsCode from NLP_PcsCodeByDocument where AccountNumber = @AccountNumber)
            end

    /*We are giving Hemodialysis code '5A1D70Z' directly if NursingReport Table contains vsqueryvalue(Hemodialysis) -- Venkatesh -- Harikrishna*/
            if exists (select top 1 EventResult from FTP_NurseNote where AccountNumber = @AccountNumber and EventResult = 'Hemodialysis' and EventDesc like '%Urinary Elimination')
            begin   
                if not exists (select top 1 PcsCode from NLP_PcsCodeByDocument where AccountNumber = @AccountNumber and PcsCode = '5A1D70Z')
                begin           
                Insert into NLP_PcsCodeByDocument (AccountNumber,documentId,PcsDesc,PcsCode,PhysicianID,PcsDate,UserName,SectionHeader,Finding,History)   
                values(@AccountNumber,@documentId,'Performance','5A1D70Z','','','KPAI','Hemodialysis from SP','Positive','False')  
                end 
            end

            /*We are giving Ventilation codes '5A19_5Z' directly if Vitals Table contains Standardvalue(Ventilator) and take vitaldate diff get appropriate Pcs code -- Venkatesh -- Harikrishna*/
            declare @ventilationCode varchar(50)
            if exists (select top 1 VitalSignDate from FTP_VitalSign where AccountNumber=@AccountNumber and Result like'%ventilator%')
            begin   
                select @ventilationCode=case when DATEDIFF(hh,min(VitalSignDate), max(VitalSignDate)) <24 then '5A1935Z'
                                 when DATEDIFF(hh,min(VitalSignDate), max(VitalSignDate)) >96 then '5A1955Z'
                                 else '5A1945Z' end
                from FTP_VitalSign where AccountNumber=@AccountNumber and Result like'%ventilator%' 

                if not exists (select top 1 PcsCode from NLP_PcsCodeByDocument where AccountNumber = @AccountNumber and PCSCode = @ventilationCode)
                begin           
                Insert into NLP_PcsCodeByDocument (AccountNumber,documentId,PcsDesc,PcsCode,PhysicianID,PcsDate,UserName,SectionHeader,Finding,History)   
                values(@AccountNumber,@documentId,'Performance',@ventilationCode,'','','KPAI','Ventilation From SP','Positive','False')  
                end 
            end

            /*We are giving CPAP/BIPAP codes '5A09_57' directly if Vitals Table contains Standardvalue(CPAP/BIPAP) and take vitaldate diff get appropriate Pcs code -- Venkatesh -- Harikrishna -- 05-Jan-2018*/
            declare @cpapCode varchar(50)
            if exists (select top 1 VitalSignDate from FTP_VitalSign where AccountNumber=@AccountNumber and (Result like '%BIPAP' or Result like '%CPAP'))
            begin   
                select @cpapCode=case when DATEDIFF(hh,min(VitalSignDate), max(VitalSignDate)) <24 then '5A09357'
                                 when DATEDIFF(hh,min(VitalSignDate), max(VitalSignDate)) >96 then '5A09557'
                                 else '5A09457' end
                from FTP_VitalSign where AccountNumber=@AccountNumber and (Result like '%BIPAP' or Result like '%CPAP')

                if not exists (select top 1 PcsCode from NLP_PcsCodeByDocument where AccountNumber = @AccountNumber and PcsCode = @cpapCode)
                begin           
                Insert into NLP_PcsCodeByDocument (AccountNumber,documentId,PcsDesc,PcsCode,PhysicianID,PcsDate,UserName,SectionHeader,Finding,History)   
                values(@AccountNumber,@documentId,'Assistance',@cpapCode,'','','KPAI','CPAP From SP','Positive','False')  
                end 
            end

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo '<Input-Params>','NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertSurgicalHistoryData

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertSurgicalHistoryData]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/06/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertSurgicalHistoryData] 
@AccountNumber varchar(30),
@DocumentId int,
@disease varchar(200),
@disType varchar(50),
@history varchar(20),
@finding varchar(20),
@StartId int,
@EndId int,
@DocumentType varchar(20)
AS
Declare @InputParamQry varchar(500)
SET @InputParamQry='AccountNumber: '+''+@AccountNumber+''+'|'+
'DocumentID: '+''+cast(@DocumentID as varchar(15))+''+'|'+
'@disease: '+''+@disease+''+'|'+
'@disType: '+''+@disType+''+'|'+
'@history: '+''+@history+''+'|'+
'@finding: '+''+@finding+''+'|'+
'@StartId: '+''+cast(@StartId as varchar(15))+''+'|'+
'@EndId: '+''+cast(@EndId as varchar(15))+''+'|'+
'@DocumentType: '+''+@DocumentType+''

declare @disorderId int
declare @code1 varchar(10)
declare @code2 varchar(10)
declare @dischdate datetime
BEGIN
    set @dischdate = null
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try

        select @dischdate = isnull(DischargeDate,getdate()) from HIM_Visit where AccountNumber = @AccountNumber

        if exists(select top 1 Disorder from MasterHRCM.dbo.KB_SurgicalDxCode where Disorder =@disease and status = 0)
        begin
            select @disorderId = disorderid,@code1=Icdcode1,@code2=Icdcode2 from MasterHRCM.dbo.KB_SurgicalDxCode sd
            inner join MasterHRCM.dbo.CMS_DxCodeDesc d on d.ICD10Code = sd.Icdcode1
            where Disorder =@disease and d.Status = 1
            and @dischdate between d.EffectiveYearFrom and d.EffectiveYearTo

            insert into NLP_DxCodeByDocument (AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
            values(@AccountNumber,@DocumentId,@code1,@disease,'Y',@finding,'True','KPAI',0,@StartId,@EndId,0,'SurgDis','Y')

            if(@code2 is not null and @code2!='')
            begin                          
               insert into NLP_DxCodeByDocument (AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
               values(@AccountNumber,@DocumentId,@code2,@disease,'Y',@finding,'True','KPAI',0,@StartId,@EndId,0,'SurgDis','Y')
            end                 
        end

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo @InputParamQry,'NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertVitalSign

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertVitalSign]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 05/21/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertVitalSign] 
    -- Add the parameters for the stored procedure here
    @AccountNumber varchar(30),
    @DocumentID int,
    @VitalSign varchar(150),    
    @Result varchar(150),
    @VitalSignDate varchar(50),
    @SectionHeader varchar(200),
    @StartId int,
    @EndId int,
    @HospitalDay int
AS
Declare @InputParamQry varchar(200)
SET @InputParamQry='AccountNumber: '+''+@AccountNumber+''+'|'+
'DocumentID: '+''+cast(@DocumentID as varchar(50))+''+'|'+
'VitalSign: '+''+@VitalSign+''+'|'+
'@Result: '+''+@Result+''+'|'+
'@VitalSignDate: '+''+@VitalSignDate+''+'|'+
'@SectionHeader: '+''+@SectionHeader+''+'|'+
'@StartId: '+''+cast(@StartId as varchar(20))+''+'|'+
'@EndId: '+''+cast(@EndId as varchar(20))+''+'|'+
'@HospitalDay: '+''+cast(@HospitalDay as varchar(5))+''
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try

    insert into NLP_VitalSign(AccountNumber,DocumentID,VitalSign,Result,VitalSignDate,SectionHeader,StartId,EndId,HospitalDay)
    values(@AccountNumber,@DocumentID,@VitalSign,@Result,CONVERT(datetime,@VitalSignDate,101),@SectionHeader,@StartId,@EndId,@HospitalDay)

    update NLP_VitalSign set NumericResult = case when Result like'[A-Za-z]%'
    then case when substring(Result,2,charindex(' ',Result,charindex(' ',Result)+1))='' then substring(Result,charindex(' ',Result),len(Result))
    else substring(ltrim(rtrim(substring(Result,charindex(' ',Result),len(Result)))),0,charindex(' ',ltrim(rtrim(substring(Result,
    charindex(' ',Result),len(Result))))))  end else case when substring(Result,0,charindex(' ',Result))='' then Result else 
    substring(Result,0,charindex(' ',Result)) end end where DocumentID=@DocumentID

    update NLP_VitalSign set NumericResult = replace(Result,'%','') where Result like'%[%]%' and DocumentID=@DocumentID

    update NLP_VitalSign set NumericResult=REPLACE(RTRIM(NumericResult),'s', '')  where  NumericResult like '%[A-Za-z]%' and DocumentID=@DocumentID

    update NLP_VitalSign set NumericResult=SUBSTRING(NumericResult,1,CHARINDEX('/',NumericResult)-1),
    NumericResult2=SUBSTRING(NumericResult,CHARINDEX('/',NumericResult)+1,LEN(NumericResult))
    where  NumericResult like '%[/]%' and CHARINDEX('/',NumericResult,1)>0  and DocumentID=@DocumentID

    update NLP_VitalSign set NumericResult =''  where NumericResult like '%[A-Za-z]%' and DocumentID=@DocumentID

    --Step : Convert WT from Pounds to KGS   
    update NLP_VitalSign set NumericResult=cast((0.453592*cast(NumericResult as int))as decimal(10,2)) where VitalSign like '%Weight%' 
    and Result like '%pounds' and DocumentID=@DocumentID

    --BMI Result Insertion to MeditechVitals    
    insert into FTP_VitalSign(AccountNumber,VitalSignDate,VitalSign,Result,HospitalDay)
    select top 1 @AccountNumber,VitalSignDate,VitalSign,Result,HospitalDay from NLP_VitalSign 
    where AccountNumber=@AccountNumber and DocumentId=@DocumentID and VitalSign in ('BMI','Body mass index','Calculated BMI')

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo @InputParamQry,'NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertVseriesCombination

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertVseriesCombination]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/06/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertVseriesCombination] 
@AccountNumber varchar(30),
@DocumentId int,
@Vehicle varchar(50),
@OpVehicle varchar(50), 
@Person varchar(50),
@Traffic varchar(50),
@Encounter varchar(50),
@Event varchar(50),
@DocumentType varchar(50),
@StartId int,
@EndId int,
@AnnotId int,
@ActualDesc varchar(100)
AS
Declare @InputParamQry varchar(500)
SET @InputParamQry='AccountNumber: '+''+@AccountNumber+''+'|'+
'DocumentID: '+''+cast(@DocumentID as varchar(15))+''+'|'+
'@Vehicle: '+''+@Vehicle+''+'|'+
'@OpVehicle: '+''+@OpVehicle+''+'|'+
'@Person: '+''+@Person+''+'|'+
'@Traffic: '+''+@Traffic+''+'|'+
'@Encounter: '+''+@Encounter+''+'|'+
'@Event: '+''+@Event+''+'|'+
'@DocumentType: '+''+@DocumentType+''+'|'+
'@StartId: '+''+cast(@StartId as varchar(15))+''+'|'+
'@EndId: '+''+cast(@EndId as varchar(15))+''+'|'+
'@AnnotId: '+''+cast(@AnnotId as varchar(15))+''+'|'+
'@ActualDesc: '+''+@ActualDesc+''


declare @Tarcode as varchar(15)
declare @shortdesc as varchar(100)
declare @priority as int
declare @tmpIntId as int
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try
        if exists(select top 1 1 from MasterHRCM.dbo.KB_VSeriesCore where event=@event and Victim=@person and VTVehicle=@Vehicle and OPVehicle=@opVehicle and traffic=@Traffic and encounter='Initial Encounter')
        begin
            select @Tarcode=code from MasterHRCM.dbo.KB_VSeriesCore where event=@event and Victim=@person and VTVehicle=@Vehicle and OPVehicle=@opVehicle and traffic=@traffic and encounter='Initial Encounter'
            select @shortdesc=ShortDesc from MasterHRCM.dbo.CMS_DxCodeDesc where ICD10Code=@Tarcode

            insert into NLP_DxCodeByDocument (AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
            values(@AccountNumber,@DocumentId,@Tarcode,@ActualDesc,'Y','Positive','False','KPAI',@AnnotId,@StartId,@EndId,0,'VseriesKeyword','Y')

            insert into NLP_VSeriesCode(AccountNumber,DocumentId,Event,Victim,VTVehicle,OPVehicle,Traffic,Encounter,Code,Rstatus,UserName)
            values(@AccountNumber,@DocumentId,@event,@person,@Vehicle,@opVehicle,@traffic,'Initial Encounter',@Tarcode,0,'KPAI')
        end 
    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo @InputParamQry,'NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertWSeriesCombination

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertWSeriesCombination]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/06/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertWSeriesCombination] 
@AccountNumber varchar(30),
@DocumentId int,
@Keyterm varchar(100),
@Keytype varchar(100), 
@Action varchar(50),
@State varchar(50),
@UserName varchar(50),
@DocumentType varchar(20),
@StartId int,
@EndId int,
@AnnotId int
AS
Declare @InputParamQry varchar(500)
SET @InputParamQry='AccountNumber: '+''+@AccountNumber+''+'|'+
'DocumentID: '+''+cast(@DocumentID as varchar(15))+''+'|'+
'@Keyterm: '+''+@Keyterm+''+'|'+
'@Keytype: '+''+@Keytype+''+'|'+
'@Action: '+''+@Action+''+'|'+
'@State: '+''+@State+''+'|'+
'@UserName: '+''+@UserName+''+'|'+
'@DocumentType: '+''+@DocumentType+''+'|'+
'@StartId: '+''+cast(@StartId as varchar(15))+''+'|'+
'@EndId: '+''+cast(@EndId as varchar(15))+''+'|'+
'@AnnotId: '+''+cast(@AnnotId as varchar(15))+''
declare @Tarcode as varchar(15)
declare @stddisorder as varchar(100)
declare @shortdesc as varchar(200)
declare @priority as int
declare @tmpIntId as int
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try
        if exists(select top 1 1 from MasterHRCM.dbo.KB_WSeriesCoreData where keyterm=@keyterm and keytype=@keytype and action=@action and rstatus=0)
        begin
            select @Tarcode=code,@stddisorder=standarddisorder from MasterHRCM.dbo.KB_WSeriesCoreData
            where keyterm=@keyterm and keytype=@keytype and action=@action and rstatus=0

            if(@state='subsequent')
            begin
                select @Tarcode=@Tarcode+CASE len(@Tarcode) 
                 WHEN 3 THEN '.XXXD'
                 --WHEN 4 THEN '.XXXD'
                 WHEN 5 THEN 'XXD'
                 WHEN 6 THEN 'XD'
                 ELSE 'D' END  
            end 
            else if(@state='sequela')
            begin
                select @Tarcode=@Tarcode+CASE len(@Tarcode) 
                 WHEN 3 THEN '.XXXS'
                 --WHEN 4 THEN '.XXXS'
                 WHEN 5 THEN 'XXS'
                 WHEN 6 THEN 'XS'
                 ELSE 'S' END
            end 
            else
            begin
                select @Tarcode=@Tarcode+CASE len(@Tarcode) 
                 WHEN 3 THEN '.XXXA'
                 --WHEN 4 THEN '.XXXA'
                 WHEN 5 THEN 'XXA'
                 WHEN 6 THEN 'XA'
                 ELSE 'A' END
            end             
            select @shortdesc=ShortDesc from MasterHRCM.dbo.CMS_DxCodeDesc where ICD10Code=@Tarcode
            insert into NLP_DxCodeByDocument (AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
            values(@AccountNumber,@DocumentId,@Tarcode,@shortdesc,'Y','Positive','False','KPAI',@AnnotId,@StartId,@EndId,0,'WseriesKeyword','Y')
            insert into NLP_WSeriesCode(AccountNumber,DocumentId,Keyterm,Keytype,Action,State,UserName,Code,RStatus,StandardDisorder)
            values(@AccountNumber,@DocumentId,@keyterm,@keytype,@action,@state,@username,@Tarcode,0,@stddisorder)
    end 

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo @InputParamQry,'NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_InsertYSeriesCombination

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_InsertYSeriesCombination]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/06/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_InsertYSeriesCombination] 
@AccountNumber varchar(30),
@DocumentId int,
@Activity varchar(50),
@Place varchar(50), 
@ExternalStatus varchar(50),    
@DocumentType varchar(50),
@StartId int,
@EndId int,
@AnnotId int
AS
Declare @InputParamQry varchar(500)
SET @InputParamQry='AccountNumber: '+''+@AccountNumber+''+'|'+
'DocumentID: '+''+cast(@DocumentID as varchar(15))+''+'|'+
'@Activity: '+''+@Activity+''+'|'+
'@Place: '+''+@Place+''+'|'+
'@ExternalStatus: '+''+@ExternalStatus+''+'|'+
'@DocumentType: '+''+@DocumentType+''+'|'+
'@StartId: '+''+cast(@StartId as varchar(15))+''+'|'+
'@EndId: '+''+cast(@EndId as varchar(15))+''+'|'+
'@AnnotId: '+''+cast(@AnnotId as varchar(15))+''

declare @ActivityCode as varchar(15)
declare @PlaceCode as varchar(15)
declare @externalCode as varchar(100)
declare @priority1 as int
declare @priority2 as int
declare @priority3 as int
declare @tmpIntId1 as int
declare @tmpIntId2 as int
declare @tmpIntId3 as int
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try
        if exists(select top 1 1 from MasterHRCM.dbo.KB_YSeriesActivity where (activity=@activity or place=@place))
        begin
            if(@activity='Unspecified' and @place='Unspecified')
            begin
                select @ActivityCode=code from MasterHRCM.dbo.KB_YSeriesActivity where activity='Unspecified Activity' and place='Unspecified Place'
                select @PlaceCode=code from MasterHRCM.dbo.KB_YSeriesActivity where activity='Unspecified Place' and place='Unspecified Place'
            end
            else if(@activity='Unspecified' and @place!='Unspecified')
            begin
                select @ActivityCode=code from MasterHRCM.dbo.KB_YSeriesActivity where activity=@activity and place=@place
                select @PlaceCode=code from MasterHRCM.dbo.KB_YSeriesActivity where activity=@activity and place=@place         
            end
            else
            begin
                select @ActivityCode=code from MasterHRCM.dbo.KB_YSeriesActivity where activity=@activity and place='Unspecified'
                select @PlaceCode=code from MasterHRCM.dbo.KB_YSeriesActivity where activity=@activity and place=@place         
            end

            select @externalCode=code from MasterHRCM.dbo.KB_YSeriesActivity where activity=@externalStatus and place='Unspecified'

            if(@PlaceCode is null or @PlaceCode like '%Y93%')
            set @PlaceCode='Y92.9'

            -- For Place COde           
            insert into NLP_DxCodeByDocument (AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
            values(@AccountNumber,@DocumentId,@PlaceCode,@Place,'Y','Positive','False','KPAI',@AnnotId,@StartId,@EndId,0,'Y92seriesKeyword','Y')

            -- For Activity Code
            insert into NLP_DxCodeByDocument (AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
            values(@AccountNumber,@DocumentId,@ActivityCode,@Activity,'Y','Positive','False','KPAI',@AnnotId,@StartId,@EndId,0,'Y93seriesKeyword','Y')

            -- For ExternalStatus Code          
            insert into NLP_DxCodeByDocument (AccountNumber,DocumentId,DxCode,AnnotationString,Poa,Finding,History,UserName,AnnotationId,StartId,EndId,Rstatus,DxCodeSource,Codable)
            values(@AccountNumber,@DocumentId,@externalCode,@ExternalStatus,'Y','Positive','False','KPAI',@AnnotId,@StartId,@EndId,0,'Y99seriesKeyword','Y')

            insert into NLP_VSeriesCode(AccountNumber,DocumentId,Event,Code,UserName)
            values(@AccountNumber,@DocumentId,@activity,@ActivityCode,'KAPI')

            insert into NLP_VSeriesCode(AccountNumber,DocumentId,Event,Code,UserName)
            values(@AccountNumber,@DocumentId,@Place,@PlaceCode,'KAPI')

            insert into NLP_VSeriesCode(AccountNumber,DocumentId,Event,Code,UserName)
            values(@AccountNumber,@DocumentId,@ExternalStatus,@externalCode,'KAPI') 
    end 
    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo @InputParamQry,'NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_RunDxCodeExclusionByPCSCodeRule

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_RunDxCodeExclusionByPCSCodeRule]    Script Date: 06/21/2018 10:58:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/20/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_RunDxCodeExclusionByPCSCodeRule] 
    -- Add the parameters for the stored procedure here
@AccountNumber varchar(30),
@DocumentTypeId int,
@DocumentType varchar(20)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try
            /*Updating Status in ICD10Icdpriority*/         
            update NLP_DxCode set DxExclusionTypeId = 2 where DxCode in (
            select distinct dxcode from MasterHRCM.dbo.KB_PcsDxExclusion pcs
            inner join NLP_PCSCode pro on pcs.PCSCode=left(pro.PCSCode,4)
            where pro.AccountNumber=@AccountNumber
            )and AccountNumber=@AccountNumber and DxExclusionTypeId=0
    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo '<Input-Params>','NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_RunDxTabExclusion1Rule

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_RunDxTabExclusion1Rule]    Script Date: 06/21/2018 10:58:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/20/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_RunDxTabExclusion1Rule] 
    -- Add the parameters for the stored procedure here
@AccountNumber varchar(30),
@DocumentId int,
@DocumentType varchar(20)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try
        /*Following line added by Krishnareddy for handling a situation where high priority coded deleted by user then omitted 
        code of 11 on this code should be back to normal*/

        Update NLP_DxCode set DxExclusionTypeId=0 where AccountNumber=@AccountNumber and DxExclusionTypeId=3

        select distinct DxCode,0 as rstatus into #extable from NLP_DxCode
        where AccountNumber=@AccountNumber and DxExclusionTypeId in (0,3)

        update #extable set rstatus=3 where DxCode in(
        select distinct e.DxCode from #extable e
        inner join MasterHRCM.dbo.KB_DxTabExclusion1Code ed on e.DxCode=ed.code1
        inner join #extable e2 on ed.code2 = e2.DxCode
        where ed.Rstatus=0)

        update NLP_DxCode set DxExclusionTypeId=3 where AccountNumber=@AccountNumber and 
        DxCode in(select DxCode from #extable where rstatus=3)

        DROP table #extable

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo '<Input-Params>','NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_RunErrDxCodeExclusionRule

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_RunErrDxCodeExclusionRule]    Script Date: 06/21/2018 10:58:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/20/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_RunErrDxCodeExclusionRule] 
    -- Add the parameters for the stored procedure here
@AccountNumber varchar (30),
@DocumentId int,
@DocumentType varchar(20)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try
            --ERR Exclusion
            update NLP_DxCode set DxExclusionTypeId=1 from NLP_DxCode dx
            inner join NLP_DxCodeByDocument dcd on dx.AccountNumber=dcd.AccountNumber
            where dcd.AccountNumber=@AccountNumber and RStatus=0
            and @DocumentType like 'er%'  and dcd.History = 'false'and dcd.DxCodeSource not in ('PMH','LongTermDrugDisease')
            and dcd.DxCode not in(select DxCode from NLP_DxCodeByDocument where AccountNumber=@AccountNumber and RStatus=0
            and Finding = 'positive' and @DocumentType not  like 'er%' and DxCode is not null)
            and dcd.DxCode not in(select DxCode from NLP_DxCodeByDocument where AccountNumber=@AccountNumber and RStatus=0 
            and Finding = 'None' and @DocumentType = 'D' and DxCode is not null)
            and dcd.DxCode not in (select icd10code from MasterHRCM.dbo.CMS_DxCodeDesc where chronic = 1)
            and dcd.AccountNumber not in(select distinct AccountNumber from NLP_DxCodeByDocument where AccountNumber=@AccountNumber 
            and (DxCode like 'O%' or DxCode like 'z38%'))

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo '<Input-Params>','NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_RunHivRulesOverDxCode

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_RunHivRulesOverDxCode]    Script Date: 06/21/2018 10:58:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/20/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_RunHivRulesOverDxCode] 
    -- Add the parameters for the stored procedure here
@AccountNumber varchar(30),
@DocumentId int,
@DocumentType varchar(20)
AS
Declare @AidsCode varchar(10)
Declare @History varchar(10)
Declare @FinalCode varchar(10)
Declare @FinalContent varchar(150)
Set @FinalContent = ''
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try
        if exists (select 1 from NLP_DxCode where AccountNumber=@AccountNumber and DxCode='Z21')
        select distinct i.DxCode,History into #temp from NLP_DxCode i
        inner join NLP_DxCodeByDocument it on it.AccountNumber = i.AccountNumber and it.DocumentId = i.DocumentId and it.DxCode = i.DxCode
        inner join MasterHRCM.dbo.KB_HivDxCode a on i.DxCode = a.A1Code
        where i.AccountNumber = @AccountNumber and a.[Status] = 0

        if exists(select 1 from #temp)
        Begin
            SET @FinalCode = 'B20'
            SET @FinalContent = 'AIDS'

            if not exists(select 1 from NLP_DxCode where AccountNumber=@AccountNumber and DxCode=@FinalCode)    
            insert into NLP_DxCode(AccountNumber,DocumentId,DxCode,DxDesc,Poa,DxType,DxPriority,CcMcc,PhysicianId,DxDate,UserName,Source)   
            select @AccountNumber,@DocumentId,@FinalCode,@FinalContent,'Y','S',0,NULL as CcMcc,PhysicianID,EditDateTime,
            'KPAI','HivRulesOverDxCode' from HIM_Document where DocumentID=@DocumentId          
        End

        if exists (select 1 from #temp where history = 'true')      
        update NLP_DxCode set DxExclusionTypeId=2 from NLP_DxCode it
        inner join #temp t on t.DxCode = it.DxCode
        inner join MasterHRCM.dbo.KB_HivDxCode dd on dd.A1Code = it.DxCode
        where it.DxCode= @AidsCode and dd.[status] = 0 and t.history = 'true'

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo '<Input-Params>','NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_RunHtnRulesOverDxCode

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_RunHtnRulesOverDxCode]    Script Date: 06/21/2018 10:58:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/18/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_RunHtnRulesOverDxCode] 
-- Add the parameters for the stored procedure here
@AccountNumber varchar(30),
@DocumentId int,
@DocumentType varchar(20)
AS
Declare @CkdCode varchar(10)
Declare @ChfCode varchar(10)
Declare @FinalCode varchar(10)
Declare @ChfContent varchar(50)
Declare @CkdContent varchar(50)
Declare @FinalContent varchar(150)
Set @FinalContent = ''
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try

        select distinct d.IcdCode,d.Priority,left(d.IcdCode,3) icdgroup , t.AnnotationString
        into #temp from NLP_DxCode i
        inner join NLP_DxCodeByDocument t on i.DocumentId = t.DocumentId and (i.DxCode = t.DxCode)
        inner join MasterHRCM.dbo.KB_DxExclusionCode d on i.DxCode = d.IcdCode
        where i.AccountNumber=@AccountNumber and GroupId in(1,5)
        order by left(d.IcdCode,3),d.Priority desc

        select top 1 @ChfCode = icdcode, @ChfContent = AnnotationString from #temp a where ICDGROUP ='I11' AND
        priority = (select MAX(priority) from #temp where icdgroup = a.icdgroup) order by icdgroup

        select top 1 @CkdCode = icdcode, @CkdContent = AnnotationString from #temp a where ICDGROUP ='I12' AND
        priority = (select MAX(priority) from #temp where icdgroup = a.icdgroup) order by icdgroup

        if(@ChfCode is not null and @CkdCode is not null)
        begin
            select @FinalCode = FinalCode from MasterHRCM.dbo.KB_HtnDxCode where CHF=@ChfCode and CKD=@CkdCode
            select @FinalContent = @ChfContent +' and '+@CkdContent         

            insert into NLP_DxCode(AccountNumber,DocumentId,DxCode,DxDesc,Poa,DxType,DxPriority,CcMcc,PhysicianId,DxDate,UserName,Source)
            select @AccountNumber,@DocumentId,@FinalCode,@FinalContent,'Y','S',0,NULL as CcMcc,PhysicianID,EditDateTime,
            'KPAI','HtnRulesOverDxCode' from HIM_Document where DocumentID=@DocumentId
        end
        Drop table #temp
    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo '<Input-Params>','NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:NLP_RunSpecificDxCodeExclusionRule

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[NLP_RunSpecificDxCodeExclusionRule]    Script Date: 06/21/2018 10:58:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      ASrinivas
-- Create date: 06/20/2018
-- Description: 
-- =============================================
CREATE PROCEDURE [dbo].[NLP_RunSpecificDxCodeExclusionRule] 
    -- Add the parameters for the stored procedure here
@AccountNumber varchar(20),
@DocumentId int,
@DocumentType varchar(20)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    Begin Try

        update NLP_DxCode set DxExclusionTypeId=0 WHERE AccountNumber=@AccountNumber AND DxExclusionTypeId=2
        --update icd10tempdisease set [Status]=0 WHERE accountno=@accountNo AND [Status]=5

        update NLP_DxCode set DxExclusionTypeId=2 where DxCode in(  
        select distinct dis_Icdcode from (  
        select i.AccountNumber,d.IcdCode dis_Icdcode,d.Priority dis_priority,d.GroupId dis_Groupid,  
        DENSE_RANK() over(PARTITION by i.AccountNumber,d.groupid order by d.groupid,d.Priority desc) Rank1  
        from NLP_DxCode i
        inner join NLP_DxCodeByDocument t on i.DocumentId = t.DocumentId and (i.DxCode=t.DxCode)    
        inner join MasterHRCM.dbo.KB_DxExclusionCode d on i.DxCode = d.IcdCode  
        where i.AccountNumber=@AccountNumber and i.DxExclusionTypeId=0
        ) a where Rank1 <> 1     
        )  
        and AccountNumber = @AccountNumber and DxExclusionTypeId=0

        --exlcuding Leukocyties and fever if Itis or L02 disease existis in ICD10Tempdisease
        if exists (
            select 1 from NLP_DxCodeByDocument dcd inner join NLP_DxCode dx on dcd.AccountNumber = dx.AccountNumber 
            where dcd.AccountNumber = @AccountNumber and (AnnotationString like '%itis%' or dcd.DxCode like 'L02%') 
            and Finding = 'Positive' and dx.DxExclusionTypeId<>1
            )       
        update NLP_DxCode set DxExclusionTypeId = 2 where AccountNumber = @AccountNumber and DxCode in ('D72.829','R50.9')

        /* any ITIS conditions which are not chronic (Except arthritis and osteoarthritis) --- no need to code */       
         Update NLP_DxCode set DxExclusionTypeId=2 from NLP_DxCode dx 
         inner join NLP_DxCodeByDocument dcd on dcd.AccountNumber=dx.AccountNumber
         where dcd.AccountNumber=@AccountNumber and AnnotationString like '%itis%' and Finding = 'Positive' and History='true'
         --and TConcept1 !=2 --Need to Review On Chronic Condition.... 
         and dx.DxExclusionTypeId<>1 and AnnotationString not like'%arthritis%'

        /*  if icdcode between 'K20' and 'k96' --- no need to code R10% series*/        
         if exists (
                select 1 from NLP_DxCode dx 
                inner join NLP_DxCodeByDocument dcd on dcd.AccountNumber=dx.AccountNumber
                where dcd.AccountNumber=@AccountNumber and dx.DxCode between 'K20' and 'K96' 
                and Finding = 'Positive' and DxExclusionTypeId<>1
            )
         Update NLP_DxCode set DxExclusionTypeId=2 where AccountNumber=@AccountNumber and DxCode like 'R10%'

        /* if F10.21(alcohol quit) code is there no need to code alcoholism*/
        if exists ( 
                select 1 from NLP_DxCode dx 
                inner join NLP_DxCodeByDocument dcd on dcd.AccountNumber=dx.AccountNumber
                where dcd.AccountNumber=@AccountNumber and dx.DxCode='F10.21' and Finding = 'Positive'
        )
        Update NLP_DxCode set DxExclusionTypeId=2 from NLP_DxCode dx 
        inner join NLP_DxCodeByDocument dcd on dcd.AccountNumber=dx.AccountNumber
        where dcd.AccountNumber=@AccountNumber and AnnotationString='alcoholism' and History='True'

        /*to clear Ambiguity b/w  history of CVA(Z86.73) and current CVA(I63.9) */
       if exists (     
                select 1 from NLP_DxCode dx 
                inner join NLP_DxCodeByDocument dcd on dcd.AccountNumber=dx.AccountNumber
                where dcd.AccountNumber=@AccountNumber and dx.DxCode='I63.9' and Finding = 'Positive'
                and (@DocumentType in ('ERR','H') and @DocumentType not in ('P','C','O','D'))--Verify Once
       )
       begin
             if exists (
                select 1 from NLP_DxCode dx 
                inner join NLP_DxCodeByDocument dcd on dcd.AccountNumber=dx.AccountNumber
                where dcd.AccountNumber=@AccountNumber and dx.DxCode='Z86.73' and Finding = 'Positive'
             )
             begin              
                Update NLP_DxCode set DxExclusionTypeId=0 where AccountNumber=@AccountNumber and DxCode='Z86.73'
                Update NLP_DxCode set DxExclusionTypeId=2 where AccountNumber=@AccountNumber and DxCode='I63.9'
             end 

        end         

    End Try
    Begin Catch 
        Exec usp_GetDBErrorInfo '<Input-Params>','NLP'
    End Catch
END
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:SYNC_InsertPatientDocument

Description:

Schema:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[SYNC_InsertPatientDocument]    Script Date: 06/21/2018 10:58:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SYNC_InsertPatientDocument]  
AS
begin
        Begin Try
        --Begin Transaction

        declare @startTime datetime
        declare @endTime datetime   
        declare @Phy_LastName VARCHAR(100)
        declare @Phy_MiddleName VARCHAR(100)
        declare @Phy_FirstName VARCHAR(100) 

        --select @startTime =convert(varchar,convert(datetime,enddate,121),121) from OTR_SyncProcess where SyncProcessID=1

        --IF(@startTime = '')
        --set @startTime='1900-01-01 00:00:00.0'

        declare InsertPatientDocument cursor for 
        select distinct top 50 rd.reportid,v.AccountNumber,v.MRN,wt.DocumentTypeID as DocumentTypeID,rd.AssignedDocumentAuthenticator,
        cast(stuff(stuff(left(rd.ActivityDateTime,12),9,0,' '),12,0,':')as datetime)as ActivityDateTime,
        cast(stuff(stuff(left(rd.OriginationDateTime,12),9,0,' '),12,0,':')as datetime)as OriginationDateTime,
        cast(stuff(stuff(left(rd.TranscriptionDateTime,12),9,0,' '),12,0,':')as datetime)as TranscriptionDateTime,      
        case when (rd.EditDateTime='' or rd.EditDateTime is null)
        then cast(stuff(stuff(left(rd.TranscriptionDateTime,12),9,0,' '),12,0,':')as datetime)
        else cast(stuff(stuff(left(rd.EditDateTime,12),9,0,' '),12,0,':')as datetime) end as EditDateTime,      
        rd.UniqueDocumentNumber,rd.ParentDocumentNumber,rd.UniqueDocumentFileName,dcs.DocumentCompletionStatusID,
        rd.InsertDate as InsertedDate,
        case when cast(v.AdmitDate as time) <='18:00:00' then DateAdd(day, Datediff(day, 0, v.AdmitDate) , 0)else DateAdd(day, Datediff(day, 0, v.AdmitDate)+1 , 0) end as AdmissionDay,
        rd.LastModify as ModifiedDate,rd.DocumentData as DocumentData,v.AdmitDate as AdmitDate      
        /*
        from [192.168.50.78].HPMCHL7.dbo.ReportsDPTEPIC rd 
        inner join [192.168.50.78].HPMCHL7.dbo.patients p on rd.PatientId = p.PatientId and p.SiteId=1
        inner join [192.168.50.78].HPMCHL7.dbo.Visits v on p.PatientId = v.PatientID  and rd.PatientVisitId = v.PatientVisitId and v.SiteId=1
        left join [192.168.50.78].HPMCHL7.dbo.HL7Insurance i on i.PatientId = p.PatientId and i.setId = 1 and i.SiteId=1 and
        i.PatientVisitId= case when exists (select 1 from [192.168.50.78].HPMCHL7.dbo.HL7Insurance where PatientVisitId=v.PatientVisitId and SetID=1) then      
        v.PatientVisitId
        else 0 end
        */
        from ReportsDPTEPIC78 rd 
        inner join patients78 p on rd.PatientId = p.PatientId and p.SiteId=1
        inner join Visits78 v on p.PatientId = v.PatientID  and rd.PatientVisitId = v.PatientVisitId and v.SiteId=1
        left join HL7Insurance78 i on i.PatientId = p.PatientId and i.setId = 1 and i.SiteId=1 and
        i.PatientVisitId= case when exists (select 1 from HL7Insurance78 where PatientVisitId=v.PatientVisitId and SetID=1) then
        v.PatientVisitId
        else 0 end
        left join MST_DocumentType wt on wt.DocumentMnemonic = rd.DocumentType
        left join MST_DocumentCompletionStatus dcs on dcs.DocumentCompletionStatus=isnull(rd.DocumentCompletionStatus,'DI')
        where rd.reportId in (40289374,40289883,40289950,40294778,40288346,40288674,40289239,40289250,40296963,40289428,40289923,40289421,40289966,40290228,40290229,40293933,40293981,40294902,40295517,40295538,40296050,40310547,40310655,40311689,40311698,40311903,40315122,40315124,40315703,40315705)
        and rd.DocumentData is not null and rd.DocumentData !='null' and rd.DocumentData !='' and rd.siteId=1 order by rd.LastModify
        /*
        where rd.DocumentData is not null and rd.DocumentData !='null' and rd.DocumentData !='' and rd.LastModify > @startTime
        and rd.siteId=1 order by rd.LastModify
        */

        declare @reportid int
        declare @AccountNumber varchar(25)
        declare @MRN varchar(25)
        declare @DocumentTypeID int
        declare @AssignedPhysicianId varchar(30)
        declare @ActivityDateTime datetime
        declare @OriginationDateTime datetime
        declare @TranscriptionDateTime datetime
        declare @EditDateTime datetime
        declare @UniqueDocumentNumber varchar(100)  
        declare @ParentDocumentNumber varchar(100)
        declare @UniqueDocumentFileName varchar(200)  
        declare @DocumentCompletionStatusID int     
        declare @InsertedDate datetime
        declare @AdmissionDay datetime
        declare @ModifiedDate datetime
        declare @DocumentData varchar(MAX)      
        declare @AdmitDate datetime

        open InsertPatientDocument      

        fetch next from InsertPatientDocument into @reportid,@AccountNumber,@MRN,@DocumentTypeID,@AssignedPhysicianId,@ActivityDateTime,
        @OriginationDateTime,@TranscriptionDateTime,@EditDateTime,@UniqueDocumentNumber,@ParentDocumentNumber,@UniqueDocumentFileName,
        @DocumentCompletionStatusID,@InsertedDate,@AdmissionDay,@ModifiedDate,@DocumentData,@AdmitDate

        while (@@fetch_Status<>-1)
        begin

            IF (@AssignedPhysicianId is not null)
            BEGIN
                    IF CHARINDEX('~',@AssignedPhysicianId,1)>0          
                    SET @AssignedPhysicianId=SUBSTRING(@AssignedPhysicianId,1,CHARINDEX('~',@AssignedPhysicianId)-1)

                    select top 1 @Phy_LastName=LastName,@Phy_FirstName=FirstName,@Phy_MiddleName=MiddleName
                    from MST_Physician where PhysicianId=@AssignedPhysicianId

                    --HIM_Physician Insertion Here...
                    If not exists(select 1 from HIM_Physician where PhysicianID=@AssignedPhysicianId)
                    begin
                        insert into HIM_Physician(PhysicianID,LastName,MiddleName,FirstName)values(@AssignedPhysicianId,@Phy_LastName,@Phy_MiddleName,@Phy_FirstName)
                    end
            END

            if exists(select DocumentID from dbo.HIM_Document where DocumentID= @reportid)
            begin
                Update HIM_Document set DocumentID=@reportid,AccountNumber=@AccountNumber,MRN=@MRN,DocumentTypeID=@DocumentTypeID,
                PhysicianID=@AssignedPhysicianId,ActivityDateTime=@ActivityDateTime,OriginationDateTime=@OriginationDateTime,
                TranscriptionDateTime=@TranscriptionDateTime,EditDateTime=@EditDateTime,UniqueDocumentNumber=@UniqueDocumentNumber,
                ParentDocumentNumber=@ParentDocumentNumber,UniqueDocumentFileName=@UniqueDocumentFileName,
                DocumentCompletionStatusID=@DocumentCompletionStatusID,DocumentRunningStatusID=0,ModifiedDate=GETDATE()
                where DocumentID= @reportid                     

                update dbo.HIM_DocumentData set DocumentID = @reportid,Document=@DocumentData where DocumentID= @reportid

                --HospitalDay Update Query          
                update dbo.HIM_Document set HospitalDay=case when DateAdd(day,Datediff(day,0,@TranscriptionDateTime),0)<DateAdd(day,Datediff(day,0,@AdmitDate),0) then 0
                when DATEDIFF(day,@AdmissionDay,@TranscriptionDateTime)<1 then 1 else DATEDIFF(day,@AdmissionDay,@TranscriptionDateTime)+1 end  
                where DocumentID= @reportid and @TranscriptionDateTime is not null and @AdmitDate is not null

            end
            else
            begin
                --Otherthan EPIC
                insert into dbo.HIM_Document(DocumentID,AccountNumber,MRN,DocumentTypeID,PhysicianID,ActivityDateTime,OriginationDateTime,TranscriptionDateTime,EditDateTime,
                UniqueDocumentNumber,ParentDocumentNumber,UniqueDocumentFileName,DocumentCompletionStatusID,DocumentRunningStatusID,InsertedDate,ModifiedDate)
                values(@reportid,@AccountNumber,@MRN,@DocumentTypeID,@AssignedPhysicianId,@ActivityDateTime,@OriginationDateTime,@TranscriptionDateTime,@EditDateTime,
                @UniqueDocumentNumber,@ParentDocumentNumber,@UniqueDocumentFileName,@DocumentCompletionStatusID,0,@InsertedDate,@Modifieddate)

                insert into dbo.HIM_DocumentData(DocumentID,Document)values(@reportid,@DocumentData)

                --HospitalDay Update Query          
                update dbo.HIM_Document set HospitalDay=case when DateAdd(day,Datediff(day,0,@TranscriptionDateTime),0)<DateAdd(day,Datediff(day,0,@AdmitDate),0) then 0
                when DATEDIFF(day,@AdmissionDay,@TranscriptionDateTime)<1 then 1 else DATEDIFF(day,@AdmissionDay,@TranscriptionDateTime)+1 end  
                where DocumentID= @reportid and @TranscriptionDateTime is not null and @AdmitDate is not null

            end             
        fetch next from InsertPatientDocument into @reportid,@AccountNumber,@MRN,@DocumentTypeID,@AssignedPhysicianId,@ActivityDateTime,
        @OriginationDateTime,@TranscriptionDateTime,@EditDateTime,@UniqueDocumentNumber,@ParentDocumentNumber,@UniqueDocumentFileName,
        @DocumentCompletionStatusID,@InsertedDate,@AdmissionDay,@ModifiedDate,@DocumentData,@AdmitDate
        select @endTime=convert(varchar,convert(datetime,@ModifiedDate,121),121)        

        end 

            --if(@endTime is not null and @endTime!='')
            --update OTR_SyncProcess set startdate =@startTime,enddate = @endTime,ModifiedDate=getDate() where SyncProcessID=1

        close InsertPatientDocument
        deallocate InsertPatientDocument

        --Commit Transaction

        End Try
        Begin Catch 
            --IF(@@TRANCOUNT>0)
            --Rollback Transaction  

            Exec usp_GetDBErrorInfo 'No Input Params','SYNC'
        End Catch

end

--Exec [SYNC_InsertPatientDocument]
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:SYNC_InsertPatientRADDocument

Description:

Schema:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[SYNC_InsertPatientRADDocument]    Script Date: 06/21/2018 10:58:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SYNC_InsertPatientRADDocument]  
AS
begin
        Begin Try
        --Begin Transaction

        declare @startTime datetime
        declare @endTime datetime   
        declare @Phy_LastName VARCHAR(100)
        declare @Phy_MiddleName VARCHAR(100)
        declare @Phy_FirstName VARCHAR(100) 
        declare @TEMP_AssignedPhysicianId VARCHAR(100)
        declare @PhysicianID VARCHAR(100)  


        --select @startTime =convert(varchar,convert(datetime,enddate,121),121) from OTR_SyncProcess where SyncProcessID=2

        --IF(@startTime = '')
        --set @startTime='1900-01-01 00:00:00.0'

        declare InsertPatientRADDocument cursor for         
        select distinct top 100 rd.reportid,v.AccountNumber,v.MRN,wt.DocumentTypeID as DocumentTypeID,
        rd.OrderingProvider as AssignedDocumentAuthenticator,
        cast(stuff(stuff(left(rd.RequestedDateTime,12),9,0,' '),12,0,':')as datetime)as ActivityDateTime,
        cast(stuff(stuff(left(rd.SpecimenReceivedDateTime,12),9,0,' '),12,0,':')as datetime)as OriginationDateTime,
        cast(stuff(stuff(left(rd.ObservationDateTime,12),9,0,' '),12,0,':')as datetime)as TranscriptionDateTime,
        case when (rd.ResultStatusChangeDateTime='' or rd.ResultStatusChangeDateTime is null) 
        then cast(stuff(stuff(left(rd.ObservationDateTime,12),9,0,' '),12,0,':')as datetime)
        else cast(stuff(stuff(left(rd.ResultStatusChangeDateTime,12),9,0,' '),12,0,':')as datetime) end as EditDateTime,
        rd.FillerOrderNumber as UniqueDocumentNumber,NULL as ParentDocumentNumber,NULL as UniqueDocumentFileName,
        dcs.DocumentCompletionStatusID,rd.InsertDate as InsertedDate,
        case when cast(v.AdmitDate as time) <='18:00:00' then DateAdd(day, Datediff(day, 0, v.AdmitDate) , 0)else DateAdd(day, Datediff(day, 0, v.AdmitDate)+1 , 0) end as AdmissionDay,
        rd.LastModify as ModifiedDate,CONVERT(varchar(max),rd.ReportData) as DocumentData,v.AdmitDate as AdmitDate
        from [192.168.50.78].HPMCHL7.dbo.reportsRadreports rd
        inner join [192.168.50.78].HPMCHL7.dbo.patients p on rd.PatientId = p.PatientId and p.SiteId=1
        inner join [192.168.50.78].HPMCHL7.dbo.Visits v on p.PatientId = v.PatientID  and rd.PatientVisitId = v.PatientVisitId and v.SiteId=1
        left join [192.168.50.78].HPMCHL7.dbo.HL7Insurance i on i.PatientId = p.PatientId and i.setId = 1 and i.SiteId=1 and
        i.PatientVisitId= case when exists (select 1 from [192.168.50.78].HPMCHL7.dbo.HL7Insurance where PatientVisitId=v.PatientVisitId and SetID=1) then
        v.PatientVisitId
        else 0 end
        left join MST_DocumentType wt on wt.DocumentMnemonic = rd.ReportType
        left join MST_DocumentCompletionStatus dcs on dcs.DocumentCompletionStatus='DI'     
        where rd.reportId in (115346,116073,131572,118535,118536,119388,119410,119787,119930,120170,120280,120362,123635,123085,123550,125029,123593,125774,126850,128281,133614)
        and rd.ReportData is not null and rd.ReportData !='null' and rd.ReportData !='' and rd.siteId=1 and rd.observationdatetime!='00000000000000' order by rd.LastModify
        /*
        where rd.ReportData is not null and rd.ReportData !='null' and rd.ReportData !='' and rd.LastModify > @startTime
        and rd.siteId=1 and rd.observationdatetime!='00000000000000' order by rd.LastModify
        */

        declare @reportid int
        declare @AccountNumber varchar(25)
        declare @MRN varchar(25)
        declare @DocumentTypeID int
        declare @AssignedPhysicianId varchar(50)
        declare @ActivityDateTime datetime
        declare @OriginationDateTime datetime
        declare @TranscriptionDateTime datetime
        declare @EditDateTime datetime
        declare @UniqueDocumentNumber varchar(100)  
        declare @ParentDocumentNumber varchar(100)
        declare @UniqueDocumentFileName varchar(200)  
        declare @DocumentCompletionStatusID int     
        declare @InsertedDate datetime
        declare @AdmissionDay datetime
        declare @ModifiedDate datetime
        declare @DocumentData varchar(MAX)      
        declare @AdmitDate datetime

        open InsertPatientRADDocument

        fetch next from InsertPatientRADDocument into @reportid,@AccountNumber,@MRN,@DocumentTypeID,@AssignedPhysicianId,@ActivityDateTime,
        @OriginationDateTime,@TranscriptionDateTime,@EditDateTime,@UniqueDocumentNumber,@ParentDocumentNumber,@UniqueDocumentFileName,
        @DocumentCompletionStatusID,@InsertedDate,@AdmissionDay,@ModifiedDate,@DocumentData,@AdmitDate

        while (@@fetch_Status<>-1)
        begin

            SET @TEMP_AssignedPhysicianId=NULL
            SET @PhysicianID=NULL
            SET @Phy_LastName=NULL
            SET @Phy_FirstName=NULL
            SET @Phy_MiddleName=NULL
            SET @TEMP_AssignedPhysicianId=@AssignedPhysicianId

            --PARSE @DoctorId
            IF CHARINDEX('^',@TEMP_AssignedPhysicianId,1)>0 
            BEGIN   
                SET @PhysicianID=SUBSTRING(@TEMP_AssignedPhysicianId,1,CHARINDEX('^',@TEMP_AssignedPhysicianId)-1)
                SET @TEMP_AssignedPhysicianId=SUBSTRING(@TEMP_AssignedPhysicianId,CHARINDEX('^',@TEMP_AssignedPhysicianId)+1,LEN(@TEMP_AssignedPhysicianId))
            END
            ELSE
            BEGIN
                SET @PhysicianID=@TEMP_AssignedPhysicianId
                SET @TEMP_AssignedPhysicianId=NULL
            END
            /*
            --PARSE @LatName
            IF CHARINDEX('^',@TEMP_AssignedPhysicianId,1)>0 
            BEGIN   
                SET @Phy_LastName=SUBSTRING(@TEMP_AssignedPhysicianId,1,CHARINDEX('^',@TEMP_AssignedPhysicianId)-1)
                SET @TEMP_AssignedPhysicianId=SUBSTRING(@TEMP_AssignedPhysicianId,CHARINDEX('^',@TEMP_AssignedPhysicianId)+1,LEN(@TEMP_AssignedPhysicianId))
            END
            ELSE
            BEGIN
                SET @Phy_LastName=@TEMP_AssignedPhysicianId
                SET @TEMP_AssignedPhysicianId=NULL
            END

            --PARSE @FirstName
            IF CHARINDEX('^',@TEMP_AssignedPhysicianId,1)>0 
            BEGIN   
                SET @Phy_FirstName=SUBSTRING(@TEMP_AssignedPhysicianId,1,CHARINDEX('^',@TEMP_AssignedPhysicianId)-1)
                SET @TEMP_AssignedPhysicianId=SUBSTRING(@TEMP_AssignedPhysicianId,CHARINDEX('^',@TEMP_AssignedPhysicianId)+1,LEN(@TEMP_AssignedPhysicianId))
            END
            ELSE
            BEGIN
                SET @Phy_FirstName=@TEMP_AssignedPhysicianId
                SET @TEMP_AssignedPhysicianId=NULL
            END
            */
            IF(@PhysicianID='')
            SET @PhysicianID=NULL

            IF (@PhysicianID is not null)
            BEGIN
                    select top 1 @Phy_LastName=LastName,@Phy_FirstName=FirstName,@Phy_MiddleName=MiddleName
                    from MST_Physician where PhysicianId=@PhysicianID

                    --HIM_Physician Insertion Here...
                    If not exists(select 1 from HIM_Physician where PhysicianID=@PhysicianID)
                    begin
                        insert into HIM_Physician(PhysicianID,LastName,MiddleName,FirstName)values(@PhysicianID,@Phy_LastName,@Phy_MiddleName,@Phy_FirstName)
                    end
            END

            if exists(select DocumentID from dbo.HIM_Document where DocumentID= @reportid)
            begin
                --Otherthan EPIC Documents
                Update HIM_Document set DocumentID=@reportid,AccountNumber=@AccountNumber,MRN=@MRN,DocumentTypeID=@DocumentTypeID,
                PhysicianID=@PhysicianID,ActivityDateTime=@ActivityDateTime,OriginationDateTime=@OriginationDateTime,
                TranscriptionDateTime=@TranscriptionDateTime,EditDateTime=@EditDateTime,UniqueDocumentNumber=@UniqueDocumentNumber,
                ParentDocumentNumber=@ParentDocumentNumber,UniqueDocumentFileName=@UniqueDocumentFileName,
                DocumentCompletionStatusID=@DocumentCompletionStatusID,DocumentRunningStatusID=0,ModifiedDate=GETDATE()
                where DocumentID= @reportid         

                update dbo.HIM_DocumentData set DocumentID = @reportid,Document=@DocumentData where DocumentID= @reportid

                --HospitalDay Update Query          
                update dbo.HIM_Document set HospitalDay=case when DateAdd(day,Datediff(day,0,@TranscriptionDateTime),0)<DateAdd(day,Datediff(day,0,@AdmitDate),0) then 0
                when DATEDIFF(day,@AdmissionDay,@TranscriptionDateTime)<1 then 1 else DATEDIFF(day,@AdmissionDay,@TranscriptionDateTime)+1 end  
                where DocumentID= @reportid and @TranscriptionDateTime is not null and @AdmitDate is not null               
            end
            else
            begin
                --Otherthan EPIC
                insert into dbo.HIM_Document(DocumentID,AccountNumber,MRN,DocumentTypeID,PhysicianID,ActivityDateTime,OriginationDateTime,TranscriptionDateTime,EditDateTime,
                UniqueDocumentNumber,ParentDocumentNumber,UniqueDocumentFileName,DocumentCompletionStatusID,DocumentRunningStatusID,InsertedDate,ModifiedDate)
                values(@reportid,@AccountNumber,@MRN,@DocumentTypeID,@PhysicianID,@ActivityDateTime,@OriginationDateTime,@TranscriptionDateTime,@EditDateTime,
                @UniqueDocumentNumber,@ParentDocumentNumber,@UniqueDocumentFileName,@DocumentCompletionStatusID,0,@InsertedDate,@Modifieddate)

                insert into dbo.HIM_DocumentData(DocumentID,Document)values(@reportid,@DocumentData)

                --HospitalDay Update Query          
                update dbo.HIM_Document set HospitalDay=case when DateAdd(day,Datediff(day,0,@TranscriptionDateTime),0)<DateAdd(day,Datediff(day,0,@AdmitDate),0) then 0
                when DATEDIFF(day,@AdmissionDay,@TranscriptionDateTime)<1 then 1 else DATEDIFF(day,@AdmissionDay,@TranscriptionDateTime)+1 end  
                where DocumentID= @reportid and @TranscriptionDateTime is not null and @AdmitDate is not null               
            end             
        fetch next from InsertPatientRADDocument into @reportid,@AccountNumber,@MRN,@DocumentTypeID,@AssignedPhysicianId,@ActivityDateTime,
        @OriginationDateTime,@TranscriptionDateTime,@EditDateTime,@UniqueDocumentNumber,@ParentDocumentNumber,@UniqueDocumentFileName,
        @DocumentCompletionStatusID,@InsertedDate,@AdmissionDay,@ModifiedDate,@DocumentData,@AdmitDate      
                select @endTime=convert(varchar,convert(datetime,@ModifiedDate,121),121)                    
        end 

            --if(@endTime is not null and @endTime!='')
            --update OTR_SyncProcess set startdate =@startTime,enddate = @endTime,ModifiedDate=getDate() where SyncProcessID=2

        close InsertPatientRADDocument
        deallocate InsertPatientRADDocument

        --Commit Transaction

        End Try
        Begin Catch 
            --IF(@@TRANCOUNT>0)
            --Rollback Transaction  

            Exec usp_GetDBErrorInfo 'No Input Params','SYNC'
        End Catch

end
--Exec SYNC_InsertPatientRADDocument
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:SYNC_InsertPatientVisitData

Description:

Schema:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[SYNC_InsertPatientVisitData]    Script Date: 06/21/2018 10:58:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SYNC_InsertPatientVisitData]
AS
begin
        Begin Try
        --Begin Transaction

        declare @startTime datetime
        declare @endTime datetime
        select @startTime =convert(varchar,convert(datetime,enddate,121),121) from OTR_SyncProcess where SyncProcessID=3

        IF(@startTime = '')
        set @startTime='1900-01-01 00:00:00.0'

        declare InsertPatientVisitData cursor for 
        select top 50 AccountNumber,AttendingDoctor,AdmittingDoctor,ReferringDoctor,ConsultingDoctor,LastModify 
        from [192.168.50.78].HPMCHL7.dbo.Visits where LastModify > @startTime and SiteId=1 order by lastmodify

        declare @AccountNumber varchar(50)
        declare @AttendingDoctor varchar(100)
        declare @AdmittingDoctor varchar(100)
        declare @ReferringDoctor varchar(100)
        declare @ConsultingDoctor varchar(500)
        declare @LastModify datetime
        declare @Phy_LastName VARCHAR(100)
        declare @Phy_MiddleName VARCHAR(100)
        declare @Phy_FirstName VARCHAR(100)
        declare @PhysicinaID varchar(50)

        open InsertPatientVisitData

        fetch next from InsertPatientVisitData into @AccountNumber,@AttendingDoctor,@AdmittingDoctor,@ReferringDoctor,@ConsultingDoctor,@LastModify

        while (@@fetch_Status<>-1)
        begin
            if(@AttendingDoctor is not null and @AttendingDoctor!='')
            begin                           
                IF CHARINDEX('^',@AttendingDoctor,1)>0          
                SET @PhysicinaID=SUBSTRING(@AttendingDoctor,1,CHARINDEX('^',@AttendingDoctor)-1)

                select top 1 @Phy_LastName=LastName,@Phy_FirstName=FirstName,@Phy_MiddleName=MiddleName
                from MST_Physician where PhysicianId=@PhysicinaID

                --HIM_Physician Insertion Here...
                If not exists(select 1 from HIM_Physician where PhysicianID=@PhysicinaID)
                begin
                    insert into HIM_Physician(PhysicianID,LastName,MiddleName,FirstName)values(@PhysicinaID,@Phy_LastName,@Phy_MiddleName,@Phy_FirstName)
                end             
                --HIM_Physician_Visit(PhysicianDetails) Insertion Here
                Update HIM_Physician_Visit set Active=0 where AccountNumber=@AccountNumber and PhysicianTypeID=1
                insert into HIM_Physician_Visit(AccountNumber,PhysicianID,PhysicianTypeID,PhysicianTypeDesc)
                values(@AccountNumber,@PhysicinaID,1,'AttendingDoctor')             
            end

            if(@AdmittingDoctor is not null and @AdmittingDoctor!='')
            begin
                IF CHARINDEX('^',@AdmittingDoctor,1)>0          
                SET @PhysicinaID=SUBSTRING(@AdmittingDoctor,1,CHARINDEX('^',@AdmittingDoctor)-1)

                select top 1 @Phy_LastName=LastName,@Phy_FirstName=FirstName,@Phy_MiddleName=MiddleName
                from MST_Physician where PhysicianId=@PhysicinaID

                --HIM_Physician Insertion Here...
                If not exists(select 1 from HIM_Physician where PhysicianID=@PhysicinaID)
                begin
                    insert into HIM_Physician(PhysicianID,LastName,MiddleName,FirstName)values(@PhysicinaID,@Phy_LastName,@Phy_MiddleName,@Phy_FirstName)
                end

                --HIM_Physician_Visit(PhysicianDetails) Insertion Here
                Update HIM_Physician_Visit set Active=0 where AccountNumber=@AccountNumber and PhysicianTypeID=2
                insert into HIM_Physician_Visit(AccountNumber,PhysicianID,PhysicianTypeID,PhysicianTypeDesc)
                values(@AccountNumber,@PhysicinaID,2,'AdmittingDoctor')
            end

            if(@ReferringDoctor is not null and @ReferringDoctor!='')
            begin
                IF CHARINDEX('^',@ReferringDoctor,1)>0          
                SET @PhysicinaID=SUBSTRING(@ReferringDoctor,1,CHARINDEX('^',@ReferringDoctor)-1)

                select top 1 @Phy_LastName=LastName,@Phy_FirstName=FirstName,@Phy_MiddleName=MiddleName
                from MST_Physician where PhysicianId=@PhysicinaID

                --HIM_Physician Insertion Here...
                If not exists(select 1 from HIM_Physician where PhysicianID=@PhysicinaID)
                begin
                    insert into HIM_Physician(PhysicianID,LastName,MiddleName,FirstName)values(@PhysicinaID,@Phy_LastName,@Phy_MiddleName,@Phy_FirstName)
                end

                --HIM_Physician_Visit(PhysicianDetails) Insertion Here
                Update HIM_Physician_Visit set Active=0 where AccountNumber=@AccountNumber and PhysicianTypeID=3
                insert into HIM_Physician_Visit(AccountNumber,PhysicianID,PhysicianTypeID,PhysicianTypeDesc)
                values(@AccountNumber,@PhysicinaID,3,'ReferringDoctor')

            end

            if(@ConsultingDoctor is not null and @ConsultingDoctor!='')
            begin
            IF CHARINDEX('^',@ConsultingDoctor,1)>0             
                SET @PhysicinaID=SUBSTRING(@ConsultingDoctor,1,CHARINDEX('^',@ConsultingDoctor)-1)

                select top 1 @Phy_LastName=LastName,@Phy_FirstName=FirstName,@Phy_MiddleName=MiddleName
                from MST_Physician where PhysicianId=@PhysicinaID

                --HIM_Physician Insertion Here...
                If not exists(select 1 from HIM_Physician where PhysicianID=@PhysicinaID)
                begin
                    insert into HIM_Physician(PhysicianID,LastName,MiddleName,FirstName)values(@PhysicinaID,@Phy_LastName,@Phy_MiddleName,@Phy_FirstName)
                end

                --HIM_Physician_Visit(PhysicianDetails) Insertion Here
                Update HIM_Physician_Visit set Active=0 where AccountNumber=@AccountNumber and PhysicianTypeID=4
                insert into HIM_Physician_Visit(AccountNumber,PhysicianID,PhysicianTypeID,PhysicianTypeDesc)
                values(@AccountNumber,@PhysicinaID,4,'ConsultingDoctor')

            end

        fetch next from InsertPatientVisitData into @AccountNumber,@AttendingDoctor,@AdmittingDoctor,@ReferringDoctor,@ConsultingDoctor,@LastModify
        select @endTime=convert(varchar,convert(datetime,@LastModify,121),121)

        end

        close InsertPatientVisitData
        deallocate InsertPatientVisitData

        if(@endTime is not null and @endTime!='')
        update OTR_SyncProcess set startdate =@startTime,enddate = @endTime,ModifiedDate=getDate() where SyncProcessID=3

        --HIM_Patient
        Update HIM_Patient set PatientId=s.PatientId,MRN=s.InternalPatientID,FirstName=s.PatientFirstName,MiddleName=s.PatientMiddleName,
        LastName=s.PatientLastName,PatientAddress=s.Patientaddress,
        RaceID=case when CHARINDEX('^',s.Race,1)>0 then SUBSTRING(s.Race,1,CHARINDEX('^',s.Race)-1)else s.Race end,
        Race=s.Race,DOB=s.DOB,Gender=s.Sex,PrimaryLanguage=s.PrimaryLanguage,
        MaritalStatus=s.MaritalStatus,Religion=s.Religion,SSNNumber=s.SSNNumber,InsertedDate=s.InsertDate,ModifiedDate=s.LastModify
        from HIM_Patient L
        inner join [192.168.50.78].HPMCHL7.dbo.Patients s on L.PatientId=s.PatientId
        where s.lastmodify between @startTime and @endTime

        Insert into HIM_Patient(PatientId,MRN,FirstName,MiddleName,LastName,PatientAddress,RaceID,Race,DOB,Gender,PrimaryLanguage,MaritalStatus,Religion,
        SSNNumber,InsertedDate,ModifiedDate)
        select PatientId,InternalPatientID,PatientFirstName,PatientMiddleName,PatientLastName,PatientAddress,
        case when CHARINDEX('^',Race,1)>0 then SUBSTRING(Race,1,CHARINDEX('^',Race)-1)else Race end as RaceID,Race,DOB,Sex,PrimaryLanguage,MaritalStatus,
        Religion,SSNNumber,InsertDate,LastModify
        from [192.168.50.78].HPMCHL7.dbo.Patients where PatientId not in (select distinct PatientId from HIM_Patient)

        --HIM_Visit     
        Update HIM_Visit set VisitID=s.PatientVisitId,PatientID=s.PatientID,AccountNumber=s.AccountNumber,MRN=s.MRN,PatientClass=s.PatientClass,
        AdmitDate=s.AdmitDate,DischargeDate=s.DischargeDate,LocationID=s.PLoc_ID,LocationRoom=s.PLoc_Room,LocationBed=s.PLoc_Bed,
        AdmissionType=s.AdmissionType,HospitalService=s.HospitalService,AdmitSource=s.AdmitSource,PatientType=s.PatientType,VIPIndicator=s.VIPIndicator,
        FinancialClass=s.FinancialClass,DischargeDisposition=s.DischargeDisposition,ReasonForVisit=s.ReasonForVisit,
        AdmissionDay=case when cast(S.AdmitDate as time) <='18:00:00' then DateAdd(day, Datediff(day, 0, S.AdmitDate) , 0)
        else DateAdd(day, Datediff(day, 0, S.AdmitDate)+1 , 0) end,InsertedDate=s.Insertdate,ModifiedDate=s.LastModify
        from HIM_Visit L
        inner join [192.168.50.78].HPMCHL7.dbo.Visits s on L.AccountNumber=s.AccountNumber and L.VisitID=s.PatientVisitId and L.PatientID=s.PatientID
        where s.lastmodify between @startTime and @endTime

        Insert into HIM_Visit(VisitID,PatientID,AccountNumber,MRN,PatientClass,AdmitDate,DischargeDate,LocationID,LocationRoom,LocationBed,AdmissionType,
        HospitalService,AdmitSource,PatientType,VIPIndicator,FinancialClass,DischargeDisposition,ReasonForVisit,AdmissionDay,InsertedDate,ModifiedDate)
        select PatientVisitId,PatientID,AccountNumber,MRN,PatientClass,AdmitDate,DischargeDate,PLoc_ID,PLoc_Room,PLoc_Bed,AdmissionType,
        HospitalService,AdmitSource,PatientType,VIPIndicator,FinancialClass,DischargeDisposition,ReasonForVisit,
        case when cast(AdmitDate as time) <='18:00:00' then DateAdd(day, Datediff(day, 0, AdmitDate) , 0)
        else DateAdd(day, Datediff(day, 0, AdmitDate)+1 , 0) end AdmissionDay,Insertdate,LastModify
        from [192.168.50.78].HPMCHL7.dbo.Visits where PatientVisitId not in (select distinct VisitID from HIM_Visit)
        --where AccountNumber not in (select distinct AccountNumber from HIM_Visit)

        Update HIM_Visit set CancelVisit=1 where VisitID in (select distinct PatientVisitId from [192.168.50.78].HPMCHL7.dbo.CancelVisits)

        --HIM_Insurance
        delete from HIM_Insurance where InsuranceId not in (select InsuranceId from [192.168.50.78].HPMCHL7.dbo.HL7Insurance)

        Insert into HIM_Insurance(InsuranceID,PatientID,VisitID,AccountNumber,SetID,InsurancePlanID,InsuranceCompanyID,InsuranceCompanyName,
        PlanEffectiveDate,PlanEndDate,FinalStatus,InsertedDate,ModifiedDate)        
        select i.InsuranceId,i.PatientId,i.PatientVisitId,v.AccountNumber,i.SetID,i.InsurancePlanID,i.InsuranceCompanyID,i.InsuranceCompanyName,
        i.PlanEffectiveDate,i.PlanExpirationDate,i.isFinal,i.InsertDate,i.LastModify
        from [192.168.50.78].HPMCHL7.dbo.Visits v
        left join [192.168.50.78].HPMCHL7.dbo.CancelVisits cv on cv.PatientVisitId=v.PatientVisitId
        left join [192.168.50.78].HPMCHL7.dbo.HL7Insurance i on v.PatientID=i.PatientId and i.SetID=1 and i.SiteId=1 and
        i.PatientVisitId= case when exists (select 1 from [192.168.50.78].HPMCHL7.dbo.HL7Insurance where PatientVisitId=v.PatientVisitId and SetID=1) then
        v.PatientVisitId else 0 end 
        where cv.PatientVisitId is null and i.PatientVisitId<>0 and i.InsuranceId not in (select distinct InsuranceId from HIM_Insurance)

        --HIM_DXCode
        delete from HIM_DXCode where AccountNumber in(
        select distinct V.AccountNumber from [192.168.50.78].HPMCHL7.dbo.HL7Diagnosis d
        inner join [192.168.50.78].HPMCHL7.dbo.Visits V on V.Patientvisitid=d.Patientvisitid and d.[Status]=1 
        where d.lastmodify between @startTime and @endTime)

        insert into HIM_DXCode(AccountNumber,DXCode,DXDesc,DXType,DXPriority,DXDate,UserName,InsertedDate,ModifiedDate)
        Select distinct V.AccountNumber,dxcode,dxdescription,d.DxType,d.SetId,cast(stuff(stuff(left(d.DXDate,12),9,0,' '),12,0,':')as datetime) as DXDate,
        d.oprId,d.InsertDate,d.LastModify
        from [192.168.50.78].HPMCHL7.dbo.HL7Diagnosis d 
        inner join [192.168.50.78].HPMCHL7.dbo.Visits V on d.Patientvisitid=V.Patientvisitid and d.Status=1
        where d.lastmodify between @startTime and @endTime order by V.AccountNumber,d.SetId 

        --HIM_PCSCode
        delete from HIM_PCSCode where AccountNumber in(
        select distinct V.AccountNumber from [192.168.50.78].HPMCHL7.dbo.HL7Procedure p
        inner join [192.168.50.78].HPMCHL7.dbo.Visits V on V.Patientvisitid=p.Patientvisitid and p.[Status]=1 
        where p.lastmodify between @startTime and @endTime)

        insert into HIM_PCSCode(AccountNumber,PCSCode,PCSDesc,PCSType,PCSPriority,PCSDate,UserName,InsertedDate,ModifiedDate)
        select distinct V.AccountNumber,PxCode,PxDescription,case when p.SetId=1 then 'P' else 'S' end as PXType,p.SetID,
        cast(stuff(stuff(left(p.PxDateTime,12),9,0,' '),12,0,':')as datetime) as PXDateTime,p.oprId,p.InsertDate,p.LastModify
        from [192.168.50.78].HPMCHL7.dbo.HL7Procedure P 
        inner join [192.168.50.78].HPMCHL7.dbo.Visits V on P.Patientvisitid=V.Patientvisitid and p.Status=1
        where p.lastmodify between @startTime and @endTime order by V.AccountNumber,p.SetId

        --POA Update From FTP_DXCode To HIM_DXCode
        update HIM_DXCode set POA=fdx.POA from HIM_DXCode hdx
        inner join FTP_DXCode fdx on fdx.AccountNumber=hdx.AccountNumber and fdx.DXCode=hdx.DXCode
        where hdx.POA is null

        --Commit Transaction

        End Try
        Begin Catch 
            --IF(@@TRANCOUNT>0)
            --Rollback Transaction      
            Exec usp_GetDBErrorInfo 'No Input Params','SYNC'
        End Catch

end
--Exec SYNC_InsertPatientVisitData
GO

ChangeLog:

======================================================

DataBase Name:HRCM

Procedure Name:usp_GetDBErrorInfo

Description:

Schema:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
USE [HRCM]
GO
/****** Object:  StoredProcedure [dbo].[usp_GetDBErrorInfo]    Script Date: 06/21/2018 10:58:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[usp_GetDBErrorInfo]  
@ErrorSchemaParam varchar(1000),
@ErrorApplicationParam varchar(20)
AS 
Declare @ErrorNumber INT;
Declare @ErrorState INT;
Declare @ErrorSeverity INT;
Declare @ErrorMessage VARCHAR(4000);
Declare @ErrorProcedureName VARCHAR(128);
Declare @Message varchar(500);
Declare @NewLine AS CHAR(2) = CHAR(13) + CHAR(10);

BEGIN   
    SET @ErrorNumber=ERROR_NUMBER()
    SET @ErrorState=ERROR_STATE()
    SET @ErrorSeverity=ERROR_SEVERITY()
    SET @ErrorMessage=ERROR_MESSAGE()
    SET @ErrorProcedureName=ERROR_PROCEDURE()

    --LOG Insertion
    insert into DBError(ErrorNumber,ErrorState,ErrorMessage,ErrorProcedureName,ErrorSchema,ErrorApplication)
    values(@ErrorNumber,@ErrorState,@ErrorMessage,@ErrorProcedureName,@ErrorSchemaParam,@ErrorApplicationParam)

    /*
    --DBMail Configuration  
    SET @Message='Hi ALL,'+@NewLine+@NewLine+'Getting DBSchema ErrorMessage For HRCM In DBError Table.'+@NewLine+@NewLine+'-------------****************-------------'+@NewLine++@NewLine+
    'ErrorMessage: '+REPLACE(@ErrorMessage,'''','''')+@NewLine++@NewLine+
    'ProcedureName: '+ISNULL(@ErrorProcedureName,'')+@NewLine+@NewLine+'Regards,'+@NewLine+'DB JOB Alerts'+@NewLine+'KPAI Team.'

    exec msdb.dbo.sp_send_dbmail 'dbmail_profile','krishnareddyn@kpmd.biz;srinivasavula@kpmd.biz',null,null,
    'DBErrorMessage',@Message,'text','normal','normal',null,null,null,0,260,1,256,' ',0,0,0,0,null,null,null
    */

    --Send an ErrorInfo to Calling Application
    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State.
               );
END
GO