• tomullus 69522 (7/29/2015)


    I think i was misunderstood. I made a mistake in the original post by copying the wrong query into it. The current post (after my edit) is the actual issue. My original intention was for the query inside the IF statement be identical to the first one.

    I'm well aware of the concerns when using NOLOCK and a WHERE instead of a JOIN, but it isn't the core of the issue. I'd like to know how is it that a query that runs reasonably fast takes forever when put inside a simple IF statement.

    Well your table has no indexing. Depending on the volume of data I would be surprised if anything ran acceptably fast.

    I would suggest completely reworking that query. The <> is nonSARGable but you can use a < which is SARGable. Also, using EXISTS instead of COUNT makes this a lot clearer what you are trying to do. See if something like doesn't help.

    if EXISTS

    (

    select *

    From table1 v

    inner join

    (

    select name

    , max(somedate) as correct_date

    From table1

    group by name

    ) z on v.name = z.name and correct_date < somedate

    )

    select 1

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/