• This should be straightforward - fetch the top row from the customer table (ordered by LastUpdated) and any row from MessageTypeTrack which matches the filter criteria. I think the optimiser is confused by one of those filter criteria:

    CONVERT(VARBINARY(8), cl.LocalLastUpdatedTS) < CONVERT(VARBINARY(8), c.DBTimeStamp)

    which could lead to an expensive triangular join.

    Bearing in mind that a query is a description of the result set, not a set of instructions to SQL Server as to how to accomplish the task, I think a better instruction for SQL Server would be something like this:

    SELECT

    c.ID,

    c.LastUpdated,

    c.DBTimeStamp,

    c.AccountNumber,

    oa.RecordID,

    oa.LocalLastUpdatedTS,

    c.PrimaryShipToID

    FROM (

    SELECT TOP 1

    ID,

    LastUpdated,

    DBTimeStamp,

    AccountNumber,

    PrimaryShipToID

    FROM dbo.Customer

    ORDER BY LastUpdated ASC

    ) c

    OUTER APPLY ( -- we don't care which - if any - row we get back

    SELECT TOP 1

    cl.RecordID,

    cl.LocalLastUpdatedTS

    FROM dbo.MessageTypeTrack cl

    WHERE CONVERT(NVARCHAR(20), cl.RecordID) = c.ID

    AND CONVERT(VARBINARY(8), cl.LocalLastUpdatedTS) < CONVERT(VARBINARY(8), c.DBTimeStamp)

    AND cl.MessageType = 'Customer'

    AND cl.MessageTypeVersion = '1.0'

    ) oa

    Note that there are currently no indexes on either table to properly support the query - whichever way you choose to write it.

    Give the query a try. It's not the only query which will work, there are a few options. Post up the actual execution plan of this query and your original as .sqlplan attachments (plans contain a ton of useful information). This will help folks figure out optimal index structure for you.


    [font="Arial"]Low-hanging fruit picker and defender of the moggies[/font]

    For better assistance in answering your questions, please read this[/url].


    Understanding and using APPLY, (I)[/url] and (II)[/url] Paul White[/url]

    Hidden RBAR: Triangular Joins[/url] / The "Numbers" or "Tally" Table: What it is and how it replaces a loop[/url] Jeff Moden[/url]