SELECT TOP #JobObjectsN#
 Objects_tbl.*,
 Ir.ObjectPuid AS IrPuid,
 Ir.ObjectName AS IrName
FROM
 dbo.Objects_tbl WITH (nolock)
 LEFT OUTER JOIN dbo.Objects_Ir_Rel_tbl WITH (nolock) ON (dbo.Objects_tbl.Id = dbo.Objects_Ir_Rel_tbl.ObjectId)
 LEFT OUTER JOIN dbo.Objects_tbl Ir WITH (nolock) ON (dbo.Objects_Ir_Rel_tbl.IrId = Ir.Id)
WHERE
 Objects_tbl.ObjectClass='DS'

 AND
 (
     -- see if Rf  ended with OK or or WRN
    (
      (Objects_tbl.ProcStateColRf like 'D.%OK' or Objects_tbl.ProcStateColRf like 'D.%WRN')
      AND (Objects_tbl.#JobRule.ProcStateCol# = 'N')
      AND (Objects_tbl.ObjectIrLatestRank<=-2)
    )
    Or
    -- or look for Data by setup by JobRoule
    (Objects_tbl.#JobRule.ProcStateCol# = '#JobRule.SelObjectsBy_ProcStateVal#')
 )

 AND Objects_tbl.ObjectOwningSiteID='#TcSiteId#'
--  AND Objects_tbl.ObjectUgMaster_Type = 'AP'
--  AND Objects_tbl.ObjectUgMaster_Type = 'SP'

ORDER BY
 Objects_tbl.ObjectUgMaster_APLevels DESC,
 Objects_tbl.ObjectUgMaster_CompCount DESC,
 Objects_tbl.ObjectIrLatestRank ASC
