3. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 1/31/2018 9:02:08 AM Central Standard Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.

3.1 Files compared

# Location File Last Modified
1 NVCC_2.2_01162018.zip\NVCC\Database\bin\Debug Database.sql Fri Nov 3 19:53:05 2017 UTC
2 NVCC_2.2_01162018.zip\NVCC\Database\bin\Debug Database.sql Mon Jan 29 17:22:07 2018 UTC

3.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 8 7878
Changed 7 20
Inserted 0 0
Removed 0 0

3.3 Comparison options

Whitespace
Character case Differences in character case are significant
Line endings Differences in line endings (CR and LF characters) are ignored
CR/LF characters Not shown in the comparison detail

3.4 Active regular expressions

No regular expressions were active.

3.5 Comparison detail

  1   /*
  2   Deployment  script fo r Database
  3  
  4   This code  was genera ted by a t ool.
  5   Changes to  this file  may cause  incorrect  behavior  and will b e lost if
  6   the code i s regenera ted.
  7   */
  8  
  9   GO
  10   SET ANSI_N ULLS, ANSI _PADDING,  ANSI_WARNI NGS, ARITH ABORT, CON CAT_NULL_Y IELDS_NULL , QUOTED_I DENTIFIER  ON;
  11  
  12   SET NUMERI C_ROUNDABO RT OFF;
  13  
  14  
  15   GO
  16   :setvar Da tabaseName  "Database "
  17   :setvar De faultFileP refix "Dat abase"
  18   :setvar De faultDataP ath "C:\Us ers\ US E R \AppData\L ocal\Micro soft\Visua lStudio\SS DT\NVCC"
  19   :setvar De faultLogPa th "C:\Use rs\ US E R \AppData\L ocal\Micro soft\Visua lStudio\SS DT\NVCC"
  20  
  21   GO
  22   :on error  exit
  23   GO
  24   /*
  25   Detect SQL CMD mode a nd disable  script ex ecution if  SQLCMD mo de is not  supported.
  26   To re-enab le the scr ipt after  enabling S QLCMD mode , execute  the follow ing:
  27   SET NOEXEC  OFF; 
  28   */
  29   :setvar __ IsSqlCmdEn abled "Tru e"
  30   GO
  31   IF N'$(__I sSqlCmdEna bled)' NOT  LIKE N'Tr ue'
  32       BEGIN
  33           PR INT N'SQLC MD mode mu st be enab led to suc cessfully  execute th is script. ';
  34           SE T NOEXEC O N;
  35       END
  36  
  37  
  38   GO
  39   USE [$(Dat abaseName) ];
  40  
  41  
  42   GO
  43   PRINT N'Cr eating [Ap p].[NVCC_A ccessLog]. ..';
  44  
  45  
  46   GO
  47   CREATE TAB LE [App].[ NVCC_Acces sLog] (
  48       [Acces sLogID]         INT            I DENTITY (1 , 1) NOT N ULL,
  49       [HostN ame]            VARCH AR (80)  N ULL,
  50       [UserI D]              VARCH AR (50)  N ULL,
  51       [Acces sDateTime]      DATET IME      N ULL,
  52       [Actio n]              VARCH AR (255) N ULL,
  53       [Patie ntSID]          INT            N ULL,
  54       [Elaps edTime]         FLOAT  (53)    N ULL,
  55       [Datab aseServerN ame] VARCH AR (50)  N ULL,
  56       CONSTR AINT [PK_A pp_NVCCAcc essLog] PR IMARY KEY  NONCLUSTER ED ([Acces sLogID] AS C) WITH (D ATA_COMPRE SSION = PA GE)
  57   );
  58  
  59  
  60   GO
  61   PRINT N'Cr eating [Ap p].[NVCC_A ccessLog]. [NVCC_Acce ssLog_Host Name_UserI D_AccessDa teTime]... ';
  62  
  63  
  64   GO
  65   CREATE CLU STERED IND EX [NVCC_A ccessLog_H ostName_Us erID_Acces sDateTime]
  66       ON [Ap p].[NVCC_A ccessLog]( [UserID] A SC, [HostN ame] ASC,  [AccessDat eTime] ASC ) WITH (DA TA_COMPRES SION = PAG E);
  67  
  68  
  69   GO
  70   PRINT N'Cr eating [Ap p].[NVCC_A nnouncemen t]...';
  71  
  72  
  73   GO
  74   CREATE TAB LE [App].[ NVCC_Annou ncement] (
  75       [Annou ncementID]      INT               IDENTITY  (1, 1) NOT  NULL,
  76       [Annou ncementTyp eID] INT               NOT NULL,
  77       [Creat or]             VARCH AR (50)     NOT NULL,
  78       [Creat ionDT]          DATET IME2 (7)    NOT NULL,
  79       [Expir ationDT]        DATET IME2 (7)    NULL,
  80       [Text]                 NVARC HAR (4000)  NULL,
  81       CONSTR AINT [PK_A pp_NVCC_An nouncement ] PRIMARY  KEY CLUSTE RED ([Anno uncementID ] ASC) WIT H (DATA_CO MPRESSION  = PAGE)
  82   );
  83  
  84  
  85   GO
  86   PRINT N'Cr eating [Ap p].[NVCC_A nnouncemen t].[Announ cementType ID_Announc ement]...' ;
  87  
  88  
  89   GO
  90   CREATE NON CLUSTERED  INDEX [Ann ouncementT ypeID_Anno uncement]
  91       ON [Ap p].[NVCC_A nnouncemen t]([Announ cementType ID] ASC) W ITH (DATA_ COMPRESSIO N = PAGE);
  92  
  93  
  94   GO
  95   PRINT N'Cr eating [Ap p].[NVCC_A nnouncemen t].[Exipra tionDT_Ann ouncement] ...';
  96  
  97  
  98   GO
  99   CREATE NON CLUSTERED  INDEX [Exi prationDT_ Announceme nt]
  100       ON [Ap p].[NVCC_A nnouncemen t]([Expira tionDT] AS C) WITH (D ATA_COMPRE SSION = PA GE);
  101  
  102  
  103   GO
  104   PRINT N'Cr eating [Ap p].[NVCC_D imAnnounce ment]...';
  105  
  106  
  107   GO
  108   CREATE TAB LE [App].[ NVCC_DimAn nouncement ] (
  109       [Annou ncementTyp eID] INT            N OT NULL,
  110       [Annou ncementTyp e]   NVARC HAR (20) N ULL,
  111       CONSTR AINT [PK_A pp_NVCC_Di mAnnouncem ent] PRIMA RY KEY CLU STERED ([A nnouncemen tTypeID] A SC) WITH ( DATA_COMPR ESSION = P AGE)
  112   );
  113  
  114  
  115   GO
  116   PRINT N'Cr eating [Ap p].[NVCC_H IPAATerms] ...';
  117  
  118  
  119   GO
  120   CREATE TAB LE [App].[ NVCC_HIPAA Terms] (
  121       [term]  VARCHAR ( 35) NOT NU LL,
  122       CONSTR AINT [PK_A pp_NVCC_HI PAATerms]  PRIMARY KE Y CLUSTERE D ([term]  ASC) WITH  (DATA_COMP RESSION =  PAGE)
  123   );
  124  
  125  
  126   GO
  127   PRINT N'Cr eating [Ap p].[NVCC_P roductionL og]...';
  128  
  129  
  130   GO
  131   CREATE TAB LE [App].[ NVCC_Produ ctionLog]  (
  132       [Acces sLogID]     INT           NOT NU LL,
  133       [UserI D]          VARCHAR ( 50) NOT NU LL,
  134       [Acces sDateTime]  DATETIME      NOT NU LL,
  135       [Patie ntSID]      INT           NOT NU LL,
  136       [Patie ntICN]      VARCHAR ( 50) NULL,
  137       [Sta3n ]           SMALLINT      NOT NU LL
  138   );
  139  
  140  
  141   GO
  142   PRINT N'Cr eating [Ap p].[NVCC_P roductionL og].[NVCC_ Production Log_Access DateTime_U serID]...' ;
  143  
  144  
  145   GO
  146   CREATE CLU STERED IND EX [NVCC_P roductionL og_AccessD ateTime_Us erID]
  147       ON [Ap p].[NVCC_P roductionL og]([Acces sDateTime]  ASC, [Use rID] ASC)  WITH (DATA _COMPRESSI ON = PAGE) ;
  148  
  149  
  150   GO
  151   PRINT N'Cr eating [Ap p].[NVCC_P roductionL og].[NVCC_ Production Log_Sta3n] ...';
  152  
  153  
  154   GO
  155   CREATE NON CLUSTERED  INDEX [NVC C_Producti onLog_Sta3 n]
  156       ON [Ap p].[NVCC_P roductionL og]([Sta3n ] ASC)
  157       INCLUD E([Patient ICN]) WITH  (DATA_COM PRESSION =  PAGE);
  158  
  159  
  160   GO
  161   PRINT N'Cr eating [Ap p].[NVCC_S ensitiveDx BaseCodes] ...';
  162  
  163  
  164   GO
  165   CREATE TAB LE [App].[ NVCC_Sensi tiveDxBase Codes] (
  166       [Codin gSystem]   VARCHAR (1 2)  NOT NU LL,
  167       [Code]            VARCHAR (1 2)  NOT NU LL,
  168       [Diagn osisText]  VARCHAR (2 50) NOT NU LL,
  169       [Abuse Dx]        INT            NULL,
  170       [Sickl eDx]       INT            NULL,
  171       [HIVDx ]          INT            NULL
  172   )
  173   WITH (DATA _COMPRESSI ON = PAGE) ;
  174  
  175  
  176   GO
  177   PRINT N'Cr eating [Ap p].[NVCC_S ensitiveDx Codes]...' ;
  178  
  179  
  180   GO
  181   CREATE TAB LE [App].[ NVCC_Sensi tiveDxCode s] (
  182       [Codin gSystem]   VARCHAR (1 2)  NOT NU LL,
  183       [Sta3n ]          SMALLINT       NULL,
  184       [ICDSI D]         INT            NULL,
  185       [Code]            VARCHAR (1 2)  NOT NU LL,
  186       [Diagn osisText]  VARCHAR (2 55) NOT NU LL,
  187       [Abuse Dx]        INT            NULL,
  188       [Sickl eDx]       INT            NULL,
  189       [HIVDx ]          INT            NULL
  190   );
  191  
  192  
  193   GO
  194   PRINT N'Cr eating [Ap p].[NVCC_S ensitiveDx Codes].[NV CC_Sensiti veDxCodes_ ICDSID]... ';
  195  
  196  
  197   GO
  198   CREATE UNI QUE CLUSTE RED INDEX  [NVCC_Sens itiveDxCod es_ICDSID]
  199       ON [Ap p].[NVCC_S ensitiveDx Codes]([IC DSID] ASC)  WITH (FIL LFACTOR =  95, DATA_C OMPRESSION  = PAGE);
  200  
  201  
  202   GO
  203   PRINT N'Cr eating [Ap p].[NVCC_S ensitiveDx Codes].[NV CC_Sensiti veDxCodes_ Sta3n_ICDC ode]...';
  204  
  205  
  206   GO
  207   CREATE UNI QUE NONCLU STERED IND EX [NVCC_S ensitiveDx Codes_Sta3 n_ICDCode]
  208       ON [Ap p].[NVCC_S ensitiveDx Codes]([St a3n] ASC,  [Code] ASC )
  209       INCLUD E([Diagnos isText], [ AbuseDx],  [SickleDx] , [HIVDx])  WITH (FIL LFACTOR =  95, DATA_C OMPRESSION  = PAGE);
  210  
  211  
  212   GO
  213   PRINT N'Cr eating [Ap p].[NVCC_S tations].. .';
  214  
  215  
  216   GO
  217   CREATE TAB LE [App].[ NVCC_Stati ons] (
  218       [Sta3n ]                SMAL LINT       NOT NULL,
  219       [MedCt r]               VARC HAR (60)   NOT NULL,
  220       [FullA ddress]          VARC HAR (130)  NULL,
  221       [Stree tAddress1]       VARC HAR (130)  NULL,
  222       [Stree tAddress2]       VARC HAR (130)  NULL,
  223       [City]                  VARC HAR (50)   NULL,
  224       [State ]                VARC HAR (30)   NULL,
  225       [Zip]                   VARC HAR (50)   NULL,
  226       [Facil ityPhoneNu mber] VARC HAR (50)   NULL,
  227       [Facil ityFaxNumb er]   VARC HAR (50)   NULL,
  228       [TPAOK ]                VARC HAR (3)    NOT NULL,
  229       [TPANa me]              VARC HAR (30)   NULL,
  230       [TPAPh one]             VARC HAR (20)   NULL,
  231       [TPAFa x]               VARC HAR (20)   NULL,
  232       CONSTR AINT [PK_N VCC_Statio ns_Sta3n]  PRIMARY KE Y CLUSTERE D ([Sta3n]  ASC) WITH  (DATA_COM PRESSION =  PAGE)
  233   );
  234  
  235  
  236   GO
  237   PRINT N'Cr eating [Ap p].[NVCC_U serFacilit ies]...';
  238  
  239  
  240   GO
  241   CREATE TAB LE [App].[ NVCC_UserF acilities]  (
  242       [UserF acilityId]    INT            IDE NTITY (1,  1) NOT NUL L,
  243       [UserI D]            INT            NOT  NULL,
  244       [Sta3n ]             SMALLIN T      NOT  NULL,
  245       [Sta6a ]             VARCHAR  (50)  NUL L,
  246       [LastA uthDateTim e] DATETIM E2 (0) NUL L,
  247       [ViaB]               BIT            NUL L,
  248       [admin ]             BIT            NOT  NULL,
  249       PRIMAR Y KEY NONC LUSTERED ( [UserFacil ityId] ASC )
  250   )
  251   WITH (DATA _COMPRESSI ON = PAGE) ;
  252  
  253  
  254   GO
  255   PRINT N'Cr eating [Ap p].[NVCC_U serFacilit ies].[NVCC _UserFacil ities_User IDSta3n].. .';
  256  
  257  
  258   GO
  259   CREATE UNI QUE CLUSTE RED INDEX  [NVCC_User Facilities _UserIDSta 3n]
  260       ON [Ap p].[NVCC_U serFacilit ies]([User ID] ASC, [ Sta3n] ASC ) WITH (DA TA_COMPRES SION = PAG E);
  261  
  262  
  263   GO
  264   PRINT N'Cr eating [Ap p].[NVCC_U serFacilit ies].[NVCC _UserFacil ities_User FacilityId ]...';
  265  
  266  
  267   GO
  268   CREATE UNI QUE NONCLU STERED IND EX [NVCC_U serFacilit ies_UserFa cilityId]
  269       ON [Ap p].[NVCC_U serFacilit ies]([User FacilityId ] ASC) WIT H (DATA_CO MPRESSION  = PAGE);
  270  
  271  
  272   GO
  273   PRINT N'Cr eating [Ap p].[NVCC_U sers]...';
  274  
  275  
  276   GO
  277   CREATE TAB LE [App].[ NVCC_Users ] (
  278       [ID]                           INT            IDEN TITY (1, 1 ) NOT NULL ,
  279       [Domai nPlusNetwo rkUserName ] VARCHAR  (50)  NOT  NULL,
  280       [SaveD ate]                    DATETIME       NULL ,
  281       [Sta3n ]                       INT            NOT  NULL,
  282       [UserI EN]                     VARCHAR  (50)  NULL ,
  283       [IsCos ignerRequi red]         VARCHAR  (5)   NULL ,
  284       [Admin ]                       BIT            NULL ,
  285       [Acces sCode]                  VARCHAR  (100) NULL ,
  286       [Verif yCode]                  VARCHAR  (100) NULL ,
  287       [ViaBA pproved]                BIT            NULL ,
  288       [Sta6a ]                       VARCHAR  (10)  NULL ,
  289       [UserS essionId]               VARCHAR  (100) NULL ,
  290       [UserS essionSave dDateTime]   DATETIME       NULL ,
  291       CONSTR AINT [PK_d bo.Users1]  PRIMARY K EY CLUSTER ED ([ID] A SC) WITH ( DATA_COMPR ESSION = P AGE)
  292   );
  293  
  294  
  295   GO
  296   PRINT N'Cr eating [Ap p].[NVCC_U sers].[NVC C_Users_Do mainPlusNe tworkUserN ame]...';
  297  
  298  
  299   GO
  300   CREATE UNI QUE NONCLU STERED IND EX [NVCC_U sers_Domai nPlusNetwo rkUserName ]
  301       ON [Ap p].[NVCC_U sers]([Dom ainPlusNet workUserNa me] ASC) W ITH (DATA_ COMPRESSIO N = PAGE);
  302  
  303  
  304   GO
  305   PRINT N'Cr eating [Ap p].[NVCC_U sersV2]... ';
  306  
  307  
  308   GO
  309   CREATE TAB LE [App].[ NVCC_Users V2] (
  310       [UserI d]      IN T           IDENTITY  (1, 1) NOT  NULL,
  311       [UserN ame]    VA RCHAR (50)  NOT NULL,
  312       [CanAn nounce] BI T           NOT NULL,
  313       [CanRe port]   BI T           NOT NULL,
  314       PRIMAR Y KEY CLUS TERED ([Us erId] ASC)
  315   )
  316   WITH (DATA _COMPRESSI ON = PAGE) ;
  317  
  318  
  319   GO
  320   PRINT N'Cr eating [Ap p].[NVCC_U sersV2].[N VCC_UsersV 2_UserName ]...';
  321  
  322  
  323   GO
  324   CREATE UNI QUE NONCLU STERED IND EX [NVCC_U sersV2_Use rName]
  325       ON [Ap p].[NVCC_U sersV2]([U serName] A SC) WITH ( DATA_COMPR ESSION = P AGE);
  326  
  327  
  328   GO
  329   PRINT N'Cr eating [Df lt].[Extra ctBatchLog ]...';
  330  
  331  
  332   GO
  333   CREATE TAB LE [Dflt]. [ExtractBa tchLog] (
  334       [DWVie wSchema]         VARC HAR (50) N ULL,
  335       [DWVie wName]           VARC HAR (50) N ULL,
  336       [LastE xtractBatc hID]  BIGI NT       N ULL,
  337       [LastE xtractDate Time] DATE TIME     N ULL
  338   );
  339  
  340  
  341   GO
  342   PRINT N'Cr eating [ET L].[ProdLa bChem]...' ;
  343  
  344  
  345   GO
  346   CREATE TAB LE [ETL].[ ProdLabChe m] (
  347       [Sta3n ]                     SMALLINT       NOT NU LL,
  348       [LabCh emTestSID]            INT            NULL,
  349       [LOINC SID]                  INT            NULL,
  350       [LabCh emSpecimen DateTime]  DATETIME2  (0) NULL,
  351       [LabCh emComplete DateTime]  DATETIME2  (0) NULL,
  352       [ETLBa tchID]                INT            NULL,
  353       [OpCod e]                    CHAR (1)       NOT NU LL,
  354       [Vista CreateDate ]          DATETIME       NULL,
  355       [Vista EditDate]             DATETIME       NULL
  356   );
  357  
  358  
  359   GO
  360   PRINT N'Cr eating [Pa nelMgmt].[ PMMasterCo hortLabTes tGroups].. .';
  361  
  362  
  363   GO
  364   CREATE TAB LE [PanelM gmt].[PMMa sterCohort LabTestGro ups] (
  365       [RowID ]                 INT             IDENTITY  (1, 1) NOT  NULL,
  366       [TestG roup]             VAR CHAR (30)   NULL,
  367       [Resul tForTestNu meric] INT             NULL,
  368       [LabPr ocedure]          VAR CHAR (100)  NULL,
  369       [Workl oadCode]          VAR CHAR (50)   NULL,
  370       [TestS earchCrite ria]   VAR CHAR (200)  NULL,
  371       CONSTR AINT [PK_P MMasterCoh ortLabTest Groups] PR IMARY KEY  CLUSTERED  ([RowID] A SC) WITH ( DATA_COMPR ESSION = P AGE)
  372   );
  373  
  374  
  375   GO
  376   PRINT N'Cr eating [Pa nelMgmt].[ PMMasterCo hortLabTes tGroupsLOI NCCodes].. .';
  377  
  378  
  379   GO
  380   CREATE TAB LE [PanelM gmt].[PMMa sterCohort LabTestGro upsLOINCCo des] (
  381       [RowID ]                 INT             IDENTITY  (1, 1) NOT  NULL,
  382       [TestG roup]             VAR CHAR (30)   NOT NULL,
  383       [Resul tForTestNu meric] INT             NULL,
  384       [LongN ame]              VAR CHAR (100)  NULL,
  385       [LOINC ]                 VAR CHAR (50)   NOT NULL,
  386       [Syste m]                VAR CHAR (30)   NULL,
  387       [YearS earchCrite ria]   INT             NULL,
  388       [LastU pdate]            DAT E           NULL,
  389       CONSTR AINT [PK_P MMasterCoh ortLabTest GroupsLOIN CCodes] PR IMARY KEY  CLUSTERED  ([RowID] A SC)
  390   );
  391  
  392  
  393   GO
  394   PRINT N'Cr eating [Pa nelMgmt].[ PMMasterCo hortSite]. ..';
  395  
  396  
  397   GO
  398   CREATE TAB LE [PanelM gmt].[PMMa sterCohort Site] (
  399       [Sta3n ]     SMAL LINT     N OT NULL,
  400       [Facil ity]  VARC HAR (50) N OT NULL,
  401       [VISN]       SMAL LINT     N OT NULL,
  402       [Activ e]    CHAR  (1)     N ULL,
  403       [NextS ta3n] INT           N ULL,
  404       [Regio n]    SMAL LINT     N OT NULL,
  405       [SiteN ame]  VARC HAR (50) N OT NULL
  406   );
  407  
  408  
  409   GO
  410   PRINT N'Cr eating [Pa nelMgmt].[ PMMasterLa bIndex]... ';
  411  
  412  
  413   GO
  414   CREATE TAB LE [PanelM gmt].[PMMa sterLabInd ex] (
  415       [LabCh emTestSID]        INT             NOT NULL,
  416       [Sta3n ]                 SMA LLINT       NOT NULL,
  417       [LabCh emTestName ]      VAR CHAR (50)   NULL,
  418       [Resul tForTestNu meric] INT             NOT NULL,
  419       [DateE xtracted]         DAT ETIME       NOT NULL,
  420       [TestG roup]             VAR CHAR (100)  NULL,
  421       [LOINC ]                 VAR CHAR (50)   NULL,
  422       [WorkL oadCode]          VAR CHAR (50)   NULL
  423   );
  424  
  425  
  426   GO
  427   PRINT N'Cr eating [Pa nelMgmt].[ PMMasterLa bIndex].[C L_PMMaster LabIndex_L abChemTest SID_TestGr oup]...';
  428  
  429  
  430   GO
  431   CREATE CLU STERED IND EX [CL_PMM asterLabIn dex_LabChe mTestSID_T estGroup]
  432       ON [Pa nelMgmt].[ PMMasterLa bIndex]([L abChemTest SID] ASC,  [TestGroup ] ASC) WIT H (FILLFAC TOR = 95,  DATA_COMPR ESSION = P AGE);
  433  
  434  
  435   GO
  436   PRINT N'Cr eating [Pa nelMgmt].[ PMMasterLa bIndex].[P MMasterLab Index_Test Group_LabC hemTestNam e_Sta3n].. .';
  437  
  438  
  439   GO
  440   CREATE NON CLUSTERED  INDEX [PMM asterLabIn dex_TestGr oup_LabChe mTestName_ Sta3n]
  441       ON [Pa nelMgmt].[ PMMasterLa bIndex]([T estGroup]  ASC, [LabC hemTestNam e] ASC, [S ta3n] ASC)  WITH (FIL LFACTOR =  95, DATA_C OMPRESSION  = PAGE);
  442  
  443  
  444   GO
  445   PRINT N'Cr eating [Pa nelMgmt].[ PMMasterLa bTestGroup sCohort].. .';
  446  
  447  
  448   GO
  449   CREATE TAB LE [PanelM gmt].[PMMa sterLabTes tGroupsCoh ort] (
  450       [RowID ]     INT           I DENTITY (1 , 1) NOT N ULL,
  451       [Cohor tIEN] INT           N OT NULL,
  452       [Cohor t]    VARC HAR (30) N ULL,
  453       [TestG roup] VARC HAR (30) N ULL,
  454       CONSTR AINT [PK_P MMasterLab TestGroups Cohort] PR IMARY KEY  CLUSTERED  ([RowID] A SC)
  455   );
  456  
  457  
  458   GO
  459   PRINT N'Cr eating [Ap p].[AllCDW Patients]. [AllCDWPat ients_Sta3 n_PatientS SN]...';
  460  
  461  
  462   GO
  463   CREATE CLU STERED IND EX [AllCDW Patients_S ta3n_Patie ntSSN]
  464       ON [Ap p].[AllCDW Patients]( [Sta3n] AS C, [Patien tSSN] ASC)  WITH (DAT A_COMPRESS ION = PAGE );
  465  
  466  
  467   GO
  468   PRINT N'Cr eating [Ap p].[AllCDW Patients]. [AllCDWPat ients_Pati entICN]... ';
  469  
  470  
  471   GO
  472   CREATE NON CLUSTERED  INDEX [All CDWPatient s_PatientI CN]
  473       ON [Ap p].[AllCDW Patients]( [PatientIC N] ASC)
  474       INCLUD E([Patient SID], [Pat ientSSN],  [Sta3n]) W ITH (DATA_ COMPRESSIO N = PAGE);
  475  
  476  
  477   GO
  478   PRINT N'Cr eating [Ap p].[AllCDW Patients]. [AllCDWPat ients_Pati entSID]... ';
  479  
  480  
  481   GO
  482   CREATE NON CLUSTERED  INDEX [All CDWPatient s_PatientS ID]
  483       ON [Ap p].[AllCDW Patients]( [PatientSI D] ASC)
  484       INCLUD E([Patient ICN]) WITH  (DATA_COM PRESSION =  PAGE);
  485  
  486  
  487   GO
  488   PRINT N'Cr eating [Ap p].[PCMMCu rrentPatie ntProvider Relationsh ip].[PCMMC urrentPati entProvide rRelations hip_Patien tSID]...';
  489  
  490  
  491   GO
  492   CREATE CLU STERED IND EX [PCMMCu rrentPatie ntProvider Relationsh ip_Patient SID]
  493       ON [Ap p].[PCMMCu rrentPatie ntProvider Relationsh ip]([Patie ntSID] ASC ) WITH (DA TA_COMPRES SION = PAG E);
  494  
  495  
  496   GO
  497   PRINT N'Cr eating [Ap p].[PCMMCu rrentPatie ntProvider Relationsh ip].[PCMMC urrentPati entProvide rRelations hip_Primar yProviderS ID]...';
  498  
  499  
  500   GO
  501   CREATE NON CLUSTERED  INDEX [PCM MCurrentPa tientProvi derRelatio nship_Prim aryProvide rSID]
  502       ON [Ap p].[PCMMCu rrentPatie ntProvider Relationsh ip]([Prima ryProvider SID] ASC)
  503       INCLUD E([Associa teProvider SID], [Pat ientSID])  WITH (DATA _COMPRESSI ON = PAGE) ;
  504  
  505  
  506   GO
  507   PRINT N'Cr eating [Ap p].[DF_Ann ouncement_ CreationDT ]...';
  508  
  509  
  510   GO
  511   ALTER TABL E [App].[N VCC_Announ cement]
  512       ADD CO NSTRAINT [ DF_Announc ement_Crea tionDT] DE FAULT (sys utcdatetim e()) FOR [ CreationDT ];
  513  
  514  
  515   GO
  516   PRINT N'Cr eating unn amed const raint on [ App].[NVCC _UserFacil ities]...' ;
  517  
  518  
  519   GO
  520   ALTER TABL E [App].[N VCC_UserFa cilities]
  521       ADD DE FAULT 0 FO R [admin];
  522  
  523  
  524   GO
  525   PRINT N'Cr eating unn amed const raint on [ App].[NVCC _UsersV2]. ..';
  526  
  527  
  528   GO
  529   ALTER TABL E [App].[N VCC_UsersV 2]
  530       ADD DE FAULT 0 FO R [CanAnno unce];
  531  
  532  
  533   GO
  534   PRINT N'Cr eating unn amed const raint on [ App].[NVCC _UsersV2]. ..';
  535  
  536  
  537   GO
  538   ALTER TABL E [App].[N VCC_UsersV 2]
  539       ADD DE FAULT 0 FO R [CanRepo rt];
  540  
  541  
  542   GO
  543   PRINT N'Cr eating [Df lt].[DF__E xtractBa__ LastE__151 B244E]...' ;
  544  
  545  
  546   GO
  547   ALTER TABL E [Dflt].[ ExtractBat chLog]
  548       ADD CO NSTRAINT [ DF__Extrac tBa__LastE __151B244E ] DEFAULT  (getdate() ) FOR [Las tExtractDa teTime];
  549  
  550  
  551   GO
  552   PRINT N'Cr eating [Ap p].[udf_St ationName] ...';
  553  
  554  
  555   GO
  556  
  557   CREATE FUN CTION [App ].[udf_Sta tionName]  (@Sta3n VA RCHAR(MAX) )
  558   RETURNS VA RCHAR(50)
  559   AS
  560   --======== ========== ========== ========== ========== ========== ========== ========== ===
  561   --Requesto r                                : Non Va C oordinated  Care Proj ect
  562   --Author                  : Jerr y Kohler -  Northwest  Innovatio n Center ( NWIC)
  563   --Object/S P Name                  : udf_St ationName
  564   --SERVER                                   
  565   --Data Bas e                                : CC_REFDO C
  566   --Schema                                    : app
  567   --Report                                    : N/A
  568   --Folder                                    : N/A
  569   --Report L oc             : N/A
  570   --Job                     : None
  571   --Job Loc                 : None
  572   --Note                    : 
  573   --Date Cre ated           : 02-1 8-2016
  574   --Last Cha nged           : 
  575   --Last Cha nged By                 : 
  576   --Reason F or Change               : 
  577   --
  578   --Purpose                 : Retu rns a "nic er" statio n name tha n what is  stored in
  579   --                          xDWW ork.dim.in stitution
  580   --======== ========== ========== ========== ========== ========== ========== ========== ===
  581   BEGIN
  582  
  583      RETURN
  584      (
  585         SELE CT
  586         CASE
  587            W HEN charin dex('(',su bstring(St a3nName,7, 50)) <=0 T HEN substr ing(Sta3nN ame,7,50)
  588            E LSE substr ing(Sta3nN ame, 7, (c harindex(' (', substr ing(Sta3nN ame,7,50)) -1))
  589         END
  590  
  591         FROM  CDWWork.D im.Sta3n
  592  
  593         WHER E Sta3n =  @Sta3n
  594           AN D Active =  'Y'
  595      )
  596  
  597   END
  598   GO
  599   PRINT N'Cr eating [Ap p].[NVCC_u df_ActiveU serCount]. ..';
  600  
  601  
  602   GO
  603  
  604   CREATE FUN CTION [App ].[NVCC_ud f_ActiveUs erCount] ( )
  605   RETURNS @A ctiveUserC ount TABLE
  606   (
  607           St ation varc har(56) NO T NULL,
  608           Ac tiveUsers  int NOT NU LL
  609   )
  610  
  611   -- NOTICE:
  612   -- Do not  edit the f unction li ve on the  server. Co de to gene rate
  613   -- the fun ction is s tored in t he project  repositor y. Any cha nges made
  614   -- that ar e not reco rded in th e reposito ry will be  overwritt en.
  615  
  616   AS
  617   --======== ========== ========== ========== ========== ========== ========== ========== ====
  618   --Requesto r              : Non  Va Coordin ated Care  Project
  619   --Author                  : Bria n Diggs
  620   --Object/S P Name         : NVCC _udf_Activ eUserCount
  621   --Server                  : 
  622   --Data Bas e              : CC_R EFDOC
  623   --Schema                  : App
  624   --Report                  : N/A
  625   --Folder                  : N/A
  626   --Report L oc             : N/A
  627   --Job                     : None
  628   --Job Loc                 : None
  629   --Note                    : 
  630   --Date Cre ated           : 08-0 2-2016
  631   --
  632   --
  633   --Last Cha nged           : 2017 -07-24
  634   --Last Cha nged By                 : Brian  Diggs
  635   --Reason F or Change               : Conver t from usi ng vNVCC_P roductionA ccessLog a nd
  636   --                          Pati ent.Patien t to using  NVCC_Prod uctionLog.
  637   --                          Also  embed sta 3n in stat ion name.
  638   --
  639   --Purpose                 : To c ount the n umber of " active" us ers.
  640   --======== ========== ========== ========== ========== ========== ========== ========== ====
  641   --Uses: Ap p.udf_Stat ionName
  642   --Uses: Ap p.NVCC_Pro ductionLog
  643  
  644   BEGIN
  645           IN SERT @Acti veUserCoun t
  646           SE LECT
  647                    '['  + convert( varchar(3) , sta3n) +  '] ' + Ap p.udf_Stat ionName(St a3n) AS St ation,
  648                    COUN T(*) AS Ac tiveUsers
  649           FR OM (
  650                    SELE CT UserID,  Sta3n
  651                    FROM
  652                             App.NV CC_Product ionLog
  653                    WHER E AccessDa teTime > d ateadd(day , -30, con vert(date,  getutcdat e()))
  654                    GROU P BY UserI D, Sta3n
  655                    HAVI NG COUNT(* ) >= 10
  656           )  AS U
  657           GR OUP BY U.S ta3n
  658   --      OR DER BY Act iveUsers D ESC
  659           RE TURN
  660   END;
  661   GO
  662   PRINT N'Cr eating [Ap p].[udf_Al lPatientsS IDs]...';
  663  
  664  
  665   GO
  666  
  667   CREATE FUN CTION [App ].[udf_All PatientsSI Ds] (@pid  INT)
  668   RETURNS @A llPtSIDS T ABLE
  669      (
  670          PtI CN VARCHAR (50),
  671          PtS ID INT PRI MARY KEY N OT NULL,
  672          Sta 3n SMALLIN T,
  673          Pat ientIEN VA RCHAR(50)
  674          --P tIEN VARCH AR(50)
  675      )
  676   AS
  677   --======== ========== ========== ========== ========== ========== ========== ========== ===
  678   --Requesto r                                : Non Va C oordinated  Care Proj ect
  679   --Author                  : Jerr y Kohler -  Northwest  Innovatio n Center ( NWIC)
  680   --Object/S P Name                  : udf_Al lPatientsS IDs
  681   --SERVER                                   
  682   --Data Bas e                                : CC_REFDO C
  683   --Schema                                    : app
  684   --Report                                    : N/A
  685   --Folder                                    : N/A
  686   --Report L oc             : N/A
  687   --Job                     : None
  688   --Job Loc                 : None
  689   --Note                    : 
  690   --Date Cre ated           : 01-1 4-2016
  691   --Last Cha nged           : 
  692   --Last Cha nged By                 : 
  693   --Reason F or Change               : 
  694   --
  695   --Purpose                 : Retu rns a tabl e containi ng ALL pat ient SIDS  plus other
  696   --                          data base key d ata for a  single pat ient.  Thi s facilita tes
  697   --                          retr ieving all  data for  a patient,  regardles s of what
  698   --                          stat ion the pa tient rece ived care  at.  This  facilitate s
  699   --                          show ing a cont inuum of c are.
  700   --
  701   --Last Cha nged           : 03-2 3-2017
  702   --Last Cha nged By                 : Jerry  Kohler - N WIC
  703   --Reason F or Change               : Change  function  to look at  App.AllCD WPatients  instead of
  704   --                        : RDWW ork.SPatie nt.SPatien t because  AllCDWPati ents is mu ch
  705   --                        : smal ler and si gnificantl y improves  performan ce.
  706   --======== ========== ========== ========== ========== ========== ========== ========== ===
  707   BEGIN
  708      INSERT  @AllPtSIDS
  709         Sele ct x.Patie ntICN
  710                ,x.Patie ntSID
  711                ,x.Sta3n
  712                ,x.Patie ntIEN
  713           Fr om App.All CDWPatient s AS x
  714          Whe re x.Patie ntICN = (S elect y.Pa tientICN
  715                                     From App. AllCDWPati ents y
  716                                    Where y.Pa tientSID =  @pid);
  717      RETURN
  718  
  719   END
  720   GO
  721   PRINT N'Cr eating [Ap p].[udf_Sp litString] ...';
  722  
  723  
  724   GO
  725   CREATE FUN CTION [App ].[udf_Spl itString]
  726  
  727   (@List NVA RCHAR (MAX ), @SplitO n VARCHAR  (MAX))
  728   RETURNS 
  729       @RtnVa lue TABLE  (
  730           [I d]    INT              IDENTITY  (1, 1) NOT  NULL,
  731           [V alue] VARC HAR (MAX)  NULL)
  732   AS
  733   BEGIN
  734         Whil e (Charind ex(@SplitO n,@List)>0 )
  735         BEGI N
  736                INSERT I NTO @RtnVa lue (Value )
  737                SELECT l trim(rtrim (Substring (@List,1,C harindex(@ SplitOn,@L ist)-1))) 
  738                
  739                SET @Lis t = Substr ing(@List, Charindex( @SplitOn,@ List)+len( @SplitOn), len(@List) )
  740         END 
  741  
  742         INSE RT INTO @R tnValue (V alue)
  743         SELE CT ltrim(r trim(@List ))
  744  
  745       Return
  746   END
  747   GO
  748   PRINT N'Cr eating [Ap p].[NVCC_v GetNVAMeds ]...';
  749  
  750  
  751   GO
  752  
  753  
  754  
  755  
  756  
  757   CREATE VIE W [App].[N VCC_vGetNV AMeds]
  758  
  759   AS
  760   --======== ========== ========== ========== ========== ========== ========== ========== ===
  761   --Requesto r                                : Non Va C oordinated  Care Proj ect
  762   --Author                  : Jerr y Kohler ( Original s cript by D r. Charles  Demosthen es)
  763   --Object/S P Name                  : NVCC_v GetNVAMeds
  764   --SERVER                                   
  765   --Data Bas e                                : CC_REFDO C
  766   --Schema                                    : app
  767   --Report                                    : N/A
  768   --Folder                                    : N/A
  769   --Report L oc             : N/A
  770   --Job                     : None
  771   --Job Loc                 : None
  772   --Note                    : 
  773   --Date Cre ated           : 02-0 5-2016
  774   --Last Cha nged           : 
  775   --Last Cha nged By                 : 
  776   --Reason F or Change               : 
  777   --
  778   --Purpose                 : Retr ieve a pat ient's med ications n ot issued  by VA for
  779   --                          incl usion into  NVCC docu mentation
  780   --======== ========== ========== ========== ========== ========== ========== ========== ===
  781  
  782   SELECT n.N onVAMedSID
  783                    d.Lo calDrugNam eWithDose
  784         ,n.M edicationR oute
  785         ,n.S chedule
  786              , n.Patien tSID
  787   FROM CDWWo rk.NonVAMe d.NonVAMed  n
  788   INNER JOIN  CDWWork.D im.LocalDr ug d ON n. LocalDrugS ID = d.Loc alDrugSID
  789   where NonV AMedSID no t in (0, - 1);
  790   GO
  791   PRINT N'Cr eating [Ap p].[vNVCC_ Division]. ..';
  792  
  793  
  794   GO
  795   CREATE VIE W App.vNVC C_Division
  796  
  797   -- NOTICE:
  798   -- Do not  edit the v iew live o n the serv er. Code t o generate
  799   -- the vie w is store d in the p roject rep ository. A ny changes  made
  800   -- that ar e not reco rded in th e reposito ry will be  overwritt en.
  801  
  802   AS
  803   --======== ========== ========== ========== ========== ========== ========== ========== ===
  804   --Requesto r                                : Non Va C oordinated  Care Proj ect
  805   --Author                  : Bria n Diggs
  806   --Object/S P Name                  : vNVCC_ Division
  807   --SERVER                                   
  808   --Data Bas e                                : CC_REFDO C
  809   --Schema                                    : App
  810   --Report                                    : N/A
  811   --Folder                                    : N/A
  812   --Report L oc             : N/A
  813   --Job                     : None
  814   --Job Loc                 : None
  815   --Note                    : 
  816   --Date Cre ated           : 05-2 5-2017
  817   --Last Cha nged           : 
  818   --Last Cha nged By                 : 
  819   --Reason F or Change               : 
  820   --
  821   --Purpose                 : Crea te a restr icted view  of CDWWor k.dim.Divi sion for
  822   --                          each  Sta6a app ears only  once.
  823   --======== ========== ========== ========== ========== ========== ========== ========== ===
  824   --
  825   -- Goal: t o get a li st of vali d sta6a's  and their  associated  names, st a3n.
  826   -- One ent ry per Sta 6a
  827   -- Only St a6a's that  are "real " and affi liated wit h a reason able sta3n .
  828   --
  829   -- Primary  source of  data is C DWWork.Dim .Division
  830   -- Seconda ry source  is CDWWork .Dim.Insti tution
  831   --
  832   -- Don't w ant Sta6a' s that are  NULL, '*M issing*',  '*Unknown  at this ti me*', or 
  833   -- any whe re the fir st three c haracters  of the sta 6a is not  the corres ponding st a3n.
  834   -- This la st criteri a will cov er all the  previous  ones as we ll.
  835   --
  836   -- This st ill leaves  multiple  entries fo r some sta 6a.
  837   -- Which e ntries are  chosen is  based on  a scoring  algorithm  that was c reated by  listing 
  838   -- all the  sta6a's t hat were m ultiples a nd, by han d, selecti ng the "be st" one ba sed on
  839   -- the inf ormation i n the reco rd and the  correspon ding (LEFT  JOINed) I nstitution  record.
  840   -- The sco re criteri a that cou ld be used  to recrea te the sel ection was :
  841   -- If the  name (CDWW ork.Dim.Di vision.Div isionName)  starts wi th 'ZZ', - 100 points
  842   -- If the  CDWWork.Di m.Institut ion.StaPa  is NULL, - 50 points
  843   -- If the  CDWWork.Di m.Institut ion.Inacti veFlag is  anything b ut NULL, - 20 points
  844   --
  845   -- The rea son that t hese crite ria are ex pressed as  a score i s so that  for any st a6a,
  846   -- there w ill always  be some e ntry which  is the "b est", even  if it is  the only o ne. That
  847   -- is, eve n if there  is only o ne entry,  it would b e selected  even if i t met one  of these
  848   -- "bad" c riteria.
  849  
  850   SELECT
  851           Or deredSta6a .DivisionS ID,
  852           Or deredSta6a .Sta3n,
  853           Or deredSta6a .DivisionN ame,
  854           Or deredSta6a .Sta6a
  855   FROM (
  856           SE LECT 
  857                    Scor edSta6a.Di visionSID,
  858                    Scor edSta6a.St a3n,
  859                    Scor edSta6a.Di visionName
  860                    Scor edSta6a.St a6a,
  861                    -- i ncluding t ie breaker s for scor e to guara ntee same  order ever y time
  862                    ROW_ NUMBER() O VER (PARTI TION BY St a6a ORDER  BY Score D ESC, Divis ionName, D ivisionSID ) as N 
  863           FR OM (
  864                    SELE CT
  865                             Divisi on.Divisio nSID,
  866                             Divisi on.Sta3n,
  867                             Divisi on.Divisio nName, 
  868                             Divisi on.Sta6a,
  869                             (
  870                                      CASE
  871                                               WHEN SUBST RING(Divis ion.Divisi onName, 1,  2) = 'ZZ'  THEN -100
  872                                               ELSE 0
  873                                      END +
  874                                      CASE
  875                                               WHEN Insti tution.Sta Pa IS NULL  THEN -50
  876                                               ELSE 0
  877                                      END +
  878                                      CASE
  879                                               WHEN Insti tution.Ina ctiveFlag  IS NOT NUL L THEN -20
  880                                               ELSE 0
  881                                      END
  882                             ) AS S core
  883                    FROM  
  884                             CDWWor k.Dim.Divi sion
  885                             LEFT J OIN CDWWor k.Dim.Inst itution 
  886                                      ON Divis ion.Instit utionSID =  Instituti on.Institu tionSID
  887                    WHER E
  888                             -- The  first thr ee digits  of Sta6a m atch Sta3n  
  889                             Divisi on.Sta3n =  CASE
  890                                      WHEN ISN UMERIC(SUB STRING(Sta 6a, 1, 3))  = 1 THEN
  891                                               CONVERT(SM ALLINT, SU BSTRING(St a6a, 1, 3) )
  892                                      ELSE NUL L
  893                             END
  894                    ) AS  ScoredSta 6a 
  895           )  AS Ordered Sta6a
  896   WHERE
  897           N= 1
  898   --ORDER BY  Sta6a
  899   GO
  900   PRINT N'Cr eating [Pa nelMgmt].[ vICD10]... ';
  901  
  902  
  903   GO
  904  
  905  
  906  
  907  
  908   CREATE VIE W [PanelMg mt].[vICD1 0] AS
  909   --======== ========== ========== ========== ========== ========== ========== ========== ========== ========== ========== =
  910   --Region                  : R01
  911   --Visn                                      : V20
  912   --Requesto r                                : NWIC
  913   --Author                  : Jerr y Kohler
  914   --Object/S P Name                  : vICD10
  915   --Server                                   
  916   --Data Bas e                                : CC_REFDO C
  917   --Schema                                    : PanelMgm t
  918   --Report                                    : Any Pane l Manageme nt registr y or repor t.
  919   --Folder                                    :
  920   --Report L oc             : 
  921   --Job Loc                 : None
  922   --Note                    : THIS  VIEW RETU RNS THE CU RRENT DESC RIPTION AN D DIAGNOST IC TEXT, N OT HISTORI C ONES
  923   --                        : BASE D ON A DAT E.  This v iew is not  supported  by CDW, B ISL or any  OI&T grou p.
  924   --                        : The  ICD-10 cod es do not  become eff ective unt il 10/01/2 015.
  925   --                        :
  926   --                        : Thes e views on ly exist a t district  5.  Any c ode using  them canno t be share d beyond
  927   --                          dist rict 5.
  928   --                        :
  929   --Date Cre ated           : 09-1 0-2015
  930   --                        :
  931   --Last Cha nged           : 09-1 1-2015
  932   --Last Cha nged By                 : Jerry  Kohler
  933   --Reason F or Change               : Added  ICD10 Diag nosis
  934   --
  935   --Purpose                 : To m inimize th e impact o f future C DW changes  to ICD-9/ 10
  936   --======== ========== ========== ========== ========== ========== ========== ========== ========== ========== ========== =
  937   Select a.S ta3n,
  938          a.I CDIEN,
  939          a.I CD10SID,
  940          a.I CD10Code, 
  941          b.I CD10Descri ption,
  942          c.I CD10Diagno sis AS ICD 10Diagnosi sText,
  943          CAS T(10 AS SM ALLINT) AS  ICDVersio n
  944   from CDWWo rk.Dim.ICD 10 a
  945   join CDWWo rk.Dim.ICD 10Descript ionVersion  b on b.IC D10SID = a .ICD10SID
  946   and b.Curr entVersion Flag = 'Y'
  947   join CDWWo rk.Dim.ICD 10Diagnosi sVersion c  on c.ICD1 0SID = a.I CD10SID
  948   and c.Curr entVersion Flag = 'Y'
  949   ;
  950   GO
  951   PRINT N'Cr eating [Pa nelMgmt].[ vICD9]...' ;
  952  
  953  
  954   GO
  955  
  956  
  957  
  958  
  959  
  960   CREATE Vie w [PanelMg mt].[vICD9 ] AS
  961   --======== ========== ========== ========== ========== ========== ========== ========== ========== ========== ========== =
  962   --Region                  : R01
  963   --Visn                                      : V20
  964   --Requesto r                                : NWIC
  965   --Author                  : Jerr y Kohler
  966   --Object/S P Name                  : vICD9
  967   --Server                                   
  968   --Data Bas e                                : CC_REFDO C
  969   --Schema                                    : PanelMgm t
  970   --Report                                    : Any Pane l Manageme nt registr y or repor t.
  971   --Folder                                    :
  972   --Report L oc             : 
  973   --Job Loc                 : None
  974   --Note                    : THIS  VIEW RETU RNS THE CU RRENT DESC RIPTION AN D DIAGNOST IC TEXT, N OT HISTORI C ONES
  975   --                        : BASE D ON A DAT E.  This v iew is not  supported  by CDW, B ISL or any  OI&T grou p.
  976   --                        :
  977   --                        : Thes e views on ly exist a t District  5.  Any c ode using  them canno t be share d beyond
  978   --                          dist rict 5.
  979   --                        :
  980   --Date Cre ated           : 09-1 0-2015
  981   --
  982   --Last Cha nged           : 09-1 1-2015
  983   --Last Cha nged By                 : Jerry  Kohler
  984   --Reason F or Change               : Added  ICD9 Diagn osis
  985   --
  986   --Purpose                 : To m inimize th e impact o f future C DW changes  to ICD-9/ 10
  987   --======== ========== ========== ========== ========== ========== ========== ========== ========== ========== ========== =
  988   Select a.S ta3n,
  989          a.I CDIEN,
  990          a.I CD9SID,
  991          a.I CD9Code, 
  992          b.I CD9Descrip tion,
  993          c.I CD9Diagnos is AS ICD9 DiagnosisT ext,
  994          CAS T(9 AS SMA LLINT) AS  ICDVersion
  995   from CDWWo rk.Dim.ICD 9 a
  996   join CDWWo rk.Dim.ICD 9Descripti onVersion  b on b.ICD 9SID = a.I CD9SID
  997    and b.Cur rentVersio nFlag = 'Y '
  998   join CDWWo rk.Dim.ICD 9Diagnosis Version c  on c.ICD9S ID = a.ICD 9SID
  999    and c.Cur rentVersio nFlag = 'Y '
  1000   ;
  1001   GO
  1002   PRINT N'Cr eating [Pa nelMgmt].[ vICD]...';
  1003  
  1004  
  1005   GO
  1006  
  1007  
  1008  
  1009  
  1010   CREATE Vie w [PanelMg mt].[vICD]  AS
  1011   --======== ========== ========== ========== ========== ========== ========== ========== ========== ========== ========== =
  1012   --Region                  : R01
  1013   --Visn                                      : V20
  1014   --Requesto r                                : NWIC
  1015   --Author                  : Jerr y Kohler
  1016   --Object/S P Name                  : vICD
  1017   --Server                                   
  1018   --Data Bas e                                : CC_REFDO C
  1019   --Schema                                    : PanelMgm t
  1020   --Report                                    : Any Pane l Manageme nt registr y or repor t.
  1021   --Folder                                    :
  1022   --Report L oc             : 
  1023   --Job Loc                 : None
  1024   --Note                    : THIS  VIEW RETU RNS THE CU RRENT DESC RIPTION AN D DIAGNOST IC TEXT, N OT HISTORI C ONES
  1025   --                        : BASE D ON A DAT E.  This v iew is not  supported  by CDW, B ISL or any  OI&T grou p.
  1026   --                        :
  1027   --                        : Thes e views on ly exist a t district  5.  Any c ode using  them canno t be share d beyond
  1028   --                          dist rict 5.
  1029   --                        :
  1030   --Date Cre ated           : 09-2 1-2015
  1031   --
  1032   --Last Cha nged           : 
  1033   --Last Cha nged By                 : 
  1034   --Reason F or Change               : 
  1035   --
  1036   --Purpose                 : To m inimize th e impact o f future C DW changes  of ICD-9/ 10 on our  code.
  1037   --======== ========== ========== ========== ========== ========== ========== ========== ========== ========== ========== =
  1038   Select Sta 3n,
  1039          ICD IEN             AS IC DIEN,
  1040          ICD 9SID            AS IC DSID,
  1041          ICD 9Code           AS IC DCode, 
  1042          ICD 9Descripti on   AS IC DDescripti on,
  1043          ICD 9Diagnosis Text AS IC DDiagnosis Text,
  1044          ICD Version
  1045   From Panel Mgmt.vICD9
  1046  
  1047   UNION ALL
  1048  
  1049   Select Sta 3n,
  1050          ICD IEN              AS I CDIEN,
  1051          ICD 10SID            AS I CDSID,
  1052          ICD 10Code           AS I CDCode, 
  1053          ICD 10Descript ion   AS I CDDescript ion,
  1054          ICD 10Diagnosi sText AS I CDDiagnosi sText,
  1055          ICD Version
  1056   From Panel Mgmt.vICD1 0
  1057  
  1058   ;
  1059   GO
  1060   PRINT N'Cr eating [Ap p].[NVCC_R ebuild_Sen sitiveDxCo desTable]. ..';
  1061  
  1062  
  1063   GO
  1064  
  1065   CREATE PRO CEDURE [Ap p].[NVCC_R ebuild_Sen sitiveDxCo desTable]
  1066  
  1067   AS
  1068   --======== ========== ========== ========== ========== ========== ========== ========== ===
  1069   --Requesto r              : Non  Va Coordin ated Care  Project
  1070   --Author                  : Jerr y Kohler
  1071   --Object/S P Name         : Rebu ild_Sensit iveDxCodes Table
  1072   --Server                  : 
  1073   --Data Bas e              : CC_R EFDOC
  1074   --Schema                  : app
  1075   --Report                  : N/A
  1076   --Folder                  : N/A
  1077   --Report L oc             : N/A
  1078   --Job                     : None
  1079   --Job Loc                 : None
  1080   --Note                    : 
  1081   --Date Cre ated           : 01-2 1-2016
  1082   --
  1083   --Changed                 : 
  1084   --Changed  By             : 
  1085   --Reason F or Change      : 
  1086   --
  1087   --
  1088   --Purpose                 : Rebu ild table  App.NVCC_S ensitiveDx Codes, an  intermedia ry
  1089   --                          cach e of sensi tive diagn ostic code s to impro ve NVCC
  1090   --                          appl ication pe rformance  by elimina ting the n eed for a
  1091   --                          sepa rate step  to obtain  the ICD co de SIDS.
  1092   --======== ========== ========== ========== ========== ========== ========== ========== ===
  1093   BEGIN
  1094  
  1095      SET NOC OUNT ON;
  1096  
  1097      IF (SEL ECT OBJECT _ID('app.N VCC_Sensit iveDxCodes ', 'U')) I S NOT NULL
  1098         DROP  TABLE App .NVCC_Sens itiveDxCod es
  1099  
  1100      CREATE  TABLE [App ].[NVCC_Se nsitiveDxC odes](
  1101               [CodingSy stem]  [va rchar](12)  NOT NULL,
  1102               [Sta3n]          [sm allint] NU LL,
  1103               [ICDSID]         [in t] NULL,
  1104               [Code]           [va rchar](12)  NOT NULL,
  1105               [Diagnosi sText] [va rchar](255 ) NOT NULL ,
  1106               [AbuseDx]        [in t] NULL,
  1107               [SickleDx ]      [in t] NULL,
  1108               [HIVDx]          [in t] NULL
  1109      ) ON [D efFG] WITH  (DATA_COM PRESSION =  PAGE)
  1110  
  1111      CREATE  UNIQUE CLU STERED IND EX [NVCC_S ensitiveDx Codes_ICDS ID]
  1112      ON [App ].[NVCC_Se nsitiveDxC odes] (ICD SID ASC)
  1113      WITH (S ORT_IN_TEM PDB = ON,  ONLINE = O FF, FILLFA CTOR = 95,  DATA_COMP RESSION =  PAGE)
  1114      ON [Def FG]
  1115  
  1116      INSERT  INTO App.N VCC_Sensit iveDxCodes  (CodingSy stem, Sta3 n, ICDSID,  Code, Dia gnosisText , AbuseDx,  SickleDx,  HIVDx)
  1117      SELECT  c.CodingSy stem
  1118                 ,i.Sta3 n
  1119                 ,i.ICDS ID
  1120                 ,c.Code
  1121                 ,i.ICDD iagnosisTe xt
  1122                 ,c.Abus eDx
  1123                 ,c.Sick leDx
  1124                 ,c.HIVD x
  1125      FROM [A pp].[NVCC_ SensitiveD xBaseCodes ] c
  1126      INNER J OIN PanelM gmt.vICD A S i ON c.C ode = i.IC DCode
  1127  
  1128  
  1129      CREATE  UNIQUE NON CLUSTERED  INDEX [NVC C_Sensitiv eDxCodes_S ta3n_ICDCo de]
  1130      ON [App ].[NVCC_Se nsitiveDxC odes] (Sta 3n, Code)
  1131      INCLUDE  (Diagnosi sText, Abu seDx, Sick leDx, HIVD x)
  1132      WITH (S ORT_IN_TEM PDB = ON,  ONLINE = O FF, FILLFA CTOR = 95,  DATA_COMP RESSION =  PAGE)
  1133      ON [Def FG]
  1134  
  1135   --select d istinct St a3n from A pp.NVCC_Se nsitiveDxC odes order  by Sta3n
  1136   --select c ode,count( *) from Ap p.NVCC_Sen sitiveDxCo des group  by code or der by cod e
  1137  
  1138   END
  1139   GO
  1140   PRINT N'Cr eating [Ap p].[NVCC_u sp_Current Usage]...' ;
  1141  
  1142  
  1143   GO
  1144   CREATE PRO CEDURE [Ap p].[NVCC_u sp_Current Usage]
  1145           --  @timefram e is the n umber of m inutes (po sitive) to  look back wards for  usage
  1146           @t imeframe n umeric
  1147   AS
  1148   --======== ========== ========== ========== ========== ========== ========== ========== ====
  1149   --Requesto r              : Non  Va Coordin ated Care  Project
  1150   --Author                  : Bria n Diggs
  1151   --Object/S P Name         : NVCC _usp_Curre ntUsage
  1152   --Server                  : 
  1153   --Data Bas e              : CC_R EFDOC
  1154   --Schema                  : App
  1155   --Report                  : N/A
  1156   --Folder                  : N/A
  1157   --Report L oc             : N/A
  1158   --Job                     : None
  1159   --Job Loc                 : None
  1160   --Note                    : 
  1161   --Date Cre ated           : 06-0 1-2016
  1162   --
  1163   --Last Cha nged           : 2017 -03-29
  1164   --Last Cha nged By                 : Brian  Diggs (Nor thwest Inn ovation Ce nter)
  1165   --Reason F or Change               : Tempor ary workar ound for d ifferent s ervers rec ording tim estamp
  1166   --                          in l ocal time
  1167   --
  1168   --Purpose                 : To g et most re cent users /usage
  1169   --======== ========== ========== ========== ========== ========== ========== ========== ====
  1170   --Uses: Ap p.NVCC_Acc essLog
  1171   BEGIN
  1172           WI TH
  1173                    -- 2  hour shif t due to d ifferences  in timezo nes of SQL  server an d applicat ion server
  1174                    Last Time AS (S ELECT DATE ADD(hour,  -2, getdat e()) AS La stTimestam p),
  1175                    -- P ull the lo g entries  for this t ime frame  to use as  a source f or the oth er queries
  1176                    Rece ntLogs AS  (
  1177                             SELECT  
  1178                                      HostName ,
  1179                                      UserID,
  1180                                      AccessDa teTime,
  1181                                      [Action] ,
  1182                                      ElapsedT ime
  1183                             FROM A pp.NVCC_Ac cessLog
  1184                             CROSS  JOIN LastT ime
  1185                              WHERE ((Ho stName = ' SERVER . URL         ' AND Acce ssDateTime  > dateadd (minute, - (@timefram e), LastTi me.LastTim estamp))
  1186                                       OR (HostNa me = 'vaww .refdoc. DNS     ' AND Acce ssDateTime  > dateadd (hour, 3,  dateadd(mi nute, -(@t imeframe),  LastTime. LastTimest amp))))
  1187                                      AND Host Name IS NO T NULL
  1188                                      AND Acce ssDateTime  IS NOT NU LL
  1189                    )
  1190                    SELE CT
  1191                             Users. HostName,
  1192                             Users. UserID,
  1193                             Users. LastLogged Event,
  1194                             Time.M eanLookupT ime,
  1195                             Users. NumberLook ups,
  1196                             Users. NumberPack ages
  1197                    FROM  (
  1198                             -- For  each comb ination of  host/user , compute  some stati stics
  1199                             SELECT
  1200                                      HostName
  1201                                      UserID,
  1202                                      MAX(Acce ssDateTime ) AS LastL oggedEvent ,
  1203                                      SUM(CASE  WHEN Acti on = 'Pati entProfile ' THEN 1 E LSE 0 END)  AS Number Lookups, 
  1204                                      SUM(CASE  WHEN Acti on = 'PDF'  THEN 1 EL SE 0 END)  AS NumberP ackages
  1205                             FROM R ecentLogs
  1206                             GROUP  BY HostNam e, UserID
  1207                    ) AS  Users
  1208                    LEFT  JOIN (
  1209                             -- Mea nLookupTim e is more  easily com puted sepa rately bec ause it
  1210                             -- nee ds just a  subset of  the data
  1211                             SELECT
  1212                                      HostName , UserID,  AVG(Elapse dTime) AS  MeanLookup Time
  1213                             FROM R ecentLogs
  1214                             WHERE  Action IS  NOT NULL A ND Action  = 'Patient Profile' 
  1215                             GROUP  BY HostNam e, UserID
  1216                    ) AS  Time
  1217                             ON Use rs.Hostnam e = Time.H ostName an d Users.Us erID = Tim e.UserID
  1218                    ORDE R BY
  1219                             HostNa me,
  1220                             LastLo ggedEvent  DESC
  1221   END
  1222   GO
  1223   PRINT N'Cr eating [Ap p].[NVCC_u sp_GetAlle rgies]...' ;
  1224  
  1225  
  1226   GO
  1227  
  1228   CREATE PRO CEDURE [Ap p].[NVCC_u sp_GetAlle rgies]
  1229          @pi d bigint - - this is  the patien t's databa se sid
  1230  
  1231   AS
  1232   --======== ========== ========== ========== ========== ========== ========== ========== ===
  1233   --Requesto r                                : Non Va C oordinated  Care Proj ect
  1234   --Author                  : Jerr y Kohler ( Original s cript by D r. Charles  Demosthen es)
  1235   --Object/S P Name                  : NVCC_u sp_GetAlle rgies
  1236   --SERVER                                   
  1237   --Data Bas e                                : CC_REFDO C
  1238   --Schema                                    : nva
  1239   --Report                                    : N/A
  1240   --Folder                                    : N/A
  1241   --Report L oc             : N/A
  1242   --Job                     : None
  1243   --Job Loc                 : None
  1244   --Note                    : 
  1245   --Date Cre ated           : 01-1 2-2016
  1246   --
  1247   --Changed                 : 03-0 3-2016  
  1248   --Changed  By                 :  Jerry Kohl er - North west Innov ation Cent er (NWIC)
  1249   --Reason F or Change               : Elimin ate multip le records  with same  allergen,
  1250   --                          only  return th e one with  the lates t verified  date.
  1251   --
  1252   --Changed                 : 02-1 8-2016  
  1253   --Changed  By                 :  Jerry Kohl er - North west Innov ation Cent er (NWIC)
  1254   --Reason F or Change               : Reques t to also  provide th e name of  the statio n.
  1255   --
  1256   --Changed                 : 01-1 2-2016  
  1257   --Changed  By                 :  Jerry Kohl er - North west Innov ation Cent er (NWIC)
  1258   --Reason F or Change               : Remove d station  parameter  in order t o expand t he search
  1259   --                          for  a patient' s allergie s from a s ingle stat ion to any
  1260   --                          stat ion a pati ent is ass ociated wi th.
  1261   --
  1262   --Purpose                 : Retr ieve a pat ient's all ergies for  inclusion  into NVCC
  1263   --                          docu mentation
  1264   --======== ========== ========== ========== ========== ========== ========== ========== ===
  1265   BEGIN
  1266  
  1267      -- SET  NOCOUNT ON  added to  prevent ex tra result  sets from
  1268      -- inte rfering wi th SELECT  statements .
  1269      SET NOC OUNT ON;
  1270  
  1271  
  1272      WITH Al lergies AS
  1273          (
  1274           SE LECT a.Sta 3n
  1275                  ,App.u df_Station Name (a.St a3n) AS St ationName
  1276                  ,a.All ergySID
  1277                  ,a.Pat ientSID
  1278                  ,a.Ori ginationDa teTime
  1279                  ,a.Ver ificationD ateTime
  1280                  ,a.All ergicReact ant as All ergy
  1281                  ,ROW_N UMBER() OV ER (PARTIT ION BY a.A llergicRea ctant ORDE R BY a.Ver ificationD ateTime DE SC) AS RN
  1282           FR OM CDWWork .Allergy.A llergy a
  1283           JO IN CDWWork .Dim.Sta3n  b ON b.St a3n = a.St a3n
  1284           WH ERE a.Pati entSID in  (select Pt SID from [ App].[udf_ AllPatient sSIDs](@pi d))
  1285              AND a.Ente redInError Flag IS NU LL
  1286          )
  1287  
  1288      SELECT  Sta3n
  1289            , StationNam e
  1290            , AllergySID
  1291            , PatientSID
  1292            , Originatio nDateTime
  1293            , Verificati onDateTime
  1294            , Allergy
  1295      FROM Al lergies
  1296      WHERE R N = 1
  1297      ORDER B Y Allergy
  1298      --exec  [app].[NVC C_usp_GetA llergies]  @pid=17174 44
  1299   END;
  1300   GO
  1301   PRINT N'Cr eating [Ap p].[NVCC_u sp_GetAnno uncement]. ..';
  1302  
  1303  
  1304   GO
  1305  
  1306   CREATE PRO CEDURE [Ap p].[NVCC_u sp_GetAnno uncement]
  1307           --  @active i s a numeri c paramete r. If 1, o nly return  the activ e announce ments;
  1308           --  if 0, ret urn all an nouncement s.
  1309           @a ctive int
  1310   AS
  1311   --======== ========== ========== ========== ========== ========== ========== ========== ====
  1312   --Requesto r              : Non  Va Coordin ated Care  Project
  1313   --Author                  : Bria n Diggs
  1314   --Object/S P Name         : NVCC _usp_GetLo gs
  1315   --Server                  : 
  1316   --Data Bas e              : CC_R EFDOC
  1317   --Schema                  : app
  1318   --Report                  : N/A
  1319   --Folder                  : N/A
  1320   --Report L oc             : N/A
  1321   --Job                     : None
  1322   --Job Loc                 : None
  1323   --Note                    : 
  1324   --Date Cre ated           : 06-0 6-2016
  1325   --
  1326   --
  1327   --Last Cha nged           : 
  1328   --Last Cha nged By                 : 
  1329   --Reason F or Change               : 
  1330   --
  1331   --Purpose                 : To g et selecte d announce ments
  1332   --======== ========== ========== ========== ========== ========== ========== ========== ====
  1333   --Uses: Ap p.NVCC_Ann ouncement
  1334   --Uses: Ap p.NVCC_Dim Announceme nt
  1335  
  1336   BEGIN
  1337           IF  (@active  = 0) 
  1338                    BEGI N
  1339                             SELECT
  1340                                      A.Announ cementID,
  1341                                      DA.Annou ncementTyp e,
  1342                                      lc.LastN ame + ', '  + lc.Firs tName AS C reator,
  1343                                      A.Creati onDT,
  1344                                      A.Expira tionDT,
  1345                                      A.Text
  1346                             FROM A pp.NVCC_An nouncement  AS A
  1347                                      INNER JO IN App.NVC C_DimAnnou ncement AS  DA
  1348                                               ON A.Annou ncementTyp eID = DA.A nnouncemen tTypeID
  1349                                      LEFT JOI N CDWWork. LCustomer. LCustomer  lc
  1350                                               ON A.Creat or = lc.AD Domain + ' \' + lc.AD Login
  1351                    END
  1352           EL SE IF (@ac tive = 1)
  1353                    BEGI N
  1354                             SELECT
  1355                                      A.Announ cementID,
  1356                                      DA.Annou ncementTyp e,
  1357                                      lc.LastN ame + ', '  + lc.Firs tName AS C reator,
  1358                                      A.Creati onDT,
  1359                                      A.Expira tionDT,
  1360                                      A.Text
  1361                             FROM A pp.NVCC_An nouncement  AS A
  1362                                      INNER JO IN App.NVC C_DimAnnou ncement AS  DA
  1363                                               ON A.Annou ncementTyp eID = DA.A nnouncemen tTypeID
  1364                                      LEFT JOI N CDWWork. LCustomer. LCustomer  lc
  1365                                               ON A.Creat or = lc.AD Domain + ' \' + lc.AD Login
  1366                             WHERE
  1367                                      A.Expira tionDT >=  GETUTCDATE () AND A.C reationDT  <= GETUTCD ATE()
  1368                    END
  1369   END
  1370   GO
  1371   PRINT N'Cr eating [Ap p].[NVCC_u sp_GetAppt s]...';
  1372  
  1373  
  1374   GO
  1375  
  1376   CREATE PRO CEDURE [Ap p].[NVCC_u sp_GetAppt s]
  1377           --  Add the p arameters  for the st ored proce dure here
  1378           @p id bigint  -- this is  the patie ntsid
  1379  
  1380   -- NOTICE:
  1381   -- Do not  edit the s tored proc edure live  on the se rver. Code  to genera te
  1382   -- the pro cedures is  stored in  the proje ct reposit ory. Any c hanges mad e
  1383   -- that ar e not reco rded in th e reposito ry will be  overwritt en.
  1384  
  1385   AS
  1386   --======== ========== ========== ========== ========== ========== ========== ========== ===
  1387   --Requesto r                                : Non Va C oordinated  Care Proj ect
  1388   --Author                  : Jerr y Kohler ( Original s cript by D r. Charles  Demosthen es)
  1389   --Object/S P Name                  : NVCC_u sp_GetAppt s
  1390   --SERVER                                   
  1391   --Data Bas e                                : CC_REFDO C
  1392   --Schema                                    : nva
  1393   --Report                                    : N/A
  1394   --Folder                                    : N/A
  1395   --Report L oc             : N/A
  1396   --Job                     : None
  1397   --Job Loc                 : None
  1398   --Note                    : 
  1399   --Date Cre ated           : 01-1 2-2016
  1400   --
  1401   --Last Cha nged           : 03-1 5-2017  
  1402   --Last Cha nged By                 : Brian  Diggs - No rthwest In novation C enter (NWI C)
  1403   --Reason F or Change               : Change  Appointme ntMadeDate Time to Ap pointmendM adeDate
  1404   --                          due  to schema  changes.
  1405   --
  1406   --Last Cha nged           : 02-1 8-2016  
  1407   --Last Cha nged By                 : Jerry  Kohler - N orthwest I nnovation  Center (NW IC)
  1408   --Reason F or Change               : Reques t to also  provide th e name of  the statio n.
  1409   --
  1410   --Last Cha nged           : 01-1 2-2016  
  1411   --Last Cha nged By                 : Jerry  Kohler - N orthwest I nnovation  Center (NW IC)
  1412   --Reason F or Change               : Remove d station  parameter  in order t o expand t he search
  1413   --                          for  a patient' s appointm ents from  a single s tation to  any
  1414   --                          stat ion a pati ent is ass ociated wi th.
  1415   --
  1416   --Purpose                 : Retr ieve a pat ient's app ointments  for inclus ion into N VCC
  1417   --                          docu mentation
  1418   --======== ========== ========== ========== ========== ========== ========== ========== ===
  1419   --Uses: Ap p.udf_Stat ionName
  1420   --Uses: CD WWork.Appt .Appointme nt
  1421   --Uses: CD WWork.Dim. Location
  1422   --Uses: Ap p.udf_AllP atientsSID s
  1423   BEGIN
  1424      -- SET  NOCOUNT ON  added to  prevent ex tra result  sets from
  1425      -- inte rfering wi th SELECT  statements .
  1426      SET NOC OUNT ON;
  1427  
  1428      SELECT  --TOP (100 )
  1429         ap.S ta3n
  1430        ,App. udf_Statio nName (ap. Sta3n) AS  StationNam e
  1431        ,loc. LocationNa me
  1432        ,conv ert(varcha r, Appoint mentDateTi me, 101) +  ' ' + con vert(varch ar, Appoin tmentDateT ime, 8) AS  Appointme ntDateTime
  1433        ,ap.A ppointment SID
  1434        ,ap.P atientSID
  1435        ,ap.A ppointment TypeSID
  1436        ,desi reddate =
  1437         CASE
  1438            W hen Desire dAppointme ntDate is  null
  1439            T hen conver t(varchar( 12), cast( dateadd(da y, 1, Appo intmentDat eTime) as  date), 101 )
  1440            E lse conver t(varchar( 12), cast( Appointmen tDateTime  as date),  101)
  1441         END
  1442        ,ap.C ancelNoSho wCode
  1443        ,ap.L ocationSID , ap.Purpo seOfVisit
  1444        ,ap.S chedulingR equestType
  1445        ,ap.C ancelDateT ime
  1446        ,ap.A ppointment CancelledF lag
  1447  
  1448      FROM CD WWork.Appt .Appointme nt AS ap
  1449      JOIN CD WWork.Dim. Location A S loc ON a p.Location SID = loc. LocationSI D
  1450      WHERE a p.Appointm entDateTim e >= getda te() and a p.Appointm entDateTim e < conver t(DATE, da teadd(mm,  6, getdate ()))
  1451        AND a p.PatientS ID  in (se lect PtSID  from [App ].[udf_All PatientsSI Ds](@pid)) ;
  1452  
  1453   END;
  1454   GO
  1455   PRINT N'Cr eating [Ap p].[NVCC_u sp_GetCons ults]...';
  1456  
  1457  
  1458   GO
  1459  
  1460   CREATE PRO CEDURE [Ap p].[NVCC_u sp_GetCons ults]
  1461           --  Add the p arameters  for the st ored proce dure here
  1462           @p id bigint  -- this is  the patie ntsid
  1463  
  1464   -- NOTICE:
  1465   -- Do not  edit the s tored proc edure live  on the se rver. Code  to genera te
  1466   -- the pro cedures is  stored in  the proje ct reposit ory. Any c hanges mad e
  1467   -- that ar e not reco rded in th e reposito ry will be  overwritt en.
  1468  
  1469   AS
  1470   --======== ========== ========== ========== ========== ========== ========== ========== ===
  1471   --Requesto r                                : Non Va C oordinated  Care Proj ect
  1472   --Author                  : Jerr y Kohler ( Original s cript by D r. Charles  Demosthen es)
  1473   --Object/S P Name                  : NVCC_u sp_GetCons ults
  1474   --SERVER                                   
  1475   --Data Bas e                                : CC_REFDO C
  1476   --Schema                                    : app
  1477   --Report                                    : N/A
  1478   --Folder                                    : N/A
  1479   --Report L oc             : N/A
  1480   --Job                     : None
  1481   --Job Loc                 : None
  1482   --Note                    : 
  1483   --Date Cre ated           : 01-1 2-2016
  1484   --Last Cha nged           : 12-0 1-2016
  1485   --Last Cha nged By                 : Brian  Diggs - No rthwest In novation C enter (NWI C)
  1486   --Reason F or Change               : Conver t from usi ng [App].[ vPCMMPatie ntProvider s] to
  1487   --                                                  :  [App].[PCM MCurrentPa tientProvi derRelatio nship]
  1488   --
  1489   --Last Cha nged           : 06-2 2-2016
  1490   --Last Cha nged By                 : Brian  Diggs - No rthwest In novation C enter (NWI C)
  1491   --Reason F or Change               : Bringi ng in prim ary provid er and oth er fields  to
  1492   --                                                     be able to  recreate  bottom blo ck of cons ult.
  1493   --                          Chan ge likely  done by Jo nathan Duc kart but w as
  1494   --                          neve r synced w ith the so urce repos itory.
  1495   --
  1496   --Last Cha nged           : 01-1 2-2016  
  1497   --Last Cha nged By                 : Jerry  Kohler - N orthwest I nnovation  Center (NW IC)
  1498   --Reason F or Change               : Remove d station  parameter  in order t o expand t he search
  1499   --                          for  a patient' s consults  from a si ngle stati on to any
  1500   --                          stat ion a pati ent is ass ociated wi th.
  1501   --
  1502   --Purpose                 : Retr ieve a pat ient's con sults from  within th e last 180
  1503   --                          days  for inclu sion into  NVCC docum entation.
  1504   --======== ========== ========== ========== ========== ========== ========== ========== ===
  1505  
  1506   BEGIN
  1507      -- SET  NOCOUNT ON  added to  prevent ex tra result  sets from
  1508      -- inte rfering wi th SELECT  statements .
  1509      SET NOC OUNT ON;
  1510  
  1511           WI TH
  1512                    PTSI D AS (
  1513                             SELECT  PtSID 
  1514                             FROM [ App].[udf_ AllPatient sSIDs](@pi d)
  1515                    )
  1516      SELECT
  1517         c.St a3n
  1518        ,App. udf_Statio nName (c.S ta3n) AS S tationName
  1519        ,c.To RequestSer viceName
  1520        ,cast (c.Request DateTime a s date) AS  RequestDa te
  1521        ,c.CP RSStatus
  1522        ,c.CP RSOrderSID
  1523        ,c.Co nsultSID
  1524            , c.ConsultI EN
  1525        ,c.Pa tientSID
  1526        ,c.To RequestSer viceSID
  1527        ,c.Re questType
  1528            , c.OrderSta tusSID
  1529        ,c.Re centActivi tyTypeSID
  1530        ,c.Re centActivi tyType
  1531            , c.SendingS taffSID
  1532        ,c.Ur gency
  1533        ,c.In patOutpat
  1534            , ISNULL(c.P rovisional Diagnosis,  ' ') AS P rovDx
  1535            , ISNULL(c.P rovisional DiagnosisC ode, ' ')  AS ProvDxC ode
  1536            , c.TIUDocum entSID
  1537        ,c.Ea rliestDate
  1538        ,r.Co nsultReaso n
  1539            , l.Location Name as Fr omService
  1540            ,  st.StaffN ame as Req uestingPro vider
  1541            ,  pcmm.Prim aryProvide r
  1542            ,  pcmm.Team
  1543            ,  sp.Eligib ility + '  ' + sp.Eli gibilitySt atus as Pr imaryEligi bility
  1544      FROM CD WWork.Con. Consult c
  1545      JOIN CD WWork.SPat ient.SCons ultReason  r
  1546                    ON r .ConsultSI D = c.Cons ultSID
  1547           JO IN CDWWork .Dim.Locat ion l
  1548                    ON l .LocationS ID=c.FromL ocationSID
  1549           JO IN CDWWork .SStaff.SS taff st
  1550                    ON s t.StaffSID =c.Sending StaffSID
  1551           LE FT JOIN (
  1552                    SELE CT TOP 1 P atientSID,  PrimaryPr ovider, Te am 
  1553                    FROM  
  1554                             App.PC MMCurrentP atientProv iderRelati onship pp
  1555                             INNER  JOIN PTSID
  1556                                      ON pp.Pa tientSID =  PTSID.PtS ID
  1557                    ORDE R BY Relat ionshipSta rtDate DES C) pcmm
  1558                    ON p cmm.Patien tSID=c.Pat ientSID
  1559           JO IN CDWWork .SPatient. SPatient s p
  1560                    ON s p.PatientS ID=c.Patie ntSID
  1561           IN NER JOIN P TSid ptsid
  1562                    ON p tsid.PtSID  = c.Patie ntSID
  1563      WHERE c .ToRequest ServiceNam e not like  'NON-FORM %' 
  1564            A ND c.CPRSS tatus not  in ('DISCO NTINUED',' CANCELLED' ,'COMPLETE ') 
  1565        AND c .RequestDa teTime >=  CAST(datea dd(dd, -36 5, getdate ()) AS DAT E)
  1566      ORDER B Y c.Reques tDateTime;
  1567   END
  1568   GO
  1569   PRINT N'Cr eating [Ap p].[NVCC_u sp_GetDivi sion]...';
  1570  
  1571  
  1572   GO
  1573  
  1574   CREATE PRO CEDURE [Ap p].[NVCC_u sp_GetDivi sion]
  1575           @s ta6a varch ar(50)
  1576  
  1577   -- NOTICE:
  1578   -- Do not  edit the s tored proc edure live  on the se rver. Code  to genera te
  1579   -- the pro cedures is  stored in  the proje ct reposit ory. Any c hanges mad e
  1580   -- that ar e not reco rded in th e reposito ry will be  overwritt en.
  1581  
  1582   AS
  1583   --======== ========== ========== ========== ========== ========== ========== ========== ===
  1584   --Requesto r                                : REFDOC
  1585   --Author                  : Jon  Duckart 
  1586   --Object/S P Name                  : NVCC_u sp_GetDivi sion
  1587   --SERVER                                   
  1588   --Data Bas e                                : CC_REFDO C
  1589   --Schema                                    : app
  1590   --Report                                    : N/A
  1591   --Folder                                    : N/A
  1592   --Report L oc             : N/A
  1593   --Job                     : None
  1594   --Job Loc                 : None
  1595   --Note                    : 
  1596   --Date Cre ated           : 08-2 5-2016
  1597   --Last Cha nged           : 05-2 5-2017
  1598   --Last Cha nged By                 : Brian  Diggs - No rthwest In novation C enter (NWI C)
  1599   --Reason F or Change               : Change d to use v iew with o nly one en try per St a6a.
  1600   --
  1601   --Last Cha nged           : 03-1 5-2017
  1602   --Last Cha nged By                 : Brian  Diggs - No rthwest In novation C enter (NWI C)
  1603   --Reason F or Change               : Change d paramete r type to  varchar(50 ) to match  the
  1604   --                          type  of sta6a  in the vie w.
  1605   --
  1606   --Last Cha nged           : 08-2 5-2016
  1607   --Last Cha nged By                 : Jon Du ckart - No rthwest In novation C enter (NWI C)
  1608   --Reason F or Change               : 
  1609   --
  1610   --Purpose                 : Retr ieve a use r's Sta6a  for VIA ca lls
  1611   --======== ========== ========== ========== ========== ========== ========== ========== ===
  1612   --Uses: CD WWork.Dim. Division
  1613  
  1614   BEGIN
  1615           --  SET NOCOU NT ON adde d to preve nt extra r esult sets  from
  1616           --  interferi ng with SE LECT state ments.
  1617           SE T NOCOUNT  ON;
  1618           SE LECT 
  1619                    [Div isionSID]
  1620                    ,[St a3n]
  1621                    ,[Di visionName ]  
  1622                    ,[St a6a]
  1623           FR OM App.vNV CC_Divisio n
  1624           WH ERE Sta6a= @sta6a
  1625         
  1626   END;
  1627   GO
  1628   PRINT N'Cr eating [Ap p].[NVCC_u sp_GetDivi sions]...' ;
  1629  
  1630  
  1631   GO
  1632  
  1633  
  1634  
  1635  
  1636   CREATE PRO CEDURE [Ap p].[NVCC_u sp_GetDivi sions]
  1637           @s ta3n small int -- thi s is the s ta3n
  1638  
  1639   -- NOTICE:
  1640   -- Do not  edit the s tored proc edure live  on the se rver. Code  to genera te
  1641   -- the pro cedures is  stored in  the proje ct reposit ory. Any c hanges mad e
  1642   -- that ar e not reco rded in th e reposito ry will be  overwritt en.
  1643  
  1644   AS
  1645   --======== ========== ========== ========== ========== ========== ========== ========== ===
  1646   --Requesto r                                : Non Va C oordinated  Care Proj ect
  1647   --Author                  : Jon  Duckart 
  1648   --Object/S P Name                  : NVCC_u sp_GetVAMe ds
  1649   --SERVER                                   
  1650   --Data Bas e                                : CC_REFDO C
  1651   --Schema                                    : app
  1652   --Report                                    : N/A
  1653   --Folder                                    : N/A
  1654   --Report L oc             : N/A
  1655   --Job                     : None
  1656   --Job Loc                 : None
  1657   --Note                    : 
  1658   --Date Cre ated           : 08-2 3-2016
  1659   --Last Cha nged           : 05-2 5-2017
  1660   --Last Cha nged By                 : Brian  Diggs - No rthwest In novation C enter (NWI C)
  1661   --Reason F or Change               : Change d to use v iew with o nly one en try per St a6a.
  1662   --
  1663   --Last Cha nged           : 08-2 3-2016
  1664   --Last Cha nged By                 : Jon Du ckart - No rthwest In novation C enter (NWI C)
  1665   --Reason F or Change               : 
  1666   --
  1667   --Purpose                 : Retr ieve a use r's Sta6a  for VIA ca lls
  1668   --======== ========== ========== ========== ========== ========== ========== ========== ===
  1669   --Uses: CD WWork.Dim. Division
  1670  
  1671   BEGIN
  1672       -- SET  NOCOUNT O N added to  prevent e xtra resul t sets fro m
  1673       -- int erfering w ith SELECT  statement s.
  1674       SET NO COUNT ON;
  1675           SE LECT 
  1676                    [Div isionSID]
  1677                    ,[St a3n]
  1678                    ,[Di visionName ]  
  1679                    ,[St a6a]
  1680           FR OM App.vNV CC_Divisio n
  1681           WH ERE Sta3n= @sta3n
  1682           OR DER BY Sta 6a
  1683   END;
  1684   GO
  1685   PRINT N'Cr eating [Ap p].[NVCC_u sp_GetLabs ]...';
  1686  
  1687  
  1688   GO
  1689  
  1690  
  1691  
  1692   CREATE PRO CEDURE [Ap p].[NVCC_u sp_GetLabs ]
  1693           --  Add the p arameters  for the st ored proce dure here
  1694           @p id bigint    --this i s the pati entSID
  1695   AS
  1696   --======== ========== ========== ========== ========== ========== ========== ========== ===
  1697   --Requesto r                                : Non Va C oordinated  Care Proj ect
  1698   --Author                  : Jerr y Kohler ( Original s cript by D r. Charles  Demosthen es)
  1699   --Object/S P Name                  : NVCC_u sp_GetLabs
  1700   --Server                                   
  1701   --Data Bas e                                : CC_REFDO C
  1702   --Schema                                    : app
  1703   --Report                                    : N/A
  1704   --Folder                                    : N/A
  1705   --Report L oc             : N/A
  1706   --Job                     : None
  1707   --Job Loc                 : None
  1708   --Note                    : 
  1709   --Date Cre ated           : 01-0 6-2016
  1710   --
  1711   --Last Cha nged           : 02-1 8-2016  
  1712   --Last Cha nged By                 : Jerry  Kohler - N orthwest I nnovation  Center (NW IC)
  1713   --Reason F or Change               : Reques t to also  provide th e name of  the statio n.
  1714   --
  1715   --Changed                 : 02-1 6-2016  
  1716   --Changed  By                 :  Jerry Kohl er - North west Innov ation Cent er (NWIC)
  1717   --Reason F or Change               : We onl y want the  most rece nt value f or any of  the
  1718   --                          labs .
  1719   --
  1720   --Changed                 : 01-1 2-2016  
  1721   --Changed  By                 :  Jerry Kohl er - North west Innov ation Cent er (NWIC)
  1722   --Reason F or Change               : Remove d station  parameter  in order t o expand t he search
  1723   --                          for  a patient' s labs fro m a single  station t o any
  1724   --                          stat ion a pati ent is ass ociated wi th by acqu iring all
  1725   --                          Pati entSIDs fr om the pas sed SIDs I CN.
  1726   --
  1727   --Changed                 : 01-1 1-2016  
  1728   --Changed  By                 :  Jerry Kohl er - North west Innov ation Cent er (NWIC)
  1729   --Reason F or Change               : Integr ated into  the NWIC l ab process  whereby l ab test
  1730   --                          name s are dete rmined by  combinatio ns of LOIN C or workl oad
  1731   --                          code s, and not  relying o n the faci lities to  normalize  or
  1732   --                          stan dardize th eir lab te st names.
  1733   --
  1734   --Purpose                 : Retr ieve resul ts for cer tain lab t ests withi n the last  15
  1735   --                          mont hs and pas s that dat a back to  the NVCC a pplication .
  1736   --======== ========== ========== ========== ========== ========== ========== ========== ===
  1737   BEGIN
  1738      -- SET  NOCOUNT ON  added to  prevent ex tra result  sets from
  1739      -- inte rfering wi th SELECT  statements .
  1740      SET NOC OUNT ON;
  1741  
  1742      WITH La bsLast15Mo nths AS
  1743      (
  1744      SELECT  lab.Sta3n
  1745            , lab.LabChe mSID
  1746            , tst.LabChe mTestName
  1747            , tst.LabChe mPrintTest Name
  1748            , lab.LabChe mSpecimenD ateTime
  1749            , lab.LabChe mResultVal ue
  1750            , ISNULL(lab .Units, '  ') as unit s
  1751            , ISNULL(lab .Abnormal,  ' ') as a bnormal
  1752            , ISNULL(lab .RefHigh,  ' ') as Re fHigh
  1753            , ISNULL(lab .RefLow, '  ') as Ref Low
  1754            , lab.LabChe mResultNum ericValue
  1755            , lab.LabChe mTestSID
  1756            , lab.Patien tSID
  1757            , ROW_NUMBER () over (p artition b y tst.LabC hemTestNam e order by  lab.LabCh emSpecimen DateTime D ESC) AS Ro wNum
  1758      FROM  C DWWork.Che m.LabChem  AS lab
  1759      INNER J OIN CDWWor k.Dim.LabC hemTest AS  tst ON la b.LabChemT estSID = t st.LabChem TestSID
  1760      --INNER  JOIN CDWW ork.SPatie nt.SPatien t s on s.P atientSID= lab.Patien tSID
  1761      WHERE l ab.Patient SID IN (Se lect PtSID  from App. udf_AllPat ientsSIDs( @pid)) AND
  1762         lab. LabChemTes tSID IN (S elect r.La bChemTestS ID
  1763                                        From [ PanelMgmt] .[PMMaster LabIndex]  r
  1764                                       Where r .TestGroup  IN (Selec t Distinct  s.TestGro up
  1765                                                                 Fro m [PanelMg mt].[PMMas terCohortL abTestGrou ps] s
  1766                                                                 Joi n [PanelMg mt].[PMMas terLabTest GroupsCoho rt] t
  1767                                                                   O n t.TestGr oup = s.Te stGroup
  1768                                                                Wher e t.Cohort  = 'NVCC')
  1769                                     ) --Patie nt SID 244 0025 is a  good test  case
  1770        AND l ab.LabChem CompleteDa teTime >=  DATEADD(mo nth, -15,  GETDATE())
  1771            - -AND s.Dat eOfDeath i s NULL
  1772      )
  1773  
  1774      SELECT  Sta3n
  1775            , App.udf_St ationName  (Sta3n) AS  StationNa me
  1776            , LabChemSID
  1777            , LabChemTes tName
  1778            , LabChemPri ntTestName
  1779            , LabChemSpe cimenDateT ime
  1780            , LabChemRes ultValue
  1781            , units
  1782            , abnormal
  1783            , RefHigh
  1784            , RefLow
  1785            , LabChemRes ultNumeric Value
  1786            , LabChemTes tSID
  1787            , PatientSID
  1788                    -- i nto App.La bsLast15Mo nths
  1789      FROM  L absLast15M onths
  1790      WHERE R owNum = 1
  1791  
  1792   END
  1793   GO
  1794   PRINT N'Cr eating [Ap p].[NVCC_u sp_GetNext OfKin]...' ;
  1795  
  1796  
  1797   GO
  1798  
  1799   CREATE PRO CEDURE [Ap p].[NVCC_u sp_GetNext OfKin]
  1800           @s id int   - -PatientSi d
  1801  
  1802   -- NOTICE:
  1803   -- Do not  edit the s tored proc edure live  on the se rver. Code  to genera te
  1804   -- the pro cedures is  stored in  the proje ct reposit ory. Any c hanges mad e
  1805   -- that ar e not reco rded in th e reposito ry will be  overwritt en.
  1806  
  1807   AS
  1808   --======== ========== ========== ========== ========== ========== ========== ========== ====
  1809   --Requesto r              : Non  Va Coordin ated Care  Project
  1810   --Author                  : Jon  Duckart
  1811   --Object/S P Name         : [NVC C_usp_GetN extOfKin]
  1812   --Server                  : 
  1813   --Data Bas e              : CC_R EFDOC
  1814   --Schema                  : app
  1815   --Report                  : N/A
  1816   --Folder                  : N/A
  1817   --Report L oc             : N/A
  1818   --Job                     : None
  1819   --Job Loc                 : None
  1820   --Note                    : 
  1821   --Date Cre ated           : 06-0 7-2016
  1822   --
  1823   --Purpose                 : To r etrieve a  single pat ient NOK r ecord for  the NVCC a pp by SID.
  1824   --======== ========== ========== ========== ========== ========== ========== ========== ====
  1825   BEGIN
  1826           --  SET NOCOU NT ON adde d to preve nt extra r esult sets  from
  1827           --  interferi ng with SE LECT state ments.
  1828      SET NOC OUNT ON;
  1829  
  1830      SELECT   SPatientA ddressSID  as NextOfK indId
  1831      , Patie ntSID
  1832      , Sta3n  as Statio n
  1833      , Addre ssType
  1834      , NameO fContact
  1835      , Stree tAddress1
  1836      , Stree tAddress2
  1837      , City
  1838      , State
  1839      , Zip
  1840      , Phone
  1841      , Phone Work
  1842      FROM  C DWWork.SPa tient.SPat ientAddres s
  1843      WHERE P atientSID=  @sid and  OrdinalNum ber=2;  -- OrdinalNum ber=2, Nex t Of Kin
  1844   END;
  1845   GO
  1846   PRINT N'Cr eating [Ap p].[NVCC_u sp_GetNVAM eds]...';
  1847  
  1848  
  1849   GO
  1850  
  1851  
  1852   CREATE PRO CEDURE [Ap p].[NVCC_u sp_GetNVAM eds]
  1853           --  Add the p arameters  for the st ored proce dure here
  1854           @p id bigint  -- this is  the patie ntsid
  1855   AS
  1856   --======== ========== ========== ========== ========== ========== ========== ========== ===
  1857   --Requesto r                                : Non Va C oordinated  Care Proj ect
  1858   --Author                  : Jerr y Kohler ( Original s cript by D r. Charles  Demosthen es)
  1859   --Object/S P Name                  : NVCC_u sp_GetNVAM eds
  1860   --SERVER                                   
  1861   --Data Bas e                                : CC_REFDO C
  1862   --Schema                                    : App
  1863   --Report                                    : N/A
  1864   --Folder                                    : N/A
  1865   --Report L oc             : N/A
  1866   --Job                     : None
  1867   --Job Loc                 : None
  1868   --Note                    : 
  1869   --Date Cre ated           : 02-0 5-2016
  1870   --
  1871   --Changed                 : 03-0 3-2016  
  1872   --Changed  By                 :  Jerry Kohl er - North west Innov ation Cent er (NWIC)
  1873   --Reason F or Change               : Added  NonVAMedCo mments per  TFS NVCC  project ta sk 1329.
  1874   --                          Also  added Non VAMedDiscl amer, and  a conditio n that
  1875   --                          the  Discontinu edDateTime  is NULL.
  1876   --
  1877   --Changed                 : 02-0 5-2016  
  1878   --Changed  By             : Jerr y Kohler -  Northwest  Innovatio n Center ( NWIC)
  1879   --Reason F or Change               : Remove d station  parameter  in order t o expand t he search
  1880   --                          for  a patient' s VA meds  from a sin gle statio n to any
  1881   --                          stat ion a pati ent is ass ociated wi th.
  1882   --
  1883   --Purpose                 : Retr ieve a pat ient's med ications n ot issued  by VA for
  1884   --                          incl usion into  NVCC docu mentation
  1885   --======== ========== ========== ========== ========== ========== ========== ========== ===
  1886   BEGIN
  1887  
  1888           --  SET NOCOU NT ON adde d to preve nt extra r esult sets  from
  1889           --  interferi ng with SE LECT state ments.
  1890           SE T NOCOUNT  ON;
  1891  
  1892           SE LECT DISTI NCT n.Sta3 n
  1893              ,App.udf_S tationName  (n.Sta3n)  AS Statio nName
  1894              ,n.NonVAMe dSID
  1895                      ,d .LocalDrug NameWithDo se
  1896              ,n.Dosage
  1897              ,n.Medicat ionRoute
  1898                  ,n.Sch edule
  1899              ,n.NonVAMe dComments
  1900              ,n.NonVAMe dDisclaime r
  1901           FR OM CDWWork .NonVAMed. NonVAMed n
  1902       INNER  JOIN CDWWo rk.Dim.Loc alDrug d O N n.LocalD rugSID = d .LocalDrug SID
  1903           WH ERE n.Pati entSID in  (select Pt SID from [ App].[udf_ AllPatient sSIDs](@pi d))
  1904         AND  n.Disconti nuedDateTi me is NULL ;
  1905           
  1906   END;
  1907   GO
  1908   PRINT N'Cr eating [Ap p].[NVCC_u sp_GetOrCr eateUser]. ..';
  1909  
  1910  
  1911   GO
  1912   CREATE PRO CEDURE App .NVCC_usp_ GetOrCreat eUser
  1913           @U serName va rchar(50)
  1914  
  1915   -- NOTICE:
  1916   -- Do not  edit the s tored proc edure live  on the se rver. Code  to genera te
  1917   -- the pro cedures is  stored in  the proje ct reposit ory. Any c hanges mad e
  1918   -- that ar e not reco rded in th e reposito ry will be  overwritt en.
  1919  
  1920   AS
  1921  
  1922   --======== ========== ========== ========== ========== ========== ========== ========== ====
  1923   --Requesto r              : Non  Va Coordin ated Care  Project
  1924   --Author                  : Bria n Diggs
  1925   --Object/S P Name         : NVCC _usp_GetOr CreateUser
  1926   --Server                  : 
  1927   --Data Bas e              : CC_R EFDOC
  1928   --Schema                  : App
  1929   --Report                  : N/A
  1930   --Folder                  : N/A
  1931   --Report L oc             : N/A
  1932   --Job                     : None
  1933   --Job Loc                 : None
  1934   --Note                    : 
  1935   --Date Cre ated           : 06-2 9-2017
  1936   --
  1937   --Last Cha nged           : 
  1938   --Last Cha nged By                 : 
  1939   --Reason F or Change               : 
  1940   --
  1941   --Purpose                 : To r etrieve a  correspond ing record  from App. NVCC_Users V2
  1942   --                          or t o create a nd return  one if non e exists.  For this t o
  1943   --                          work , all colu mns other  that UserN ame must h ave defaul t
  1944   --                          valu es.
  1945   --======== ========== ========== ========== ========== ========== ========== ========== ====
  1946  
  1947   BEGIN
  1948           --  Derived f rom https: //stackove rflow.com/ a/1488387/ 892313
  1949           SE T TRANSACT ION ISOLAT ION LEVEL  SERIALIZAB LE
  1950           BE GIN TRANSA CTION
  1951                    DECL ARE @UserI D int
  1952                    SELE CT @UserID  = UserId  FROM App.N VCC_UsersV 2 WHERE Us erName = @ UserName
  1953                    IF @ UserID IS  NULL
  1954                    BEGI N
  1955                             INSERT  INTO App. NVCC_Users V2 (UserNa me) VALUES  (@UserNam e)
  1956                             SELECT  @UserID =  SCOPE_IDE NTITY()
  1957                    END
  1958                    SELE CT * FROM  App.NVCC_U sersV2 WHE RE UserId  = @UserID
  1959           CO MMIT TRANS ACTION
  1960   END
  1961   GO
  1962   PRINT N'Cr eating [Ap p].[NVCC_u sp_GetPati ent]...';
  1963  
  1964  
  1965   GO
  1966  
  1967  
  1968   CREATE PRO CEDURE [Ap p].[NVCC_u sp_GetPati ent]
  1969           @s tation int ,   --stat ion for pt , restrict s queries  local VA s tation
  1970           @s sn varchar (9) -- thi s is the p atient's S SN
  1971  
  1972   AS
  1973   --======== ========== ========== ========== ========== ========== ========== ========== ====
  1974   --Requesto r              : Non  Va Coordin ated Care  Project
  1975   --Author                  : Jerr y Kohler ( Original s cript by D r. Charles  Demosthen es)
  1976   --Object/S P Name         : NVCC _usp_GetPa tient
  1977   --Server                  : 
  1978   --Data Bas e              : CC_R EFDOC
  1979   --Schema                  : app
  1980   --Report                  : N/A
  1981   --Folder                  : N/A
  1982   --Report L oc             : N/A
  1983   --Job                     : None
  1984   --Job Loc                 : None
  1985   --Note                    : 
  1986   --Date Cre ated           : 01-2 0-2016
  1987   --
  1988   --
  1989   --Last Cha nged           : 02-1 8-2016  
  1990   --Last Cha nged By                 : Jerry  Kohler - N orthwest I nnovation  Center (NW IC)
  1991   --Reason F or Change               : Reques t to also  provide th e name of  the statio n.
  1992   --
  1993   --Purpose                 : To r etrieve a  single pat ient recor d for the  NVCC app.
  1994   --======== ========== ========== ========== ========== ========== ========== ========== ====
  1995   BEGIN
  1996           --  SET NOCOU NT ON adde d to preve nt extra r esult sets  from
  1997           --  interferi ng with SE LECT state ments.
  1998      SET NOC OUNT ON;
  1999  
  2000      SELECT  Cast(Patie ntSID as v archar) as  strPatien tSID
  2001            , Sta3n
  2002            , App.udf_St ationName  (Sta3n) AS  StationNa me
  2003            , PatientNam e
  2004            , PatientLas tName
  2005            , PatientFir stName
  2006            , PatientSSN
  2007            , StreetAddr ess1
  2008            , StreetAddr ess2
  2009            , StreetAddr ess3
  2010            , City
  2011            , Zip
  2012            , Zip4
  2013            , PostalCode
  2014            , Province
  2015            , Country
  2016            , PhoneResid ence
  2017            , PhoneWork
  2018            , PhoneCellu lar
  2019            , DateOfDeat h
  2020            , BadAddress Indicator
  2021            , TemporaryA ddressActi veFlag
  2022            , Gender
  2023            , Age
  2024            , [State]
  2025            , Deceased
  2026            , Eligibilit y
  2027            , DateOfBirt h
  2028            , Ineligible Date
  2029            , Eligibilit yStatus
  2030            , Eligibilit yVerificat ionSource
  2031      FROM  C DWWork.SPa tient.SPat ient
  2032      WHERE P atientSSN  like @ssn  and sta3n= @station;
  2033   END;
  2034   GO
  2035   PRINT N'Cr eating [Ap p].[NVCC_u sp_GetPati entBySid]. ..';
  2036  
  2037  
  2038   GO
  2039  
  2040   CREATE PRO CEDURE [Ap p].[NVCC_u sp_GetPati entBySid]
  2041           @p id int   - -PatientSI D
  2042  
  2043   -- NOTICE:
  2044   -- Do not  edit the s tored proc edure live  on the se rver. Code  to genera te
  2045   -- the pro cedures is  stored in  the proje ct reposit ory. Any c hanges mad e
  2046   -- that ar e not reco rded in th e reposito ry will be  overwritt en.
  2047  
  2048   AS
  2049   --======== ========== ========== ========== ========== ========== ========== ========== ====
  2050   --Requesto r              : Non  Va Coordin ated Care  Project
  2051   --Author                  : Jon  Duckart (O riginal sc ript by Dr . Charles  Demosthene s)
  2052   --Object/S P Name         : NVCC _usp_GetPa tientBySid
  2053   --Server                  : 
  2054   --Data Bas e              : CC_R EFDOC
  2055   --Schema                  : app
  2056   --Report                  : N/A
  2057   --Folder                  : N/A
  2058   --Report L oc             : N/A
  2059   --Job                     : None
  2060   --Job Loc                 : None
  2061   --Note                    : 
  2062   --Date Cre ated           : 04-1 4-2016
  2063   --
  2064   --Last Cha nged           : 06-2 2-2016
  2065   --Last Cha nged By                 : Brian  Diggs - No rthwest In novation C enter (NWI C)
  2066   --Reason F or Change               : Format ting and i dempotence  and signi ng
  2067   --
  2068   --Purpose                 : To r etrieve a  single pat ient recor d for the  NVCC app b y SID.
  2069   --======== ========== ========== ========== ========== ========== ========== ========== ====
  2070   BEGIN
  2071           --  SET NOCOU NT ON adde d to preve nt extra r esult sets  from
  2072           --  interferi ng with SE LECT state ments.
  2073      SET NOC OUNT ON;
  2074  
  2075      SELECT   [PatientS ID]
  2076         ,[Pa tientIEN]
  2077         ,[St a3n] as St ation
  2078         ,[Pa tientName]
  2079         ,[Pa tientLastN ame]
  2080         ,[Pa tientFirst Name]
  2081         ,[Pa tientSSN]
  2082         ,[Sc rSSN]
  2083         ,[St reetAddres s1]
  2084         ,[St reetAddres s2]
  2085         ,[St reetAddres s3]
  2086         ,[Ci ty]
  2087         ,[Zi p]
  2088         ,[Zi p4]
  2089         ,[Po stalCode]
  2090         ,[Pr ovince]
  2091         ,[Co untrySID]
  2092         ,[Co untry]
  2093         ,[Ph oneResiden ce]
  2094         ,[Ph oneWork]
  2095         ,[Ph oneCellula r]
  2096         ,[Mo thersMaide nName]
  2097         ,[Da teOfDeath]
  2098         ,[Da teOfDeathT ext]
  2099         ,[Em ailAddress ]
  2100         ,[Ba dAddressIn dicator]
  2101         ,[Ex cludeFromF acilityDir ectoryFlag ]
  2102         ,[Ad dressChang eInstituti onSID]
  2103         ,[Ad dressChang eStaffSID]
  2104         ,[NO KPrimaryCh angeDateTi me]
  2105         ,[NO KPrimaryCh angeVistaE rrorDate]
  2106         ,[NO KPrimaryCh angeDateTi meTransfor mSID]
  2107         ,[NO KSecondary ChangeDate Time]
  2108         ,[NO KSecondary ChangeVist aErrorDate ]
  2109         ,[NO KSecondary ChangeDate TimeTransf ormSID]
  2110         ,[NO KRelations hipToPatie nt]
  2111         ,[NO KDesigneeS ameAsFlag]
  2112         ,[NO KEmergency ContactSam eAsFlag]
  2113         ,[Te mporaryAdd ressActive Flag]
  2114         ,[Te mporaryAdd ressLastEd itedDateTi me]
  2115         ,[Te mporaryAdd ressLastEd itedVistaE rrorDate]
  2116         ,[Te mporaryAdd ressLastEd itedDateTi meTransfor mSID]
  2117         ,[Te mporaryAdd ressChange Institutio nSID]
  2118         ,[Te mporaryAdd ressStartD ate]
  2119         ,[Te mporaryAdd ressStartV istaErrorD ate]
  2120         ,[Te mporaryAdd ressStartD ateTransfo rmSID]
  2121         ,[Te mporaryAdd ressEndDat e]
  2122         ,[Te mporaryAdd ressEndVis taErrorDat e]
  2123         ,[Te mporaryAdd ressEndDat eTransform SID]
  2124         ,[Co nfidential AddressAct iveFlag]
  2125         ,[CD Flag]
  2126         ,[CD DecidedByN ame]
  2127         ,[CD DecisionDa te]
  2128         ,[CD DecisionVi staErrorDa te]
  2129         ,[CD DecisionDa teTransfor mSID]
  2130         ,[CD ReviewedDa te]
  2131         ,[CD ReviewedVi staErrorDa te]
  2132         ,[CD ReviewedDa teTransfor mSID]
  2133         ,[CD Determinin gInstituti onSID]
  2134         ,[CD Determinat ionType]
  2135         ,[Cu rrentPurpl eHeartDeci sionType]
  2136         ,[Cu rrentPurpl eHeartStat us]
  2137         ,[Pu rpleHeartI nstitution SID]
  2138         ,[Me dicaidNumb er]
  2139         ,[Ra ceSID]
  2140         ,[Ge nder]
  2141         ,[Ag e]
  2142         ,[St ateSID]
  2143         ,[St ate]
  2144         ,[Co unty]
  2145         ,[De ceased]
  2146         ,[Pa tientICN]
  2147         ,[Pa tientICNCh ecksum]
  2148         ,[Ps eudoSSNFla g]
  2149         ,[Pe riodOfServ iceSID]
  2150         ,[Pe riodOfServ ice]
  2151         ,[Cu rrentMeans TestStatus SID]
  2152         ,[Ma ritalStatu sSID]
  2153         ,[Ma ritalStatu s]
  2154         ,[Pe rcentServi ceConnect]
  2155         ,[In suranceCov erageFlag]
  2156         ,[Re ligionSID]
  2157         ,[Re ligion]
  2158         ,[Ag entOrangeE xposureFla g]
  2159         ,[Ag entOrangeL ocationCod e]
  2160         ,[Ra diationExp osureCode]
  2161         ,[Io nizingRadi ationExpos ureFlag]
  2162         ,[SH ADFlag]
  2163         ,[Ve teranFlag]
  2164         ,[Co mbatFlag]
  2165         ,[Co mbatEligib ilityEndDa te]
  2166         ,[Co mbatEligib ilityEndVi staErrorDa te]
  2167         ,[Co mbatEligib ilityEndDa teTransfor mSID]
  2168         ,[Te stPatientF lag]
  2169         ,[CD WPossibleT estPatient Flag]
  2170         ,[Sp inalCordIn juryType]
  2171         ,[En teredIntoF ileDate]
  2172         ,[En teredIntoF ileVistaEr rorDate]
  2173         ,[En teredIntoF ileDateTra nsformSID]
  2174         ,[Em ergencyRes ponseIndic ator]
  2175         ,[El igibilityS ID]
  2176         ,[El igibility]
  2177         ,[El igibilityV ACode]
  2178         ,[Da teOfBirth]
  2179         ,[Da teOfBirthT ext]
  2180         ,[Se nsitiveFla g]
  2181         ,[La stServiceE ntryDate]
  2182         ,[La stServiceE ntryVistaE rrorDate]
  2183         ,[La stServiceE ntryDateTr ansformSID ]
  2184         ,[La stServiceS eparationD ate]
  2185         ,[La stServiceS eparationV istaErrorD ate]
  2186         ,[La stServiceS eparationD ateTransfo rmSID]
  2187         ,[Pr eferredIns titutionSI D]
  2188         ,[PO WFlag]
  2189         ,[PO WLocationS ID]
  2190         ,[PO WFromVista Date]
  2191         ,[PO WToVistaDa te]
  2192         ,[Co mbatFromVi staDate]
  2193         ,[Co mbatToVist aDate]
  2194         ,[Cl aimNumber]
  2195         ,[Ro omBedSID]
  2196         ,[In eligibleDa te]
  2197         ,[In eligibleVi staErrorDa te]
  2198         ,[In eligibleDa teTransfor mSID]
  2199         ,[In eligibleRe ason]
  2200         ,[El igibilityS tatus]
  2201         ,[El igibilityV erificatio nSource]
  2202         ,[GI SLocatorNa me]
  2203         ,[GI SMatchStat usCode]
  2204         ,[GI SMatchScor e]
  2205         ,[GI SMatchMeth odCode]
  2206         ,[GI SMatchedAd dress]
  2207         ,[GI SAddressTy pe]
  2208         ,[GI SStreetSid e]
  2209         ,[GI SPatientAd dressLongi tude]
  2210         ,[GI SPatientAd dressLatit ude]
  2211         ,[GI SAddressUp datedDate]
  2212         ,[GI SFIPSCode]
  2213         ,[GI SMarket]
  2214         ,[GI SSubmarket ]
  2215         ,[GI SSector]
  2216         ,[GI SURH]
  2217         ,[GI SCongressD istrict]
  2218      FROM  C DWWork.SPa tient.SPat ient
  2219           WH ERE
  2220                    Pati entSid= @p id
  2221                    AND  patientnam e <>'*Unkn own at thi s time*'
  2222                    AND  patientnam e is not n ull;
  2223   END;
  2224   GO
  2225   PRINT N'Cr eating [Ap p].[NVCC_u sp_GetPati entBySSN]. ..';
  2226  
  2227  
  2228   GO
  2229  
  2230   CREATE PRO CEDURE App .NVCC_usp_ GetPatient BySSN
  2231           @S SN varchar (50),
  2232           @s ta3n small int
  2233   AS
  2234   --======== ========== ========== ========== ========== ========== ========== ========== ===
  2235   --Requesto r                                : Non Va C oordinated  Care Proj ect
  2236   --Author                  : Bria n Diggs
  2237   --Object/S P Name                  : usp_Ge tPatientBy SSN
  2238   --SERVER                                   
  2239   --Data Bas e                                : CC_REFDO C
  2240   --Schema                                    : PanelMgm t
  2241   --Report                                    : N/A
  2242   --Folder                                    : N/A
  2243   --Report L oc             : N/A
  2244   --Job                     : None
  2245   --Job Loc                 : None
  2246   --Note                    : 
  2247   --Date Cre ated           : 07-1 4-2017
  2248   --
  2249   --Changed                 : 2017 -07-31
  2250   --Changed  By                 :  Brian Digg s
  2251   --Reason F or Change               : Added  (NOLOCK) q uery hint  so that se arcing for  a patient
  2252   --                          will  not block  during th e daily up date.
  2253   --
  2254   --Purpose                 : Retr ieve a pat ient's SID  from the  SSN and st a3n
  2255   --                        : usin g the heav ily indexe d App.AllC DWPatients
  2256   --======== ========== ========== ========== ========== ========== ========== ========== ===
  2257   BEGIN
  2258           SE LECT
  2259                    Pati entSID,
  2260                    Pati entSSN,
  2261                    Sta3 n
  2262           FR OM App.All CDWPatient s WITH (NO LOCK)
  2263           WH ERE
  2264                    Pati entSSN = @ SSN AND st a3n = @sta 3n
  2265   END
  2266   GO
  2267   PRINT N'Cr eating [Ap p].[NVCC_u sp_GetProb s]...';
  2268  
  2269  
  2270   GO
  2271  
  2272   CREATE PRO CEDURE [Ap p].[NVCC_u sp_GetProb s]
  2273           --  Add the p arameters  for the st ored proce dure here
  2274           @p id bigint  -- this is  the patie ntsid
  2275   AS
  2276   --======== ========== ========== ========== ========== ========== ========== ========== ===
  2277   --Requesto r                                : Non Va C oordinated  Care Proj ect
  2278   --Author                  : Jerr y Kohler -  Northwest  Innovatio n Center ( NWIC)
  2279   --Object/S P Name                  : NVCC_u sp_GetProb s
  2280   --SERVER                                   
  2281   --Data Bas e                                : CC_REFDO C
  2282   --Schema                                    : app
  2283   --Report                                    : N/A
  2284   --Folder                                    : N/A
  2285   --Report L oc             : N/A
  2286   --Job                     : None
  2287   --Job Loc                 : None
  2288   --Note                    : 
  2289   --Date Cre ated           : 01-1 4-2016
  2290   --
  2291   --Last Cha nged           : 03-1 6-2016  
  2292   --Last Cha nged By                 : Jerry  Kohler - N orthwest I nnovation  Center (NW IC)
  2293   --Reason F or Change               : TFS Pr oject NVCC , item num ber 1368 -  Eliminate  
  2294   --                          dupl icate prob lem codes  (Brian Dig gs).
  2295   --
  2296   --Last Cha nged           : 02-1 8-2016  
  2297   --Last Cha nged By                 : Jerry  Kohler - N orthwest I nnovation  Center (NW IC)
  2298   --Reason F or Change               : Reques t to also  provide th e station  and statio n
  2299   --                          name .
  2300   --
  2301   --Last Cha nged           : 01-1 9-2016  
  2302   --Last Cha nged By                 : Jerry  Kohler - N orthwest I nnovation  Center (NW IC)
  2303   --Reason F or Change               : Restru ctured the  procedure  into a CT E and sing le
  2304   --                          SELE CT stateme nt.  Added  DISTINCT  to elimina te
  2305   --                          dupl icate retu rned rows,  and tuned  for perfo rmance.
  2306   --
  2307   --Changed                 : 01-1 4-2016  
  2308   --Changed  By                 :  Jerry Kohl er - North west Innov ation Cent er (NWIC)
  2309   --Reason F or Change               : Remove d station  parameter  in order t o expand t he search
  2310   --                          for  a patient' s consults  from a si ngle stati on to any
  2311   --                          stat ion a pati ent is ass ociated wi th.
  2312   --
  2313   --Purpose                 : Retr ieve a pat ient's act ive proble m lists fo r provider
  2314   --                          revi ew while c ompiling N VCC docume ntation.
  2315   --======== ========== ========== ========== ========== ========== ========== ========== ===
  2316   BEGIN
  2317   --declare  @station i nt; set @s tation=508 ; declare  @pid bigin t; set @pi d=1717444;  declare @ sflag int;  set @sfla g=1;
  2318           --  SET NOCOU NT ON adde d to preve nt extra r esult sets  from
  2319           --  interferi ng with SE LECT state ments.
  2320      SET NOC OUNT ON;
  2321  
  2322   --DECLARE  @PID INT =  24257470   --zzteleh ealth pati ent with t ons of dat a
  2323  
  2324      ;
  2325      WITH PT Probs0 (St a3n, Stati onName, Pr oblemListS ID, Patien tSID, ICD9 SID, ICD10 SID, RN, L astModifie dDate) AS
  2326        (
  2327         SELE CT p.Sta3n
  2328                ,App.udf _StationNa me (p.Sta3 n) AS Stat ionName
  2329                ,p.Probl emListSID
  2330                ,p.Patie ntSID
  2331                ,p.ICD9S ID
  2332                ,p.ICD10 SID
  2333                ,RN = CA SE
  2334                    When  ICD9SID < > 0
  2335                       T hen ROW_NU MBER() OVE R (PARTITI ON BY p.IC D9SID  ORD ER BY p.La stModified Date DESC)
  2336                    When  ICD10SID  <> 0
  2337                       T hen ROW_NU MBER() OVE R (PARTITI ON BY p.IC D10SID ORD ER BY p.La stModified Date DESC)
  2338                    Else  -999
  2339                    End
  2340                ,p.LastM odifiedDat e
  2341         FROM  CDWWork.O utpat.Prob lemList p 
  2342         WHER E p.Patien tSID IN (S elect PtSI D From App .udf_AllPa tientsSIDs  (@pid))
  2343           AN D p.Active Flag = 'A'
  2344           AN D ProblemL istConditi on <> 'H'
  2345        ),
  2346  
  2347        PTPro bs1 (Sta3n , StationN ame, ICDCo de, ICDVer sion, Prob lemListSID , Problem,  LastModif iedDate ,R N, Sensiti veDx, Abus eDx, Sickl eDx, HIVDx ) AS
  2348        (
  2349         SELE CT p.Sta3n
  2350                ,p.Stati onName
  2351                ,i.ICD9C ode AS ICD Code
  2352                ,'ICD9'  AS ICDVers ion
  2353                ,p.Probl emListSID
  2354                ,left(i. ICD9Diagno sisText,50 ) AS Probl em
  2355                ,p.LastM odifiedDat e
  2356                ,ROW_NUM BER() OVER  (PARTITIO N BY left( i.ICD9Diag nosisText, 50) ORDER  BY p.LastM odifiedDat e DESC) AS  RN
  2357                             , CASE  WHEN dx.I CDSID is N OT NULL TH EN 1 ELSE  0 END AS S ensitiveDx
  2358                             , dx.A buseDx
  2359                             , dx.S ickleDx
  2360                             , dx.H IVDx
  2361         FROM  PTProbs0  p
  2362         left  outer joi n PanelMgm t.vICD9 i  on p.ICD9S ID = i.ICD 9SID
  2363              LEFT OUTER  JOIN [App ].[NVCC_Se nsitiveDxC odes] dx
  2364              on dx.ICDS ID = p.ICD 9SID
  2365         WHER E p.ICD9SI D <> 0
  2366           AN D p.RN = 1
  2367  
  2368         UNIO N ALL
  2369      
  2370         SELE CT p.Sta3n
  2371                ,p.Stati onName
  2372                ,k.ICD10 Code AS IC DCode
  2373                ,'ICD10'      AS IC DVersion
  2374                ,p.Probl emListSID
  2375                ,left(k. ICD10Diagn osisText,5 0) AS Prob lem
  2376                ,p.LastM odifiedDat e
  2377                ,ROW_NUM BER() OVER  (PARTITIO N BY left( k.ICD10Dia gnosisText ,50) ORDER  BY p.Last ModifiedDa te DESC) A S RN
  2378                             , CASE  WHEN dx.I CDSID is N OT NULL TH EN 1 ELSE  0 END AS S ensitiveDx
  2379                             , dx.A buseDx
  2380                             , dx.S ickleDx
  2381                             , dx.H IVDx
  2382         FROM  PTProbs0  p
  2383         left  outer joi n PanelMgm t.vICD10 k  on p.ICD1 0SID = k.I CD10SID
  2384                LEFT OUT ER JOIN [A pp].[NVCC_ SensitiveD xCodes] dx
  2385              on dx.ICDS ID = p.ICD 10SID
  2386         WHER E p.ICD10S ID <> 0
  2387           AN D p.RN = 1
  2388       )
  2389  
  2390      SELECT  Sta3n
  2391            , StationNam e
  2392            , ICDCode
  2393            , ICDVersion
  2394            , ProblemLis tSID
  2395            , Problem
  2396            , LastModifi edDate
  2397                     ,Se nsitiveDx,  AbuseDx,  SickleDx,  HIVDx
  2398      FROM PT Probs1
  2399      WHERE R N = 1
  2400      ORDER B Y LastModi fiedDate D ESC;
  2401  
  2402   END;
  2403  
  2404   --exec nva .getProbs  @station=5 08, @pid=1 717444;
  2405   --exec nva .getSensDx Codes;
  2406   GO
  2407   PRINT N'Cr eating [Ap p].[NVCC_u sp_GetSens Dx]...';
  2408  
  2409  
  2410   GO
  2411  
  2412  
  2413   CREATE PRO CEDURE [Ap p].[NVCC_u sp_GetSens Dx]
  2414           --  Add the p arameters  for the st ored proce dure here
  2415           @p id bigint  -- this is  the patie ntsid
  2416   --======== ========== ========== ========== ========== ========== ========== ========== ====
  2417   --Requesto r              : Non  Va Coordin ated Care  Project
  2418   --Author                  : Jerr y Kohler ( Original s cript by D r. Charles  Demosthen es)
  2419   --Object/S P Name         : NVCC _usp_GetSe nsDx
  2420   --Server                  : 
  2421   --Data Bas e              : CC_R EFDOC
  2422   --Schema                  : App
  2423   --Report                  : N/A
  2424   --Folder                  : N/A
  2425   --Report L oc             : N/A
  2426   --Job                     : None
  2427   --Job Loc                 : None
  2428   --Note                    : 
  2429   --Date Cre ated           : 01-2 0-2016
  2430   --
  2431   --Changed                 : 01-2 0-2016
  2432   --Changed  By             : Jerr y Kohler
  2433   --Reason F or Change      : Remo ved statio n paramete r; we want  the data  for the
  2434   --                          pati ent no mat ter where  that patie nt was tre ated.
  2435   --
  2436   --Changed                 : 01-2 9-2016
  2437   --Changed  By             : Jerr y Kohler
  2438   --Reason F or Change      : Cons olidated s ome querie s the scri pt was doi ng into fe wer,
  2439   --                          smal ler ones s ince we no w have a t able conta ining all  of
  2440   --                          the  sensitive  diagnoses  & ICD SIDS  (9 & 10)
  2441   --
  2442   --Purpose                 : Retr ieve any s ensitive d iagnoses t hat may ex ist for a
  2443   --                          pati ent.  If t here are a ny, they r equire spe cial handl ing
  2444   --                          to d etermine w hich outso urce partn ers can kn ow about t hem.
  2445   --======== ========== ========== ========== ========== ========== ========== ========== ====
  2446   AS
  2447  
  2448   BEGIN
  2449       -- dec lare @pid  bigint; se t @pid=171 7444;
  2450           --  SET NOCOU NT ON adde d to preve nt extra r esult sets  from
  2451           --  interferi ng with SE LECT state ments.
  2452           SE T NOCOUNT  ON;
  2453  
  2454       DECLAR E @flag in t;
  2455       SET @f lag=0;
  2456  
  2457       -- Che ck all of  a patient' s recorded  diagnoses  against o ur table o f sensitiv e
  2458       -- dia gnoses, an d record t he various  diagnosis  flags.
  2459       SELECT  --TOP 300
  2460                    CASE
  2461                             WHEN p .ICD10SID  > 0 THEN p .ICD10SID
  2462                             ELSE p .ICD9SID
  2463                    END  as Code
  2464                    ,CAS E
  2465                             WHEN p .ICD10SID  > 0 THEN ' ICD10'
  2466                             ELSE ' ICD9'
  2467                    END  as  Coding System
  2468                    ,CAS E
  2469                             WHEN p .ICD10SID  > 0 THEN 
  2470                                      (select  top 1 s.Ab useDx from  App.NVCC_ SensitiveD xCodes s w here p.ICD 10SID = s. ICDSID)
  2471                             ELSE
  2472                                      (select  top 1 t.Ab useDx from  App.NVCC_ SensitiveD xCodes t w here p.ICD 9SID = t.I CDSID)
  2473                    END  as AbuseDx
  2474                    ,CAS E
  2475                             WHEN p .ICD10SID  > 0 THEN 
  2476                                      (select  top 1 s.Si ckleDx fro m App.NVCC _Sensitive DxCodes s  where p.IC D10SID = s .ICDSID)
  2477                             ELSE
  2478                                      (select  top 1 t.Si ckleDx fro m App.NVCC _Sensitive DxCodes t  where p.IC D9SID = t. ICDSID)
  2479                    END  as SickleD x
  2480                    ,CAS E
  2481                             WHEN p .ICD10SID  > 0 THEN 
  2482                                      (select  top 1 s.HI VDx from A pp.NVCC_Se nsitiveDxC odes s whe re p.ICD10 SID = s.IC DSID)
  2483                             ELSE
  2484                                      (select  top 1 t.HI VDx from A pp.NVCC_Se nsitiveDxC odes t whe re p.ICD9S ID = t.ICD SID)
  2485                    END  as HIVDx
  2486        INTO  #ptsdx
  2487        FROM  CDWWork.Ou tpat.VDiag nosis p
  2488        JOIN  App.NVCC_S ensitiveDx Codes x on  (p.ICD9SI D = x.ICDS ID OR p.IC D10SID = x .ICDSID)
  2489        WHERE  PatientSI D in (sele ct PtSID f rom [App]. [udf_AllPa tientsSIDs ](@pid));
  2490  
  2491  
  2492             
  2493        IF (( select sum (AbuseDx)  from #ptsd x) > 0)  s et @flag=@ flag+1;
  2494        IF (( select sum (HIVDx) fr om #ptsdx)  > 0)    s et @flag=@ flag+4;
  2495        IF (( select sum (SickleDx)  from #pts dx) > 0) s et @flag=@ flag+16;
  2496  
  2497  
  2498        -- Ch eck all of  a patient 's recorde d ICD code s recorded  on his pr oblem list
  2499        -- ag ainst our  table of s ensitive d iagnoses,  and record  the vario us
  2500        -- di agnosis fl ags.
  2501        SELEC T prb.ICD9 SID
  2502               ,prb.ICD1 0SID
  2503               ,prb.Pati entSID
  2504               ,x.AbuseD x
  2505               ,x.Sickle Dx
  2506               ,x.HIVDx 
  2507        INTO  #ptsprb
  2508        FROM  CDWWork.Ou tpat.Probl emList AS  prb 
  2509        INNER  JOIN App. NVCC_Sensi tiveDxCode s x on (pr b.ICD9SID  = x.ICDSID  OR prb.IC D10SID = x .ICDSID)
  2510        WHERE  PatientSI D in (sele ct PtSID f rom [App]. [udf_AllPa tientsSIDs ](@pid))
  2511          AND  prb.Activ eFlag = 'A '
  2512          AND  prb.Probl emListCond ition <> ' H';
  2513  
  2514        if (( select sum (AbuseDx)  from #ptsp rb) > 0) s et @flag=@ flag+2;
  2515        if (( select sum (HIVDx) fr om #ptsprb )   > 0) s et @flag=@ flag+8;
  2516        if (( select sum (SickleDx)  from #pts prb)> 0) s et @flag=@ flag+32;
  2517  
  2518  
  2519        drop  table #pts dx;
  2520        drop  table #pts prb;
  2521  
  2522        selec t @flag as  sensdxfla g;
  2523        --exe c [App].[N VCC_usp_Ge tSensDx] @ pid=171744 4;
  2524        end;
  2525   GO
  2526   PRINT N'Cr eating [Ap p].[NVCC_u sp_GetVAMe ds]...';
  2527  
  2528  
  2529   GO
  2530  
  2531   CREATE PRO CEDURE [Ap p].[NVCC_u sp_GetVAMe ds]
  2532           @p id bigint  -- this is  the patie ntsid
  2533  
  2534   -- NOTICE:
  2535   -- Do not  edit the s tored proc edure live  on the se rver. Code  to genera te
  2536   -- the pro cedures is  stored in  the proje ct reposit ory. Any c hanges mad e
  2537   -- that ar e not reco rded in th e reposito ry will be  overwritt en.
  2538  
  2539   AS
  2540   --======== ========== ========== ========== ========== ========== ========== ========== ===
  2541   --Requesto r                                : Non Va C oordinated  Care Proj ect
  2542   --Author                  : Jerr y Kohler ( Original s cript by D r. Charles  Demosthen es)
  2543   --Object/S P Name                  : NVCC_u sp_GetVAMe ds
  2544   --SERVER                                   
  2545   --Data Bas e                                : CC_REFDO C
  2546   --Schema                                    : App
  2547   --Report                                    : N/A
  2548   --Folder                                    : N/A
  2549   --Report L oc             : N/A
  2550   --Job                     : None
  2551   --Job Loc                 : None
  2552   --Note                    : 
  2553   --Date Cre ated           : 02-0 4-2016
  2554   --
  2555   --Last Cha nged           : 08-2 3-2016
  2556   --Last Cha nged By                 : Jerry  Kohler - N orthwest I nnovation  Center (NW IC)
  2557   --Reason F or Change               : Users  registerin g complain ts that RE FDOC is no t showing
  2558   --                          the  same numbe r of curre nt prescri ptions as  CPRS.
  2559   --                          Afte r a meetin g with Jud y & Dr. D  they had u s change
  2560   --                          the  criteria t o all pres criptions  released o ver the la st
  2561   --                          year  regardles s of statu s or curre ntly takin g (see
  2562   --                          comm ents embed ded below)
  2563   --
  2564   --Last Cha nged           : 08-2 2-2016
  2565   --Last Cha nged By                 : Brian  Diggs - No rthwest In novation C enter (NWI C)
  2566   --Reason F or Change               : Reconc iled with  version on  server.
  2567   --                          Upda ted docume ntation an d creation /signing s tandards
  2568   --                                 : Remove d station  parameter  in order t o expand t he search
  2569   --                          for  a patient' s VA meds  from a sin gle statio n to any
  2570   --                          stat ion a pati ent is ass ociated wi th.
  2571   --
  2572   --Purpose                 : Retr ieve a pat ient's med ications i ssued by V A for
  2573   --                          incl usion into  NVCC docu mentation
  2574   --======== ========== ========== ========== ========== ========== ========== ========== ===
  2575  
  2576  
  2577   BEGIN
  2578       -- SET  NOCOUNT O N added to  prevent e xtra resul t sets fro m
  2579       -- int erfering w ith SELECT  statement s.
  2580       SET NO COUNT ON;
  2581  
  2582       WITH M yDrugs AS
  2583          (
  2584   --      de clare @PID  int = 100 0862763
  2585   --      se lect PTSid  from [App ].[udf_All PatientsSI Ds](@pid)
  2586           SE LECT ROF.S ta3n
  2587                  ,ROF.[ RxOutpatSI D]
  2588                  ,ROF.[ FillNumber ]
  2589                  ,RO.[R xStatus]
  2590                  ,ROF.[ LocalDrugN ameWithDos e]
  2591                  ,ROF.[ IssueDate]
  2592                  ,ROF.[ FillDateTi me]
  2593                               ,RO. NextPossib leFillDate
  2594                  ,ROF.[ Qty]
  2595                  ,ROF.[ DaysSupply ]
  2596                               ,RO. [MaxRefill s]
  2597                  ,Row_N umber() OV ER(partiti on by ROF. [LocalDrug NameWithDo se] Order  by ROF.[Fi llDateTime ] desc) AS  Rn
  2598           FR OM [CDWWor k].[RxOut] .[RxOutpat Fill] ROF
  2599                             INNER  JOIN CDWWo rk.RxOut.R xOutpat AS  RO
  2600                                      ON ROF.R xOutpatSID  = RO.RxOu tpatSID
  2601           WH ERE ROF.Pa tientSID i n (select  PtSID from  [App].[ud f_AllPatie ntsSIDs](@ pid)) 
  2602              AND (Relea seDateTime  > dateadd (year, -1,  SYSDATETI ME()))
  2603                      AN D ReleaseD ateTime IS  NOT NULL
  2604          )
  2605       
  2606           SE LECT dl.St a3n
  2607                  ,dl.rx outpatsid
  2608                  ,dl.lo caldrugnam ewithdose
  2609                  ,cast( dl.filldat etime as d ate) as fi lldate
  2610                  ,dl.qt y as qty
  2611                  ,dl.Fi llNumber
  2612                  ,sig.S ig
  2613                  ,dl.is suedate
  2614                               ,ISN ULL(cast(d l.NextPoss ibleFillDa te as varc har), 'N/A ') as next possiblefi lldate
  2615                               ,ISN ULL(dl.max refills, ' 0') as max refills
  2616                               ,dl. DaysSupply  AS dayssu pply
  2617                               ,dl. RxStatus
  2618           FR OM MyDrugs  dl
  2619           IN NER JOIN C DWWork.RxO ut.RxOutpa tSig sig o n dl.Rxout patsid=sig .RxOutpatS ID
  2620           WH ERE dl.Rn  = 1
  2621       ORDER  BY dl.RxSt atus, dl.F illDateTim e desc;
  2622       
  2623   END;
  2624   GO
  2625   PRINT N'Cr eating [Ap p].[NVCC_u sp_GetXdwF acility].. .';
  2626  
  2627  
  2628   GO
  2629  
  2630   CREATE PRO CEDURE [Ap p].[NVCC_u sp_GetXdwF acility]
  2631           --  @LCustome rID is fro m CDWWork. LCustomer. LCustomer
  2632           @L CustomerID  int
  2633   AS
  2634   --======== ========== ========== ========== ========== ========== ========== ========== ====
  2635   --Requesto r              : Non  Va Coordin ated Care  Project
  2636   --Author                  : Bria n Diggs
  2637   --Object/S P Name         : NVCC _usp_GetXd wFacility
  2638   --Server                  : 
  2639   --Data Bas e              : CC_R EFDOC
  2640   --Schema                  : app
  2641   --Report                  : N/A
  2642   --Folder                  : N/A
  2643   --Report L oc             : N/A
  2644   --Job                     : None
  2645   --Job Loc                 : None
  2646   --Note                    : 
  2647   --Date Cre ated           : 2017 -02-14
  2648   --
  2649   --
  2650   --Last Cha nged           : 
  2651   --Last Cha nged By                 : 
  2652   --Reason F or Change               : 
  2653   --
  2654   --Purpose                 : To g et the sit es for whi ch a user  has PHI/PI I access
  2655   --======== ========== ========== ========== ========== ========== ========== ========== ====
  2656   --Uses: Ap p.udf_Stat ionName
  2657   --Uses: CD WWork.LCus tomer.AllP ermissions
  2658   --Uses: CD WWork.Dim. Sta3n
  2659  
  2660   BEGIN
  2661           SE LECT
  2662                    s.St a3n AS Fac ilityID
  2663                    ,App .udf_Stati onName(s.S ta3n) AS F acilityNam e
  2664                    ,s.V ISNFY17 AS  VISN
  2665                    ,s.D istrictNum berFY17 AS  District
  2666           FR OM CDWWork .LCustomer .AllPermis sions AS a p
  2667                    JOIN  CDWWork.D im.Sta3n A S s
  2668                             ON ap. Sta3n = s. Sta3n
  2669           WH ERE 
  2670                    ap.L CustomerID  = @LCusto merID 
  2671                    AND  ap.PHIPII  = 1 
  2672                    AND  ap.Sta3n >  0
  2673                    AND  s.Active =  'Y'
  2674   END
  2675   GO
  2676   PRINT N'Cr eating [Ap p].[NVCC_u sp_GetXdwF acilityByS ta3n]...';
  2677  
  2678  
  2679   GO
  2680  
  2681   CREATE PRO CEDURE [Ap p].[NVCC_u sp_GetXdwF acilityByS ta3n]
  2682           @S ta3n small int
  2683  
  2684   -- NOTICE:
  2685   -- Do not  edit the s tored proc edure live  on the se rver. Code  to genera te
  2686   -- the pro cedures is  stored in  the proje ct reposit ory. Any c hanges mad e
  2687   -- that ar e not reco rded in th e reposito ry will be  overwritt en.
  2688  
  2689   AS
  2690   --======== ========== ========== ========== ========== ========== ========== ========== ====
  2691   --Requesto r              : Non  Va Coordin ated Care  Project
  2692   --Author                  : Bria n Diggs
  2693   --Object/S P Name         : NVCC _usp_GetXd wFacilityB ySta3n
  2694   --Server                  : 
  2695   --Data Bas e              : CC_R EFDOC
  2696   --Schema                  : app
  2697   --Report                  : N/A
  2698   --Folder                  : N/A
  2699   --Report L oc             : N/A
  2700   --Job                     : None
  2701   --Job Loc                 : None
  2702   --Note                    : 
  2703   --Date Cre ated           : 2017 -02-14
  2704   --
  2705   --
  2706   --Last Cha nged           : 
  2707   --Last Cha nged By                 : 
  2708   --Reason F or Change               : 
  2709   --
  2710   --Purpose                 : To g et details  about a g iven site  from the S ta3n
  2711   --======== ========== ========== ========== ========== ========== ========== ========== ====
  2712   --Uses: Ap p.udf_Stat ionName
  2713   --Uses: CD WWork.Dim. Sta3n
  2714  
  2715   BEGIN
  2716           SE LECT
  2717                    s.St a3n AS Fac ilityID
  2718                    ,App .udf_Stati onName(s.S ta3n) AS F acilityNam e
  2719                    ,s.V ISNFY17 AS  VISN
  2720                    ,s.D istrictNum berFY17 AS  District
  2721           FR OM CDWWork .Dim.Sta3n  AS s
  2722           WH ERE 
  2723                    s.St a3n = @Sta 3n
  2724   END
  2725   GO
  2726   PRINT N'Cr eating [Ap p].[NVCC_u sp_GetXdwU ser]...';
  2727  
  2728  
  2729   GO
  2730  
  2731   CREATE PRO CEDURE [Ap p].[NVCC_u sp_GetXdwU ser]
  2732           --  @username  is the ne twork (AD)  username/ login of t he user
  2733           @u sername va rchar(50)
  2734   AS
  2735   --======== ========== ========== ========== ========== ========== ========== ========== ====
  2736   --Requesto r              : Non  Va Coordin ated Care  Project
  2737   --Author                  : Bria n Diggs
  2738   --Object/S P Name         : NVCC _usp_GetXd wUser
  2739   --Server                  : 
  2740   --Data Bas e              : CC_R EFDOC
  2741   --Schema                  : app
  2742   --Report                  : N/A
  2743   --Folder                  : N/A
  2744   --Report L oc             : N/A
  2745   --Job                     : None
  2746   --Job Loc                 : None
  2747   --Note                    : 
  2748   --Date Cre ated           : 2017 -02-14
  2749   --
  2750   --
  2751   --Last Cha nged           : 
  2752   --Last Cha nged By                 : 
  2753   --Reason F or Change               : 
  2754   --
  2755   --Purpose                 : To g et LCustom er and AD  informatio n about a  user
  2756   --======== ========== ========== ========== ========== ========== ========== ========== ====
  2757   --Uses: CD WWork.NDim .ActiveDir ectoryAcco unt
  2758   --Uses: CD WWork.LCus tomer.LCus tomer
  2759   --Uses: CD WWork.Dim. Sta3n
  2760  
  2761   BEGIN
  2762           SE LECT TOP 1
  2763                    UPPE R(ada.SamA ccountName ) AS NetWo rkName
  2764                    ,ada .Surname A S LastName
  2765                    ,ada .GivenName  AS FirstN ame
  2766                    ,lc. LCustomerI D
  2767                    ,Acc ountEmailA ddress as  Email
  2768                    ,lc. UpdatedDat e as DateA dded
  2769                    ,lc. InferredSt a3n
  2770                    ,s.S ta3n AS AD LoginInfer redSta3n
  2771           FR OM
  2772                    CDWW ork.NDim.A ctiveDirec toryAccoun t AS ada
  2773                    LEFT  JOIN CDWW ork.LCusto mer.LCusto mer AS lc
  2774                             ON ada .SamAccoun tName = lc .ADLogin
  2775                    LEFT  JOIN CDWW ork.Dim.St a3n s
  2776                             ON s.S iteCode =  SUBSTRING( UPPER(@use rname), 4,  3)
  2777           WH ERE SamAcc ountName =  @username
  2778           OR DER BY lc. UpdatedDat e DESC
  2779   END
  2780   GO
  2781   PRINT N'Cr eating [Ap p].[NVCC_u sp_Product ionAccessL ogUniqueSt a3n]...';
  2782  
  2783  
  2784   GO
  2785   --DROP PRO CEDURE App .NVCC_usp_ Production AccessLogU niqueSta3n
  2786  
  2787   CREATE PRO CEDURE [Ap p].[NVCC_u sp_Product ionAccessL ogUniqueSt a3n]
  2788  
  2789   -- NOTICE:
  2790   -- Do not  edit the s tored proc edure live  on the se rver. Code  to genera te
  2791   -- the pro cedures is  stored in  the proje ct reposit ory. Any c hanges mad e
  2792   -- that ar e not reco rded in th e reposito ry will be  overwritt en.
  2793  
  2794   AS
  2795   --======== ========== ========== ========== ========== ========== ========== ========== ====
  2796   --Requesto r              : Non  Va Coordin ated Care  Project
  2797   --Author                  : Bria n Diggs
  2798   --Object/S P Name         : NVCC _usp_Produ ctionAcces sLogUnique Sta3n
  2799   --Server                  : 
  2800   --Data Bas e              : CC_R EFDOC
  2801   --Schema                  : App
  2802   --Report                  : N/A
  2803   --Folder                  : N/A
  2804   --Report L oc             : N/A
  2805   --Job                     : None
  2806   --Job Loc                 : None
  2807   --Note                    : 
  2808   --Date Cre ated           : 05-2 7-2016
  2809   --
  2810   --Last Cha nged           : 2017 -07-24
  2811   --Last Cha nged By                 : Brian  Diggs
  2812   --Reason F or Change               : Conver t to using  NVCC_Prod uctionLog
  2813   --
  2814   --Purpose                 : Get  unique sta tions from  the acces s log
  2815   --======== ========== ========== ========== ========== ========== ========== ========== ====
  2816   --Uses: Ap p.NVCC_Pro ductionLog
  2817   --Uses: Ap p.udf_Stat ionName
  2818   BEGIN
  2819           SE LECT
  2820                    Sta3 n,
  2821                    App. udf_Statio nName(Sta3 n) AS Stat ion
  2822           FR OM (
  2823                    SELE CT DISTINC T
  2824                             Sta3n
  2825                    FROM
  2826                             App.NV CC_Product ionLog
  2827           )  S
  2828           OR DER BY Sta tion
  2829   END
  2830   GO
  2831   PRINT N'Cr eating [Ap p].[NVCC_u sp_Product ionAccessL ogUniqueUs ers]...';
  2832  
  2833  
  2834   GO
  2835   --DROP PRO CEDURE App .NVCC_usp_ Production AccessLogU niqueUsers
  2836  
  2837   CREATE PRO CEDURE [Ap p].[NVCC_u sp_Product ionAccessL ogUniqueUs ers]
  2838  
  2839   -- NOTICE:
  2840   -- Do not  edit the s tored proc edure live  on the se rver. Code  to genera te
  2841   -- the pro cedures is  stored in  the proje ct reposit ory. Any c hanges mad e
  2842   -- that ar e not reco rded in th e reposito ry will be  overwritt en.
  2843  
  2844   AS
  2845   --======== ========== ========== ========== ========== ========== ========== ========== ====
  2846   --Requesto r              : Non  Va Coordin ated Care  Project
  2847   --Author                  : Bria n Diggs
  2848   --Object/S P Name         : NVCC _usp_Produ ctionAcces sLogUnique Users
  2849   --Server                  : 
  2850   --Data Bas e              : CC_R EFDOC
  2851   --Schema                  : App
  2852   --Report                  : N/A
  2853   --Folder                  : N/A
  2854   --Report L oc             : N/A
  2855   --Job                     : None
  2856   --Job Loc                 : None
  2857   --Note                    : 
  2858   --Date Cre ated           : 05-2 7-2016
  2859   --
  2860   --Last Cha nged           : 2017 -07-24
  2861   --Last Cha nged By                 : Brian  Diggs
  2862   --Reason F or Change               : Conver t from vNV CC_Produci onAccessLo g, SStaff,  and NVCC_ Users
  2863   --                        : to N VCC_Produc tionLog an d LCustome r
  2864   --
  2865   --Purpose                 : Get  unique use rs from th e access l og
  2866   --======== ========== ========== ========== ========== ========== ========== ========== ====
  2867   --Uses: Ap p.NVCC_Pro ductionLog
  2868   --Uses: CD WWork.LCus tomer.LCus tomer
  2869   BEGIN
  2870           SE LECT
  2871                    U.Us erID,
  2872                    lc.L astName +  ', ' + lc. FirstName  AS StaffNa me,
  2873                    U.St a3n
  2874           FR OM (
  2875                    SELE CT DISTINC T
  2876                             pl.Use rID,
  2877                             pl.Sta 3n
  2878                    FROM
  2879                             App.NV CC_Product ionLog pl
  2880           )  AS U
  2881                    LEFT  JOIN CDWW ork.LCusto mer.LCusto mer lc
  2882                             ON U.U serID = lc .ADDomain  + '\' + lc .ADLogin
  2883           OR DER BY Sta ffName
  2884   END
  2885   GO
  2886   PRINT N'Cr eating [Ap p].[NVCC_u sp_UniqueV eterans].. .';
  2887  
  2888  
  2889   GO
  2890  
  2891   CREATE PRO CEDURE [Ap p].[NVCC_u sp_UniqueV eterans]
  2892  
  2893   -- NOTICE:
  2894   -- Do not  edit the s tored proc edure live  on the se rver. Code  to genera te
  2895   -- the pro cedures is  stored in  the proje ct reposit ory. Any c hanges mad e
  2896   -- that ar e not reco rded in th e reposito ry will be  overwritt en.
  2897  
  2898   AS
  2899   --======== ========== ========== ========== ========== ========== ========== ========== ====
  2900   --Requesto r              : Non  Va Coordin ated Care  Project
  2901   --Author                  : Bria n Diggs
  2902   --Object/S P Name         : App. NVCC_usp_U niqueVeter ans
  2903   --Server                  : 
  2904   --Data Bas e              : CC_R EFDOC
  2905   --Schema                  : app
  2906   --Report                  : N/A
  2907   --Folder                  : N/A
  2908   --Report L oc             : N/A
  2909   --Job                     : None
  2910   --Job Loc                 : None
  2911   --Note                    : 
  2912   --Date Cre ated           : 11-0 2-2016
  2913   --
  2914   --Last Cha nged           : 
  2915   --Last Cha nged By                 : 
  2916   --Reason F or Change               : 
  2917   --
  2918   --Purpose                 : To g et aggrega ted counts  of RDPs a nd unique  veterans a t
  2919   --                          stat ion and VI SN levels  of aggrega tion
  2920   --======== ========== ========== ========== ========== ========== ========== ========== ====
  2921  
  2922   BEGIN
  2923           SE LECT 
  2924                    pl.P atientICN,  pl.Sta3n,  s.VISNFY1 7, s.Distr ictNumberF Y17 AS Dis trict
  2925           IN TO #TMP
  2926           FR OM 
  2927                    App. NVCC_Produ ctionLog p l
  2928                    INNE R JOIN CDW Work.Dim.S ta3n s
  2929                             ON pl. Sta3n = s. Sta3n
  2930  
  2931           SE LECT
  2932                    ROW_ NUMBER() O VER (ORDER  BY Distri ct, VISNFY 17, Sta3n)  AS ID,
  2933                    Dist rict,
  2934                    VISN FY17,
  2935                    Sta3 n,
  2936                    App. udf_Statio nName(Sta3 n) AS Stat ion,
  2937                    RDP,
  2938                    Uniq ueVeterans
  2939           FR OM (
  2940                    SELE CT
  2941                             Distri ct,
  2942                             VISNFY 17,
  2943                             Sta3n,
  2944                             count( *) AS RDP,
  2945                             count( distinct P atientICN)  AS Unique Veterans
  2946                    FROM  #TMP
  2947                    GROU P BY Sta3n , VISNFY17 , District
  2948                    UNIO N
  2949                    SELE CT
  2950                             Distri ct,
  2951                             VISNFY 17,
  2952                             NULL A S Sta3n,
  2953                             count( *) AS RDP,
  2954                             count( distinct P atientICN)  AS Unique Veterans
  2955                    FROM  #TMP
  2956                    GROU P BY VISNF Y17, Distr ict
  2957                    UNIO N
  2958                    SELE CT
  2959                             Distri ct,
  2960                             NULL A S VISNFY17 ,
  2961                             NULL A S Sta3n, 
  2962                             count( *) AS RDP,
  2963                             count( distinct P atientICN)  AS Unique Veterans
  2964                    FROM  #TMP
  2965                    GROU P BY Distr ict
  2966                    UNIO N
  2967                    SELE CT
  2968                             NULL A S District ,
  2969                             NULL A S VISNFY17 ,
  2970                             NULL A S Sta3n, 
  2971                             count( *) AS RDP,
  2972                             count( distinct P atientICN)  AS Unique Veterans
  2973                    FROM  #TMP
  2974  
  2975           )  A
  2976           OR DER BY Dis trict, VIS NFY17, Sta 3n
  2977  
  2978           DR OP TABLE # TMP
  2979   END
  2980   GO
  2981   PRINT N'Cr eating [Ap p].[NVCC_u sp_UpdateP roductionL og]...';
  2982  
  2983  
  2984   GO
  2985  
  2986   CREATE PRO CEDURE App .NVCC_usp_ UpdateProd uctionLog
  2987  
  2988   -- NOTICE:
  2989   -- Do not  edit the s tored proc edure live  on the se rver. Code  to genera te
  2990   -- the pro cedures is  stored in  the proje ct reposit ory. Any c hanges mad e
  2991   -- that ar e not reco rded in th e reposito ry will be  overwritt en.
  2992  
  2993   AS
  2994   --======== ========== ========== ========== ========== ========== ========== ========== ====
  2995   --Requesto r              : Non  Va Coordin ated Care  Project
  2996   --Author                  : Bria n Diggs
  2997   --Object/S P Name         : App. NVCC_usp_U pdateProdu ctionLog
  2998   --Server                  : 
  2999   --Data Bas e              : CC_R EFDOC
  3000   --Schema                  : App
  3001   --Report                  : N/A
  3002   --Folder                  : N/A
  3003   --Report L oc             : N/A
  3004   --Job                     : None
  3005   --Job Loc                 : None
  3006   --Note                    : 
  3007   --Date Cre ated           : 2017 -07-21
  3008   --
  3009   --Last Cha nged           : 2017 -08-01
  3010   --Last Cha nged By                 : Brian  Diggs
  3011   --Reason F or Change               : Explic it check t hat Access DateTime i s not null
  3012   --                          and  UserID and  HostName  (to elimin ate possib le
  3013   --                          NULL  predicate s)
  3014   --
  3015   --Purpose                 : Proc edure to b e run peri odically t o update t he table
  3016   --                          NVCC _Productio nLog from  the table  NVCC_Acces sLog
  3017   --                          base d on the c riteria of  what is c onsidered  to be a
  3018   --                          pack age create d in the p roduction  environmen t
  3019   --
  3020   --                          NVCC _Productio nLog is a  non-normal ized set o f data
  3021   --                          (sin ce it can  be defined  based on  the conten ts of
  3022   --                          NVCC _AccessLog ) that is  indexed/op timized fo r reportin g
  3023   --======== ========== ========== ========== ========== ========== ========== ========== ====
  3024  
  3025   BEGIN
  3026           DE CLARE @Las tID int;
  3027           SE LECT @Last ID = MAX(A ccessLogID ) FROM App .NVCC_Prod uctionLog
  3028  
  3029           IN SERT INTO  App.NVCC_P roductionL og
  3030           SE LECT
  3031                    al.A ccessLogID ,
  3032                    al.U serID,
  3033                    al.A ccessDateT ime,
  3034                    al.P atientSID,
  3035                    p.Pa tientICN,
  3036                    p.St a3n
  3037           FR OM
  3038                    App. NVCC_Acces sLog al
  3039                    INNE R JOIN CDW Work.Patie nt.Patient  p
  3040                             ON al. PatientSID  = p.Patie ntSID
  3041           WH ERE
  3042                     al.UserID  NOT IN ('V HA20\
U SER ', 'VHA20\ USER ', 'VHA20\ USER ', 'VHA20\ US E R ', 'VHA20\ USE R
') 
  3043                    AND  al.UserID  IS NOT NUL L
  3044                    AND  (
  3045                              al.HostNam e = ' SERVER . URL         ' OR
  3046                             --dev. nwic was b eing used  to host us ers who co uld not co vert to th e VIA vers ion during  these dat es
  3047                               (al.HostNa me = ' SERVER .portland. URL         ' AND Acce ssDateTime  BETWEEN ' 2016-10-19 ' AND '201 6-11-15')
  3048                              OR al.Host Name = 'va ww.refdoc. DNS     ' --the EW IS hosted  national p roduction  site
  3049                    )
  3050                    AND  al.HostNam e IS NOT N ULL
  3051                    AND  AccessDate Time IS NO T NULL
  3052                    AND  al.Action  = 'PDF'
  3053                    AND  ((AccessLo gID > @Las tID) OR (@ LastID IS  NULL))
  3054   END
  3055   GO
  3056   PRINT N'Cr eating [Ap p].[NVCC_u sp_UsageDa ta2]...';
  3057  
  3058  
  3059   GO
  3060  
  3061   CREATE PRO CEDURE [Ap p].[NVCC_u sp_UsageDa ta2]
  3062           --  @timegrou p is a cha racter par ameter whi ch can tak e values N ULL, 'day' , 'week',
  3063           --  'month',  'quarter',  'year', o r 'ever'.  NULL is eq uivalent t o 'ever'.  Any other  value
  3064           --  will resu lt in unde find behav ior.
  3065           @t imegroup v archar(max ) = NULL,
  3066           --  @statisti c is a cha racter par ameter whi ch can tak e values ' count' or  'cumulativ e'.
  3067           --  Any other  value wil l result i n undefine d behavior .
  3068           --  For 'coun t', the va lue N repr esents num ber within  that time group and  any
  3069           --  other gro uping cate gories
  3070           --  For 'cumu lative', t he value N  represent s the cumu lative num ber, over  time,
  3071           --  up to tha t timepoin t, separat ed by any  other grou ping categ ories
  3072           @s tatistic v archar(max ) = NULL,
  3073           --  @sta3n is  a charact er paramet er which c an either  NULL, a si ngle stati on number,
  3074           --  or a comm a demlimit ed list of  station n umbers. NU LL implies  that the  data for
  3075           --  all stati ons should  be return ed/used an d that no  stratifica tion by st ation shou ld
  3076           --  be done.  A single s tation num ber (as a  string) wi ll return  data for o nly that
  3077           --  station.  A comma de limited li st of stat ion number s will res trict the  returned d ata
  3078           --  to those  present in  the list  and any ag gregation  or ordinat ion will b e done
  3079           --  separatel y for each  station.
  3080           @s ta3n varch ar(max) =  NULL,
  3081           --  @userid i s a charac ter parame ter which  can either  NULL, a s ingle user  identifie r,
  3082           --  or a comm a demlimit ed list of  user iden tifiers. A  user iden tifier is  a login,
  3083           --  including  the domai n. NULL im plies that  the data  for all us erss stati ons should
  3084           --  be return ed/used an d that no  stratifica tion by us er should  be done. A  userid
  3085           --  will retu rn data fo r only tha t user. A  comma deli mited list  of users  will
  3086           --  restrict  the return ed data to  those pre sent in th e list and  any aggre gation
  3087           --  or ordina tion will  be done se parately f or each us er.
  3088           @u serid varc har(max) =  NULL
  3089   AS
  3090   --======== ========== ========== ========== ========== ========== ========== ========== ====
  3091   --Requesto r              : Non  Va Coordin ated Care  Project
  3092   --Author                  : Bria n Diggs
  3093   --Object/S P Name         : App. NVCC_usp_U sageData2
  3094   --Server                  : 
  3095   --Data Bas e              : CC_R EFDOC
  3096   --Schema                  : app
  3097   --Report                  : N/A
  3098   --Folder                  : N/A
  3099   --Report L oc             : N/A
  3100   --Job                     : None
  3101   --Job Loc                 : None
  3102   --Note                    : 
  3103   --Date Cre ated           : 08-0 3-2016
  3104   --
  3105   --Last Cha nged           : 2017 -07-24
  3106   --Last Cha nged By                 : Brian  Diggs
  3107   --Reason F or Change               : Use NV CC_Product ionLog ins tead of vN VCC_Produc tionAccess Log
  3108   --
  3109   --Purpose                 : To g et aggrega ted, subse tted produ ction coun ts.
  3110   --======== ========== ========== ========== ========== ========== ========== ========== ====
  3111   --Uses: Ap p.udf_Spli tString
  3112   --Uses: Ap p.NVCC_Pro ductionLog
  3113   --Uses: Ap p.udf_Stat ionName
  3114   --Uses: CD WWork.LCus tomer.LCus tomer
  3115  
  3116   BEGIN
  3117           --  First, cr eate a tem porary tab le, #LogDa ta, which  pulls reco rds from
  3118           --  App.NVCC_ Production AccessLog.
  3119           --
  3120           --  The Acces sDateTime  and UserID  are kept  from the l og, and th e
  3121           --  PatientSI D is used  to determi ne the Sta 3n for tha t patient.
  3122           --
  3123           --  This list  is furthe r restrict ed to thos e stations  and users  specified
  3124           --  by the pa rameters.  This is ac complished  by conver ting the p arameter
  3125           --  string to  a table u sing App.u df_SplitSt ring. Only  the value  is kept
  3126           --  and, for  the statio n, convert ed to a sm allint to  match the  datatype
  3127           --  elsewhere . An input  of NULL w ill give a  single ro w table wi th value
  3128           --  NULL. The se convers ions are d one as com mon table  expression s.
  3129           --  These tab le are INN ER JOIN-ed  to the da ta, with t he clause  that
  3130           --  everythin g is kept  if the val ue is NULL .
  3131           --
  3132           --  UserID an d Sta3n ar e converte d to NULL  if their r espective  parameters
  3133           --  are NULL.  This indi cates that  there is  no stratif ication do ne (or
  3134           --  possible)  on those  variables.  The TimeG roup colum n contains  a date
  3135           --  which is  the start  of the int erval corr esponding  to the req uested
  3136           --  aggregati on level ( day, start  of week,  start of m onth, star t of
  3137           --  quarter,  start of y ear).
  3138           WI TH
  3139                    Sta3 n AS (SELE CT CONVERT (smallint,  Value) AS  Sta3n FRO M App.udf_ SplitStrin g(@sta3n,  ',')),
  3140                    User ID AS (SEL ECT Value  AS UserID  FROM App.u df_SplitSt ring(@user id, ','))
  3141                    SELE CT
  3142                             CASE
  3143                                      WHEN @us erid IS NU LL THEN NU LL
  3144                                      ELSE pl. UserID
  3145                             END AS  UserID,
  3146                             CASE
  3147                                      WHEN @st a3n IS NUL L THEN NUL L
  3148                                      ELSE pl. Sta3n
  3149                             END AS  Sta3n,
  3150                             CASE @ timegroup
  3151                                      WHEN 'da y' THEN
  3152                                               CONVERT(DA TE, pl.Acc essDateTim e)
  3153                                      WHEN 'we ek' THEN
  3154                                               CONVERT(DA TE, DATEAD D(DAY, 7 *  (DATEDIFF (DAY, '199 0-01-07',  pl.AccessD ateTime) /  7), '1990 -01-07'))
  3155                                      WHEN 'mo nth' THEN
  3156                                               DATEFROMPA RTS(DATEPA RT(YEAR, p l.AccessDa teTime), D ATEPART(MO NTH, pl.Ac cessDateTi me), 1)
  3157                                      WHEN 'qu arter' THE N
  3158                                               DATEFROMPA RTS(DATEPA RT(YEAR, p l.AccessDa teTime), ( ((DATEPART (MONTH, pl .AccessDat eTime) - 1 ) / 3) * 3 ) + 1, 1)
  3159                                      WHEN 'ye ar' THEN
  3160                                               DATEFROMPA RTS(DATEPA RT(YEAR, p l.AccessDa teTime), 1 , 1)
  3161                                      WHEN 'ev er' THEN
  3162                                               NULL
  3163                             END AS  TimeGroup
  3164                    INTO  #LogData
  3165                    FROM
  3166                             App.NV CC_Product ionLog pl
  3167                             INNER  JOIN Sta3n  st
  3168                                      ON (pl.S ta3n = st. Sta3n OR s t.Sta3n IS  NULL)
  3169                             INNER  JOIN UserI D uid
  3170                                      ON (pl.U serID = ui d.UserID O R uid.User ID IS NULL )
  3171  
  3172           --  A tempora ry table,  #LogAgg, i s created  based on t he structu re of #Log Agg plus o ne
  3173           --  other, NU LLable num eric colum n N. This  must be do ne in a se parate ste p
  3174           --  step (rat her than i mplicitly  with a SEL ECT ... IN TO) becaus e the same  named
  3175           --  temporary  table can  not be us ed as a ta rget for m ultiple SE LECT ... I NTO statem ents.
  3176           --  The WHERE  clause is  designed  to select  no rows, s o no data  is initial ly seeded
  3177           --  in the te mporary ta ble.
  3178           SE LECT
  3179                    ld.U serID,
  3180                    ld.S ta3n,
  3181                    ld.T imeGroup,
  3182                    CONV ERT(intege r, NULL) A S N
  3183           IN TO #LogAgg
  3184           FR OM #LogDat a AS ld
  3185           WH ERE 1=0;
  3186  
  3187           --  Choose th e code pat h based on  the value  of @stati stic.
  3188           IF  (@statist ic = 'coun t')
  3189                    BEGI N
  3190                             INSERT  INTO #Log Agg (Sta3n , UserID,  TimeGroup,  N)
  3191                             SELECT
  3192                                      Sta3n,
  3193                                      UserID,
  3194                                      TimeGrou p,
  3195                                      COUNT(*)  AS N
  3196                             FROM # LogData
  3197                             GROUP  BY Sta3n,  UserID, Ti meGroup
  3198                    END
  3199  
  3200           IF  (@statist ic = 'cumu lative')
  3201                    BEGI N
  3202                             INSERT  INTO #Log Agg (Sta3n , UserID,  TimeGroup,  N)
  3203                             SELECT
  3204                                      Sta3n,
  3205                                      UserID,
  3206                                      TimeGrou p,
  3207                                      SUM(N) O VER (PARTI TION BY St a3n, UserI D ORDER BY  TimeGroup ) AS N
  3208                             FROM (
  3209                                      SELECT
  3210                                               Sta3n,
  3211                                               UserID,
  3212                                               TimeGroup,
  3213                                               COUNT(*) A S N
  3214                                      FROM #Lo gData
  3215                                      GROUP BY  Sta3n, Us erID, Time Group
  3216                             ) A
  3217                    END
  3218  
  3219           --  This temp orary tabl e is no lo nger neede d.
  3220           DR OP TABLE # LogData;
  3221  
  3222           --  Further a nnotate th e #LogAgg  table by c onverting  the UserID
  3223           --  into the  Staff Name  and conve rting the  station nu mber into
  3224           --  a more us able versi on of the  station na me based o n the
  3225           --  App.udf_S tationName  function.
  3226           --
  3227           --  An additi onal ID co lumn is in cluded so  that Entit y Framewor k
  3228           --  has somet hing to us e as a pri mary key.  Ironically , there is
  3229           --  no column  in the ta ble which  is guarant eed to be  non-NULL
  3230           --  for all v alues of t he paramet ers. And a pparently,  having
  3231           --  ID as the  ORDER BY  inside the  OVER clau se definin g ID
  3232           --  isn't inv alid. I ha ve no idea  what it m eans, thou gh.
  3233           --  However,  since the  ID is not  semantical ly meaning ful (it
  3234           --  just has  to be uniq ue), it do esn't matt er.
  3235           --
  3236           --  Return th is further  annotated  table.
  3237           SE LECT
  3238                    ROW_ NUMBER() O VER (ORDER  BY la.Sta 3n) AS ID,
  3239                    la.U serID,
  3240                    la.S ta3n,
  3241                    la.T imeGroup,
  3242                    la.N ,
  3243                    lc.L astName +  ', ' + lc. FirstName  AS StaffNa me,
  3244                    App. udf_Statio nName(la.S ta3n) AS S tation
  3245           FR OM
  3246                    #Log Agg AS la
  3247                    LEFT  JOIN CDWW ork.LCusto mer.LCusto mer lc
  3248                             ON la. UserID = l c.ADDomain  + '\' + l c.ADLogin
  3249           OR DER BY Sta 3n, UserID , TimeGrou p
  3250   END
  3251   GO
  3252   PRINT N'Cr eating [Ap p].[NVCC_u sp_UserCou nts]...';
  3253  
  3254  
  3255   GO
  3256  
  3257   CREATE PRO CEDURE [Ap p].[NVCC_u sp_UserCou nts]
  3258  
  3259   -- NOTICE:
  3260   -- Do not  edit the s tored proc edure live  on the se rver. Code  to genera te
  3261   -- the pro cedures is  stored in  the proje ct reposit ory. Any c hanges mad e
  3262   -- that ar e not reco rded in th e reposito ry will be  overwritt en.
  3263  
  3264   AS
  3265   --======== ========== ========== ========== ========== ========== ========== ========== ====
  3266   --Requesto r              : Non  Va Coordin ated Care  Project
  3267   --Author                  : Bria n Diggs
  3268   --Object/S P Name         : NVCC _usp_UserC ounts
  3269   --Server                  : 
  3270   --Data Bas e              : CC_R EFDOC
  3271   --Schema                  : App
  3272   --Report                  : N/A
  3273   --Folder                  : N/A
  3274   --Report L oc             : N/A
  3275   --Job                     : None
  3276   --Job Loc                 : None
  3277   --Note                    : 
  3278   --Date Cre ated           : 08-0 2-2016
  3279   --
  3280   --Last Cha nged           : 2017 -07-24
  3281   --Last Cha nged By                 : Brian  Diggs
  3282   --Reason F or Change               : Conver t to use N VCC_UsersV 2 and NVCC _Productio nLog.
  3283   --                          Drop  LoggedUse rs.
  3284   --
  3285   --Purpose                 : Vari ous counts  of users
  3286   --======== ========== ========== ========== ========== ========== ========== ========== ====
  3287   --Uses: Ap p.NVCC_Use rsV2
  3288   --Uses: Ap p.NVCC_Pro ductionLog
  3289   --Uses: Ap p.NVCC_udf _ActiveUse rCount()
  3290  
  3291   SELECT
  3292           T. LookedUser s,
  3293           0  AS LoggedU sers, -- U sed to be  the number  of users  who had ge nerated a  logged ent ry, but ex pensive to  calculate  and not u seful beca use poorly  defined
  3294           R. RDPUsers,
  3295           A. ActiveUser s,
  3296           A. ActiveSite s
  3297   FROM
  3298           (
  3299                    SELE CT COUNT(* ) AS Looke dUsers
  3300                    FROM  App.NVCC_ UsersV2
  3301           )  AS T
  3302           CR OSS JOIN
  3303           (
  3304                    SELE CT COUNT(D ISTINCT Us erID) AS R DPUsers
  3305                    FROM  App.NVCC_ Production Log
  3306           )  AS R
  3307           CR OSS JOIN
  3308           (
  3309                    SELE CT
  3310                             SUM(Ac tiveUsers)  AS Active Users,
  3311                             COUNT( *) AS Acti veSites
  3312                    FROM  App.NVCC_ udf_Active UserCount( )
  3313           )  AS A
  3314   GO
  3315   PRINT N'Cr eating [Pa nelMgmt].[ usp_PMUpda teMasterLa bIndexFrom LOINC]...' ;
  3316  
  3317  
  3318   GO
  3319  
  3320  
  3321   CREATE PRO CEDURE [Pa nelMgmt].[ usp_PMUpda teMasterLa bIndexFrom LOINC] 
  3322   AS
  3323   --======== ========== ========== ========== ========== ========== ========== ========== ===
  3324   --Requesto r                                : Jianji Y ang
  3325   --Author                  : Jerr y Kohler ( Original s cript by S teve Schre iner)
  3326   --Object/S P Name                  : [Panel Mgmt].[usp _PMUpdateM asterLabIn dexfromLOI NC]
  3327   --SERVER                                    SERVER       
  3328   --Data Bas e                                : NWIC_Pan elMgmt
  3329   --Schema                                    : PanelMgm t
  3330   --Report                                    : None Yet
  3331   --Folder                                    :
  3332   --Report L oc             : 
  3333   --Job                     : None
  3334   --Job Loc                 : None
  3335   --Note                    : 
  3336   --Date Cre ated           : 12-2 8-2015
  3337   --Last Cha nged           :   
  3338   --Last Cha nged By                 : 
  3339   --Reason F or Change               :                                 
  3340   --Purpose                 : Upda te Panel M anagement  Master Lab  Index tab le 
  3341   --                          with  lab test  that have  valid LOIN C codes.   This is do ne
  3342   --                          thro ugh the BI SL's incre mental upd ate method  in the fi rst
  3343   --                          sect ion.  This  is done t o decrease  the proce ssing time
  3344   --                          and  conserve s erver reso urces.
  3345   --======== ========== ========== ========== ========== ========== ========== ========== ===
  3346   SET NOCOUN T on
  3347  
  3348   BEGIN
  3349       /* 
  3350       Locate  and load  the outsta nding Chem .LabChem b atches sin ce the
  3351       last e xecution r ather than  processin g the enti re Chem.La bChem view .
  3352       */
  3353  
  3354           -- declare ba tch variab les and cu rsor
  3355           DE CLARE @ETL BatchID    AS INT, @E xtractBatc hID AS INT ;
  3356           DE CLARE @DWV iewSchema  AS VARCHAR (50) = 'Ch em';
  3357           DE CLARE @DWV iewName    AS VARCHAR (50) = 'La bChem';
  3358  
  3359  
  3360       DECLAR E BatchCur sor CURSOR  STATIC FO R
  3361           -- get batch  ids
  3362               SELECT EX .ETLBatchI D, EX.Extr actBatchID
  3363               FROM SPV. EB.Extract Batch AS E X
  3364               INNER JOI N Dflt.Ext ractBatchL og AS EL
  3365                   ON EX .DWViewSch ema = EL.D WViewSchem a AND EX.D WViewName  = EL.DWVie wName
  3366               WHERE EX. DWViewSche ma = @DWVi ewSchema
  3367            A ND EX.DWVi ewName   =  @DWViewNa me
  3368            A ND EX.Extr actBatchID  > EL.Last ExtractBat chID
  3369               ORDER BY  EX.Extract BatchID;
  3370  
  3371           OP EN BatchCu rsor;
  3372           FE TCH NEXT F ROM BatchC ursor INTO  @ETLBatch ID, @Extra ctBatchID;
  3373  
  3374           WH ILE @@FETC H_STATUS =  0
  3375           BE GIN
  3376  
  3377           IF  (SELECT O BJECT_ID(' tempdb..#L abChemPrep ')) IS NOT  NULL
  3378           DR OP TABLE # LabChemPre p
  3379  
  3380                    -- t he lab res ults load  table has  duplicate  records, w hich the
  3381           --  MERGE sta tement wil l not tole rate.  Try  and get t he latest
  3382           --  record fo r each Lab ChemTestSI D in the b atch by so rting on
  3383           --  specimen  date time  descending  within th at LabChem TestSID
  3384                    SELE CT [Sta3n]
  3385                  ,[LabC hemTestSID ]
  3386                  ,[LOIN CSID]
  3387                  ,[LabC hemSpecime nDateTime]
  3388                  ,[LabC hemComplet eDateTime]
  3389                  ,[ETLB atchID]
  3390                  ,[OpCo de]
  3391                  ,[Vist aCreateDat e]
  3392                  ,[Vist aEditDate]
  3393                  ,row_n umber() ov er (Partit ion by Lab ChemTestSI D
  3394                                            or der by Lab ChemTestSI D, LabChem SpecimenDa teTime DES C) AS RN
  3395           IN TO #LabChe mPrep
  3396                    FROM  SPV.Chem. LabChem
  3397                    WHER E ETLBatch ID = @ETLB atchID             
  3398  
  3399                    -- m erge data  into produ ction(dest ination) t able
  3400                    MERG
  3401                             ETL.Pr odLabChem  AS D
  3402                    USIN G
  3403                             (
  3404                                      SELECT [ Sta3n]
  3405                           ,[LabChe mTestSID]
  3406                           ,[LOINCS ID]
  3407                           ,[LabChe mSpecimenD ateTime]
  3408                           ,[LabChe mCompleteD ateTime]
  3409                           ,[ETLBat chID]
  3410                           ,[OpCode ]
  3411                           ,[VistaC reateDate]
  3412                           ,[VistaE ditDate]
  3413                           ,RN
  3414                                      FROM #La bChemPrep
  3415                                      WHERE ET LBatchID =  @ETLBatch ID
  3416                      AN D RN = 1 - - the late st record  for a give n LabChemT estSID
  3417                             ) AS M
  3418                    ON
  3419                             D.LabC hemTestSID  = M.LabCh emTestSID
  3420                    WHEN  NOT MATCH ED THEN
  3421                             INSERT
  3422                                      (
  3423                                                  [Sta3n]
  3424                           ,[LabChe mTestSID]
  3425                           ,[LOINCS ID]
  3426                           ,[LabChe mSpecimenD ateTime]
  3427                           ,[LabChe mCompleteD ateTime]
  3428                           ,[ETLBat chID]
  3429                           ,[OpCode ]
  3430                           ,[VistaC reateDate]
  3431                           ,[VistaE ditDate]
  3432                                      )
  3433                             VALUES
  3434                                      (
  3435                          M.[Sta3n]
  3436                         ,M.[LabChe mTestSID]
  3437                         ,M.[LOINCS ID]
  3438                         ,M.[LabChe mSpecimenD ateTime]
  3439                         ,M.[LabChe mCompleteD ateTime]
  3440                         ,M.[ETLBat chID]
  3441                         ,M.[OpCode ]
  3442                         ,M.[VistaC reateDate]
  3443                         ,M.[VistaE ditDate]
  3444  
  3445                                      )
  3446                    WHEN  MATCHED T HEN
  3447                             UPDATE  SET
  3448                            [Sta3n]                     =  M.[Sta3n]
  3449                                                 ,[LabChe mTestSID]           =  M.[LabChe mTestSID]
  3450                           ,[LOINCS ID]                 =  M.[LOINCS ID]
  3451                           ,[LabChe mSpecimenD ateTime] =  M.[LabChe mSpecimenD ateTime]
  3452                           ,[LabChe mCompleteD ateTime] =  M.[LabChe mCompleteD ateTime]
  3453                           ,[ETLBat chID]               =  M.[ETLBat chID]
  3454                           ,[OpCode ]                   =  M.[OpCode ]
  3455                           ,[VistaC reateDate]          =  M.[VistaC reateDate]
  3456                           ,[VistaE ditDate]            =  M.[VistaE ditDate]
  3457                    ;
  3458  
  3459                    -- a fter mergi ng batch t hen update  the Extra ctBatchLog  table
  3460                    UPDA TE Dflt.Ex tractBatch Log
  3461                       S ET LastExt ractBatchI D = @Extra ctBatchID,  LastExtra ctDateTime  = GETDATE ()
  3462            W HERE DWVie wSchema =  @DWViewSch ema
  3463               AND DWVie wName   =  @DWViewNam e;
  3464  
  3465                    -- g rab the ne xt batch f or process ing
  3466                    FETC H NEXT FRO M BatchCur sor INTO @ ETLBatchID , @Extract BatchID;
  3467           EN D
  3468  
  3469           --  close and  deallocat e the curs or once al l batches  for a give n table ha ve been pr ocessed
  3470           CL OSE BatchC ursor;
  3471           DE ALLOCATE B atchCursor ;
  3472  
  3473   --
  3474   --
  3475   --
  3476   --  Using  the increm entally up dated ETL. ProdLabChe m rather t han the fu ll
  3477   --  CDWWor k.Dim.Labc hem view,  insert new  lab tests  into [Pan elMgmt].[P MMasterLab Index] 
  3478   --
  3479   --
  3480   --
  3481      -- all  LOINC SIDS  for all s tations de fined in P MMasterCoh ortSite
  3482      IF (SEL ECT OBJECT _ID('tempd b..#TempLO INCSID'))  IS NOT NUL L
  3483      DROP TA BLE #TempL OINCSID
  3484  
  3485      select  li.LOINCSI D
  3486              ,li.Sta3n
  3487              ,lc.LOINC
  3488              ,lc.TestGr oup
  3489              ,lc.Result ForTestNum eric
  3490              ,dateadd(y y,lc.YearS earchCrite ria,getdat e()) as Ye arSearchDa te
  3491      into #T empLOINCSI D
  3492      from [P anelMgmt]. [PMMasterC ohortLabTe stGroupsLO INCCodes]  as lc
  3493      inner j oin [CDWWo rk].[Dim]. [LOINC] as  li on lc. LOINC = li .LOINC
  3494      inner j oin [Panel Mgmt].[PMM asterCohor tSite] as  cs on li.S ta3n = cs. Sta3n;
  3495  
  3496  
  3497      -- base d on LOINC  codes, ar e there an y new lab  tests we d o NOT
  3498      -- alre ady have i n PMMaster LabIndex?
  3499      IF (SEL ECT OBJECT _ID('tempd b..#Insert TheseRecor ds')) IS N OT NULL
  3500      DROP TA BLE #Inser tTheseReco rds
  3501  
  3502      select  distinct l i.LabChemT estSID
  3503                                        ,li.St a3n
  3504                                        ,li.La bChemTestN ame
  3505                                        ,tl.Re sultForTes tNumeric
  3506                                        ,getda te() as Da teExtracte d
  3507                                        ,tl.Te stGroup
  3508                                        ,tl.LO INC
  3509                                        ,NULL  as WorkLoa dCode
  3510      into          #Ins ertTheseRe cords
  3511      from                   [ETL]. ProdLabChe m lc
  3512      inner j oin   [CDW Work].[Dim ].[LabChem Test] as l i on lc.La bChemTestS ID = li.La bChemTestS ID
  3513      inner j oin   #Tem pLOINCSID  tl on lc.S ta3n = li. Sta3n AND  lc.LabChem CompleteDa teTime > t l.YearSear chDate
  3514      where         lc.L OINCSID =  tl.LOINCSI D
  3515        and         not  exists (se lect ni.La bChemTestS ID
  3516                                                     from  [PanelMgm t].[PMMast erLabIndex ] as ni
  3517                                                             where l i.LabChemT estSID = n i.LabChemT estSID
  3518                                                                   a nd li.Sta3 n = ni.Sta 3n);
  3519  
  3520      Insert  into [Pane lMgmt].[PM MasterLabI ndex]
  3521      (
  3522         LabC hemTestSID ,
  3523         Sta3 n,
  3524         LabC hemTestNam e,
  3525         Resu ltForTestN umeric,
  3526         Date Extracted,
  3527         Test Group,
  3528         LOIN C,
  3529         Work LoadCode
  3530      )
  3531      Select  LabChemTes tSID,
  3532              Sta3n,
  3533              LabChemTes tName,
  3534              ResultForT estNumeric ,
  3535              DateExtrac ted,
  3536              TestGroup,
  3537              LOINC,
  3538              WorkLoadCo de
  3539       From # InsertThes eRecords
  3540      
  3541      Drop ta ble #Inser tTheseReco rds
  3542   --select t op 1000 *  from #Inse rtTheseRec ords
  3543   --select *  from #Ins ertTheseRe cords wher e LabChemT estSID in  (select La bChemTestS ID from [P anelMgmt]. [PMMasterL abIndex])
  3544   --select d istinct da teextracte d from #In sertTheseR ecords
  3545   --select c ount(*) fr om #Insert TheseRecor ds
  3546   --select a .*, b.* fr om #Insert TheseRecor ds a join  cdwwork.di m.labchemt est b on b .LabChemTe stSID = a. LabChemTes tSID
  3547   --select a .* from #I nsertThese Records a  join cdwwo rk.dim.lab chemtest b  on b.LabC hemTestSID  = a.LabCh emTestSID  where b.St a3n != a.S ta3n
  3548  
  3549      UPDATE  [PanelMgmt ].[PMMaste rCohortLab TestGroups LOINCCodes ]
  3550         set  LastUpdate  = cast(ge tdate() as  date);
  3551  
  3552   END
  3553   GO
  3554   PRINT N'Cr eating [Pa nelMgmt].[ usp_PMUpda teMasterLa bIndexFrom Workload]. ..';
  3555  
  3556  
  3557   GO
  3558   CREATE PRO CEDURE [Pa nelMgmt].[ usp_PMUpda teMasterLa bIndexFrom Workload] 
  3559  
  3560   -- NOTICE:
  3561   -- Do not  edit the s tored proc edure live  on the se rver. Code  to genera te
  3562   -- the pro cedures is  stored in  the proje ct reposit ory. Any c hanges mad e
  3563   -- that ar e not reco rded in th e reposito ry will be  overwritt en.
  3564  
  3565   AS
  3566   --======== ========== ========== ========== ========== ========== ========== ========== ========== ========== ========== =
  3567   --Requesto r                                : Jianji Y ang
  3568   --Author                  : Stev e Schreine r
  3569   --Object/S P Name                  : [Panel Mgmt].[usp _PMUpdateM asterLabIn dexFromWor kload]
  3570   --SERVER                                   
  3571   --Data Bas e                                : CC_REFDO C
  3572   --Schema                                    :    
  3573   --Report                                    : None Yet
  3574   --Folder                                    :
  3575   --Report L oc             : 
  3576   --Job                     : None
  3577   --Job Loc                 : None
  3578   --Note                    : 
  3579   --Date Cre ated           : 08-0 4-2014
  3580   --Last Cha nged           : 08-2 4-2017  
  3581   --Last Cha nged By                 : Brian  Diggs
  3582   --Reason F or Change               : Rebuil d as an in ner join r ather than  an assemb led string  which is  exec'd
  3583   --
  3584   --Last Cha nged           : 05-1 5-2015  
  3585   --Last Cha nged By                 : Jianji  Yang
  3586   --Reason F or Change               : exclud e NON-HDL  from 668 w hich is as signed to  LDL worklo ad code                                
  3587   --Purpose                 : Upda te Panel M anagement  Master Lab  Index tab le 
  3588   --                          with  lab test  with valid ate worklo ad codes.
  3589   --======== ========== ========== ========== ========== ========== ========== ========== ========== ========== ========== ===
  3590   BEGIN
  3591  
  3592           in sert                    [PanelMg mt].[PMMas terLabInde x]
  3593           se lect 
  3594                                               li.LabChem TestSID,
  3595                                               li.Sta3n,
  3596                                               li.LabChem TestName,
  3597                                               tg.ResultF orTestNume ric,
  3598                                               getdate()  as DateExt racted,
  3599                                               tg.TestGro up,
  3600                                               null as LO INC,
  3601                                               nc.Workloa dCode
  3602           fr om                      [CDWWork ].[dim].[L abChemTest ] as li
  3603           le ft outer j oin [CDWWo rk].[dim]. [NationalV ALabCode]  as nc on
  3604                                               li.Nationa lVALabCode SID = nc.N ationalVAL abCodeSID
  3605           in ner join                [PanelMg mt].[PMMas terCohortS ite] as cs  on
  3606                                               li.Sta3n =  cs.Sta3n
  3607           in ner join                (select  distinct
  3608                                                       Te stGroup,
  3609                                                       Re sultForTes tNumeric,
  3610                                                       Te stSearchCr iteria
  3611                                               from [Pane lMgmt].[PM MasterCoho rtLabTestG roups]) as  tg on
  3612                                               nc.Workloa dCode like  tg.TestSe archCriter ia
  3613           wh ere                     not exis ts (select  ni.LabChe mTestSID
  3614                                                                                  from [Pa nelMgmt].[ PMMasterLa bIndex] as  ni
  3615                                                                                  where li .LabChemTe stSID = ni .LabChemTe stSID
  3616                                                                                             and li.S ta3n = ni. Sta3n)
  3617           or der by                  li.Sta3n
  3618  
  3619           --  remove no n HDL lab  with LDL w orkload co de assigne d. working  with loca l CAC to r eassign ap propiate c ode 
  3620           --  LabChemTe stSID        LabChemT estIEN  St a3n   LabC hemTestNam e     LabC hemPrintTe stName         NLTNat ionalVALab CodeSID Na tionalVALa bCodeSID
  3621           --  800223162                    70 54    668    NON-HDL  CHOLESTERO L NHDL                      8005 22569                 800398429
  3622  
  3623           de lete FROM  [PanelMgmt ].[PMMaste rLabIndex]  where Lab ChemTestNa me like '% NON-HDL%'
  3624  
  3625   END
  3626   GO
  3627   PRINT N'Cr eating [Pa nelMgmt].[ usp_Rebuil dAllCDWPat ients]...' ;
  3628  
  3629  
  3630   GO
  3631  
  3632   CREATE PRO CEDURE [Pa nelMgmt].[ usp_Rebuil dAllCDWPat ients] 
  3633   AS
  3634   --======== ========== ========== ========== ========== ========== ========== ========== ====
  3635   --Requesto r              : Non  Va Coordin ated Care  Project, b ut produce s a great
  3636   --                          gene ral use al l patient  table for  any applic ation.
  3637   --Author                  : Jerr y Kohler,  Jianji Yan g - Northw est Innova tion Cente r
  3638   --Object/S P Name         : usp_ RebuildAll CDWPatient s
  3639   --Server                  :  SERVER       
  3640   --Data Bas e              : CC_R EFDOC
  3641   --Schema                  : Pane lMgmt
  3642   --Report                  : N/A
  3643   --Folder                  : N/A
  3644   --Report L oc             : N/A
  3645   --Job                     : None
  3646   --Job Loc                 : None
  3647   --Note                    : This  table con tains ALL  patients,  including
  3648   --                          dece ased and t est.
  3649   --Date Cre ated           : 03-1 0-2016
  3650   --
  3651   --
  3652   --Purpose                 : Beca use SPatie nt does no t have an  index on P atientSSN,
  3653   --                          we c reate a ta ble to tra nslate bet ween sever al types o f
  3654   --                          pati ent identi fication f or REFDOC:
  3655   --                             -  SSN
  3656   --                             -  SID
  3657   --                             -  ICN
  3658   --                             -  Name (las t,first)
  3659   --                             -  CPRSKey ( first char acter of l ast name,  last4)
  3660   --
  3661   --Last Cha nged           : 08-1 0-2017
  3662   --Last Cha nged By                 : Brian  Diggs - NW IC
  3663   --Reason F or Change               : Proces s was stil l blocking  for way t oo long, p reventing
  3664   --                          look ups of pat ients. Ref actored ba sed on dis cussions
  3665   --                          with  Andrew Ke lly. Extra ct the bat ches outsi de the
  3666   --                          (blo cking) MER GE, then f ilter them  while
  3667   --                          flag ging if th e record i s an updat e or inser t.
  3668   --                          Do t he updates  and then  inserts an d update t he ETLBatc hID
  3669   --
  3670   --Last Cha nged           : 07-1 4-2017
  3671   --Last Cha nged By                 : Brian  Diggs - NW IC
  3672   --Reason F or Change               : Implem ented sugg estions fr om Andrew  Kelly
  3673   --
  3674   --Last Cha nged           : 06-0 9-2017
  3675   --Last Cha nged By                 : Brian  Diggs - NW IC
  3676   --Reason F or Change               : Conver ted to inc remental u pdate foll owing reco mmended CD
  3677   --                          para digm
  3678   --
  3679   --Last Cha nged           : 04-1 9-2017
  3680   --Last Cha nged By                 : Brian  Diggs - NW IC
  3681   --Reason F or Change               : Stripp ed this do wn to just  the parts  needed fo r REFDOC
  3682   --                          as p art of the  migration  to the Fi eld Report ing Enclav e.
  3683   --                          The  only colum ns needed  are Sta3n,  PatientSS N, Patient ICN,
  3684   --                          Pati entSID, an d PatientI EN.
  3685   --
  3686   --Last Cha nged           : 06-0 6-2016
  3687   --Last Cha nged By                 : Jerry  Kohler - N WIC
  3688   --Reason F or Change               : Added  Next of Ki n, and per  Microsoft  recommend ation
  3689   --                          chan ged drop/c reate tabl e to drop  indexes an d TRUNCATE .
  3690   --                          Also  added WIT H (TABLOCK ) in the i nsert.
  3691   --                          All  of this sh ould boost  the perfo rmance, an d not
  3692   --                          elim inate stor ed executi on plans o n the tabl e.
  3693   --
  3694   --Last Cha nged           : 06-0 3-2016
  3695   --Last Cha nged By                 : Jerry  Kohler - N WIC
  3696   --Reason F or Change               : Take a ll patient s from SPa tient, tes t or decea sed.
  3697   --                          Join  to PanelM gmt.PMMast erCohortDe ceasedInde xNEW
  3698   --                          to e nsure bett er accurac y.  Add de ceased fla g and
  3699   --                          date  of death.
  3700  
  3701   --Last Cha nged           : 04-0 5-2016
  3702   --Last Cha nged By                 : Jianji  Yang - NW IC
  3703   --Reason F or Change               : Add te st patient  data, dec eased pati ents, and  patient's
  3704   --                        : home  station ( based on P CP's Sta3n ).
  3705   --
  3706   --Last Cha nged           : 03-1 7-2017
  3707   --Last Cha nged By                 : Jerry  Kohler - N WIC
  3708   --Reason F or Change               : Add Pa tientIEN s o that fun ction App. udf_AllPat ientsSIDs
  3709   --                        : can  now hit Al lCDWPatien ts instead  of SPatie nt.  This
  3710   --                        : tabl e is much  smaller, a nd will be  much fast er.
  3711   --
  3712   --Last Cha nged           : 03-2 0-2017
  3713   --Last Cha nged By                 : Jerry  Kohler - N WIC
  3714   --Reason F or Change               : Change  procedure  to place  data in a  temporary  table THEN
  3715   --                        : trun cate and i nsert into  the produ ction tabl e.  This
  3716   --                        : mini mize the a mount of t ime querie s would re turn no da ta.
  3717   --======== ========== ========== ========== ========== ========== ========== ========== ====
  3718  
  3719   BEGIN
  3720  
  3721           SE T NOCOUNT  ON;
  3722  
  3723           -- declare ba tch variab les and cu rsor
  3724           DE CLARE @ETL BatchID AS  INT, @Ext ractBatchI D AS INT;
  3725           DE CLARE @DWV iewName AS  VARCHAR(1 00) = 'SPa tient';
  3726  
  3727           -- add a TRY/ CATCH to e xit upon f ailure
  3728           BE GIN TRY
  3729  
  3730                    SET  @ExtractBa tchID = (S ELECT EL.L astExtract BatchID FR OM Dflt.Ex tractBatch Log AS EL  WHERE EL.D WViewName  = @DWViewN ame) ;
  3731  
  3732                    DECL ARE BatchC ursor CURS OR STATIC 
  3733                    FOR
  3734                    --ge t batch id s
  3735                    SELE CT EX.ETLB atchID, EX .ExtractBa tchID
  3736                    FROM  SPV.EB.Ex tractBatch  AS EX
  3737                    WHER E EX.DWVie wName = @D WViewName
  3738                             AND EX .ExtractBa tchID > @E xtractBatc hID
  3739                    ORDE R BY EX.Ex tractBatch ID;
  3740  
  3741                    CREA TE TABLE # spat1 (
  3742                             Sta3n  smallint,
  3743                             Patien tIEN varch ar(50),
  3744                             Patien tSSN varch ar(50),
  3745                             Patien tSID int,
  3746                             Patien tICN varch ar(50)
  3747                    )
  3748                    DECL ARE @LastE xtractBatc hID AS INT ;
  3749  
  3750                    OPEN  BatchCurs or;
  3751                    FETC H NEXT FRO M BatchCur sor INTO @ ETLBatchID , @Extract BatchID;
  3752  
  3753                    WHIL E @@FETCH_ STATUS = 0
  3754                    BEGI N
  3755                             INSERT  INTO #spa t1
  3756                             SELECT  Sta3n, Pa tientIEN,  PatientSSN , PatientS ID, Patien tICN
  3757                             FROM S PV.SPatien t.SPatient
  3758                             WHERE  ETLBatchID  = @ETLBat chID
  3759  
  3760                             -- Sto re to upda te trackin g table la ter
  3761                             SET @L astExtract BatchID =  @ExtractBa tchID
  3762  
  3763                             --merg e data fro m view int o producti on(destina tion) tabl e
  3764                             --grab  the next  batch for  processing
  3765                             FETCH  NEXT FROM  BatchCurso r INTO @ET LBatchID,  @ExtractBa tchID;
  3766                    END
  3767  
  3768                    --cl ose and de allocate t he cursor  once all b atches for  a given t able have  been proce ssed
  3769                    CLOS E BatchCur sor;
  3770                    DEAL LOCATE Bat chCursor;
  3771  
  3772                    SELE CT
  3773                             S.Sta3 n,
  3774                             S.Pati entIEN,
  3775                             S.Pati entSSN,
  3776                             S.Pati entSID,
  3777                             S.Pati entICN,
  3778                             CASE
  3779                                      WHEN A.P atientSID  IS NULL TH EN 'I'
  3780                                      ELSE 'U'
  3781                             END AS  InsertUpd ate
  3782                    INTO  #spat2
  3783                    FROM
  3784                             #spat1  AS S
  3785                             LEFT J OIN App.Al lCDWPatien ts AS A WI TH (NOLOCK )
  3786                                      ON S.Pat ientSID =  A.PatientS ID
  3787                             WHERE
  3788                                      A.Patien tSID IS NU LL 
  3789                                      OR (S.St a3n != A.S ta3n
  3790                                               OR S.Patie ntICN != A .PatientIC N
  3791                                               OR S.Patie ntSSN != A .PatientSS N
  3792                                               OR S.Patie ntIEN != A .PatientIE N)
  3793  
  3794                    CREA TE CLUSTER ED INDEX [ #tmpidx] O N #spat2 ( PatientSID  ASC) WITH  (DATA_COM PRESSION =  PAGE);
  3795  
  3796                    BEGI N TRANSACT ION
  3797                             UPDATE  A
  3798                             SET
  3799                                      A.Sta3n  = U.Sta3n,
  3800                                      A.Patien tIEN = U.P atientIEN,
  3801                                      A.Patien tSSN = U.P atientSSN,
  3802                                      A.Patien tICN = U.P atientICN
  3803                             FROM
  3804                                      App.AllC DWPatients  AS A
  3805                                      INNER JO IN #spat2  AS U
  3806                                               ON A.Patie ntSID = U. PatientSID
  3807                             WHERE
  3808                                      U.Insert Update = ' U'
  3809  
  3810                             INSERT  INTO App. AllCDWPati ents (Sta3 n, Patient IEN, Patie ntSSN, Pat ientSID, P atientICN)
  3811                             SELECT  Sta3n, Pa tientIEN,  PatientSSN , PatientS ID, Patien tICN
  3812                             FROM # spat2
  3813                             WHERE  InsertUpda te = 'I'
  3814  
  3815                             --afte r merging  batch then  update th e ExtractB atchLog ta ble
  3816                             UPDATE  Dflt.Extr actBatchLo g
  3817                                      SET Last ExtractBat chID = @La stExtractB atchID, La stExtractD ateTime =  GETDATE()
  3818                             WHERE  DWViewName  = @DWView Name;
  3819  
  3820                    COMM IT TRANSAC TION
  3821  
  3822           EN D TRY
  3823  
  3824           -- CATCH will  report ba ck specifi c details  about fail ure; the l oop will s top
  3825           BE GIN CATCH
  3826  
  3827                    IF @ @TRANCOUNT  > 0
  3828                             ROLLBA CK TRANSAC TION;
  3829  
  3830                    SELE CT
  3831                    ERRO R_NUMBER()  AS ErrorN umber,
  3832                    ERRO R_SEVERITY () AS Erro rSeverity,
  3833                    ERRO R_STATE()  AS ErrorSt ate,
  3834                    ERRO R_PROCEDUR E() AS Err orProcedur e,
  3835                    ERRO R_LINE() A S ErrorLin e,
  3836                    ERRO R_MESSAGE( ) AS Error Message;
  3837            
  3838           EN D CATCH 
  3839  
  3840   END
  3841   GO
  3842   PRINT N'Cr eating Per mission... ';
  3843  
  3844  
  3845   GO
  3846   GRANT DELE TE
  3847       ON SCH EMA::[App]  TO [uCC_R EFDOC_App] ;
  3848  
  3849  
  3850   GO
  3851   PRINT N'Cr eating Per mission... ';
  3852  
  3853  
  3854   GO
  3855   GRANT EXEC UTE
  3856       ON SCH EMA::[App]  TO [uCC_R EFDOC_App] ;
  3857  
  3858  
  3859   GO
  3860   PRINT N'Cr eating Per mission... ';
  3861  
  3862  
  3863   GO
  3864   GRANT INSE RT
  3865       ON SCH EMA::[App]  TO [uCC_R EFDOC_App] ;
  3866  
  3867  
  3868   GO
  3869   PRINT N'Cr eating Per mission... ';
  3870  
  3871  
  3872   GO
  3873   GRANT SELE CT
  3874       ON SCH EMA::[App]  TO [uCC_R EFDOC_App] ;
  3875  
  3876  
  3877   GO
  3878   PRINT N'Cr eating Per mission... ';
  3879  
  3880  
  3881   GO
  3882   GRANT UPDA TE
  3883       ON SCH EMA::[App]  TO [uCC_R EFDOC_App] ;
  3884  
  3885  
  3886   GO
  3887   PRINT N'Cr eating Per mission... ';
  3888  
  3889  
  3890   GO
  3891   DENY ALTER
  3892       ON SCH EMA::[dbo]  TO [uCC_R EFDOC] CAS CADE;
  3893  
  3894  
  3895   GO
  3896   /*
  3897   Post-Deplo yment Scri pt Templat e                                                     
  3898   ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ------
  3899    This file  contains  SQL statem ents that  will be ap pended to  the build  script.            
  3900    Use SQLCM D syntax t o include  a file in  the post-d eployment  script.                       
  3901    Example:       :r .\ myfile.sql                                                                
  3902    Use SQLCM D syntax t o referenc e a variab le in the  post-deplo yment scri pt.                
  3903    Example:       :setv ar TableNa me MyTable                                                              
  3904                   SELEC T * FROM [ $(TableNam e)]                                        
  3905   ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ------
  3906   */
  3907  
  3908   -- The CDW  envrionme nt require s that any  stored pr ocedure or  function  in the
  3909   -- App sch ema execut ed by the  App accoun t (CC_REFD OC_APP) an d referenc ing
  3910   -- anythin g in the C DWWork dat abase be s igned. If  only items  in the pr oject
  3911   -- databas e (any sch ema) are r eferenced,  it need n ot be sign ed.
  3912  
  3913   -- Comment ed out ite ms below u sed to req uire signi ng, but wi th refacto ring
  3914   -- they no  longer do . Left in  the file a nd comment ed to be a n affirmat ive
  3915   -- stateme nt that th ey do not  need to be  signed ra ther than  that they  were
  3916   -- overloo ked.
  3917  
  3918   exec dbo.s p_SignAppO bject 'NVC C_Rebuild_ SensitiveD xCodesTabl e'
  3919   exec dbo.s p_SignAppO bject 'NVC C_usp_Curr entUsage'
  3920   exec dbo.s p_SignAppO bject 'NVC C_usp_GetA llergies'
  3921   exec dbo.s p_SignAppO bject 'NVC C_usp_GetA nnouncemen t'
  3922   exec dbo.s p_SignAppO bject 'NVC C_usp_GetA ppts'
  3923   exec dbo.s p_SignAppO bject 'NVC C_usp_GetC onsults'
  3924   exec dbo.s p_SignAppO bject 'NVC C_usp_GetD ivision'
  3925   exec dbo.s p_SignAppO bject 'NVC C_usp_GetD ivisions'
  3926   exec dbo.s p_SignAppO bject 'NVC C_usp_GetL abs'
  3927   exec dbo.s p_SignAppO bject 'NVC C_usp_GetN extOfKin'
  3928   exec dbo.s p_SignAppO bject 'NVC C_usp_GetN VAMeds'
  3929   exec dbo.s p_SignAppO bject 'NVC C_usp_GetP atient'
  3930   exec dbo.s p_SignAppO bject 'NVC C_usp_GetP atientBySi d'
  3931   exec dbo.s p_SignAppO bject 'NVC C_usp_GetP robs'
  3932   exec dbo.s p_SignAppO bject 'NVC C_usp_GetS ensDx'
  3933   exec dbo.s p_SignAppO bject 'NVC C_usp_GetV AMeds'
  3934   exec dbo.s p_SignAppO bject 'NVC C_usp_GetX dwFacility '
  3935   exec dbo.s p_SignAppO bject 'NVC C_usp_GetX dwFacility BySta3n'
  3936   exec dbo.s p_SignAppO bject 'NVC C_usp_GetX dwUser'
  3937   --exec dbo .sp_SignAp pObject 'N VCC_usp_Pr oductionAc cessLogUni queSta3n'
  3938   exec dbo.s p_SignAppO bject 'NVC C_usp_Prod uctionAcce ssLogUniqu eUsers'
  3939   exec dbo.s p_SignAppO bject 'NVC C_usp_Uniq ueVeterans '
  3940   exec dbo.s p_SignAppO bject 'NVC C_usp_Usag eData2'
  3941   --exec dbo .sp_SignAp pObject 'N VCC_usp_Us erCounts'
  3942   --exec dbo .sp_SignAp pObject 'N VCC_udf_Ac tiveUserCo unt'
  3943   GO
  3944  
  3945   GO
  3946   PRINT N'Up date compl ete.';
  3947  
  3948  
  3949   GO