SELECT 
       OBJ_ADDRESS AS EVT_ADDRESS,
       OBJ_XCOORDINATE AS EVT_XCOORDINATE,
       OBJ_YCOORDINATE AS EVT_YCOORDINATE,
       OBJ_GISOBJID AS EVT_OBJECT_GISOBJID,
       EVT_CODE AS EVT_CODE,
       evt_desc  AS EVT_DESC,
       EVT_JOBTYPE AS EVT_JOBTYPE,
       ( 
           SELECT UCO_DESC
             FROM r5ucodes
            WHERE uco_rentity = 'JBTP' 
                  AND
                  UCO_CODE = EVT_JOBTYPE 
       ) 
       AS EVT_JOBTYPE_DESC,
       EVT_MRC AS EVT_MRC,
       EVT_OBJECT AS EVT_OBJECT,
       OBJ_DESC AS EVT_OBJECT_DESC,
       EVT_OBJECT_ORG AS EVT_OBJECT_ORG,
       evt_obtype AS EVT_OBTYPE,
       EVT_ORG AS EVT_ORG,
       EVT_PPM AS EVT_PPM,
       EVT_PPMREV AS EVT_PPMREV,
       EVT_PRIORITY AS EVT_PRIORITY,
       EVT_RSTATUS AS EVT_RSTATUS,
       EVT_SAFETY AS EVT_SAFETY,
       EVT_STATUS AS EVT_STATUS,
       ( 
           SELECT UCO_DESC
             FROM r5ucodes
            WHERE uco_rentity = 'EVST' 
                  AND
                  UCO_CODE = EVT_STATUS 
       ) 
       AS EVT_STATUS_DESC,
       EVT_WARRANTY AS EVT_WARRANTY,
       EVT_PERSON AS EVT_PERSON,
	   EVT_LATITUDE AS EVT_LATITUDE,
	   EVT_LONGITUDE AS EVT_LONGITUDE,
       PER_USER,
       EVT_START AS EVT_START,
       EVT_TARGET AS EVT_TARGET,
       EVT_CAMPAIGN_SURVEY AS EVT_CAMPAIGN_SURVEY,
       EVT_CAMPAIGN AS EVT_CAMPAIGN,
       EVT_CAMPAIGN_ORG AS EVT_CAMPAIGN_ORG
       FROM r5events e
LEFT OUTER JOIN r5objects ON OBJ_CODE = EVT_OBJECT AND OBJ_ORG = EVT_OBJECT_ORG
LEFT OUTER JOIN r5personnel ON PER_CODE=EVT_PERSON
WHERE evt_rstatus IN ( 'Q', 'R' ) 
       AND
       evt_rtype IN ( 'JOB', 'PPM' ) 
       AND
       EXISTS ( 
           SELECT 1
             FROM r5ucodes
            WHERE uco_rentity = 'JBTP' 
                  AND
                  uco_code = evt_jobtype 
                  AND
                  uco_rcode IN ( '*', 'BR', 'ST', 'PM', 'CAL', 'RP' )  
       ) 
       
       AND
        (  (<parameter.deptsec>  = 'OFF' ) 
           OR
           EXISTS ( 
               SELECT 1
                 FROM r5departmentsecurity
                WHERE dse_user = <parameter.r5user> 
                      AND
                      dse_mrc = evt_mrc 
           ) 
        )
ORDER BY CASE
   WHEN e.DMLTYPE='A' THEN EVT_CODE
   ELSE 1
   END DESC,
 <parameter.fieldname> <parameter.sortorder>
