• prady_1988 (10/5/2012)


    Its a pretty big query but here it is:

    <<snip>>

    The FROM list and WHERE clause of both of the queries is identical:

    FROM BMC_CORE_BMC_BaseElement BASE1 (NOLOCK)

    LEFT JOIN BMC_CORE_BMC_BaseRelationship RELA (NOLOCK)

    ON BASE1.InstanceId = RELA.Source_InstanceId

    LEFT JOIN BMC_CORE_BMC_BaseElement BASE2 (NOLOCK)

    ON RELA.Destination_InstanceId = BASE2.InstanceId

    AND Base2.DatasetId='BMC.ASSET'

    LEFT JOIN AST_CMDB_Associations AST (NOLOCK)

    ON AST.request_id02 = BASE1.ReconciliationIdentity

    and AST.Request_ID02 != '0' and AST.Request_ID01 != '0'

    and AST.form_name01 <> 'TMS:TASK' and AST.form_name01 <> 'WOI:WorkOrder'

    WHERE BASE1.AssetID = 'abcd'

    FROM BMC_CORE_BMC_BaseElement BASE1 (NOLOCK)

    LEFT JOIN BMC_CORE_BMC_BaseRelationship RELA (NOLOCK)

    ON BASE1.InstanceId = RELA.Source_InstanceId

    LEFT JOIN BMC_CORE_BMC_BaseElement BASE2 (NOLOCK)

    ON RELA.Destination_InstanceId = BASE2.InstanceId

    AND Base2.DatasetId='BMC.ASSET'

    LEFT JOIN AST_CMDB_Associations AST (NOLOCK)

    ON AST.request_id02 = BASE1.ReconciliationIdentity

    and AST.Request_ID02 != '0' and AST.Request_ID01 != '0'

    and AST.form_name01 <> 'TMS:TASK' and AST.form_name01 <> 'WOI:WorkOrder'

    WHERE BASE1.AssetID = 'abcd'

    - and deduplication in each is performed by the DISTINCT, which operates on the output list. If you can fathom out how to more predictably deduplicate the result sets using GROUP BY, then you would get away with one query.

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden