views:

194

answers:

3

I have this query as a stored procedure:

SELECT     ID
    FROM         dbo.tblRentalUnit
    WHERE     (NOT EXISTS
        (SELECT     1 AS Expr1
        FROM          dbo.tblTenant
        WHERE      (dbo.tblRentalUnit.ID = UnitID)))

In Microsoft SQL Server Management Studio Express, it executes in 16 ms. When I have it in a typed dataset auto-generated by Visual Studio 2008, it executes in 64,453 ms. More than a minute.

Estimated and Execution plan are like this:

Select [0%] <- Filter [1%] <- Merge Join (Left Outer Join) [28%] <- Index Scan [16%]
                                                                 <- Sort [43%] <- Clustered Index Scan [12%]

Why is this difference here, and how can I correct it?

+2  A: 

It sounds like an incorrectly cached query plan.

Are your indexes and statistics up to date?

BTW, if tblTenant.UnitId is a Foriegn Key into tblRentalUnit.ID then your query can be rewritten as:

SELECT ru.ID    
FROM         
    dbo.tblRentalUnit ru
    LEFT JOIN dbo.tblTenant t ON ru.ID = t.UnitID
WHERE
    t.UnitID IS NULL
Mitch Wheat
How do I check and see if my indexes and statistics are up to date? According to the properties of the database, they're auto-updated
Malfist
Switching to this query and setting ARITHABORT ON; dropped the execution time down to 5859 ms in the application, but it still isn't the same as how it would execute in Management Studio
Malfist
In SSMS take a look at the Estimated and Actual Execution plans for differences (maybe post here)
Mitch Wheat
There is no difference between the two. I'll append it to my question though
Malfist
A: 

Did you flush the buffers before each test (from either client)? Make sure you are executing DBCC DROPCLEANBUFFERS and DBCC FREEPROCCACHE between each test.

Make sure it's not a production box! ;)
Mitch Wheat
I did that, it's not a production box either :)
Malfist
A: 

Is tblRentalUnit.ID properly indexed?

andrewbadera
yes it is. Everything is indexed, everything in this query acts only on indexes.
Malfist
"Everything" being indexed could be part of the problem. How did you tune your indexes?
andrewbadera