Table1 has columns
Id int, Date smalldatetime.
View1 has, among many other columns, column Id int.
View1 has a maximum of 2000 rows, but there are some rather complex computation to determine the values of all the columns.
What is the most efficient way to return all Table1.Id that are not in View1.Id for Table1.Date between '2012-05-30' and '2012-05-31' ?
The filtered selection from Table1 typically returns about 200 unique Table1.Id.
When I do a SELECT * FROM View1, the total data is returned always in under one second. When I do a SELECT Id from Table1 WHERE Date BETWEEN ‘2012-05-30’ AND ‘2012-05-31’, the result is always instanteous.
The moment I tried SELECT Table1.Id from Table1 T1 WHERE Date BETWEEN .. AND .. AND NOT EXISTS (SELECT Id from View1 WHERE ViewId=T1.Id), it takes ages (almost 20s).
I tried using a CTE also, WITH V1 as (SELECT Id from View1) SELECT T1.Id FROM Table1 T1 WHERE Date BETWEEN … and … AND NOT EXISTS (SELECT Id from V1 WHERE V1.Id=T1.Id), and it also took ages.
Thanks.
Try something like this:
The HASH hint forces the SQL Server query optimizer to evaluate the view only once.
Another way would be to use a table variable to store the result of the view:
Razvan