Okay here is another piece of query optimization for you guys. I have this stored procedure as you know which joins many tables. It's purpose is to be a search for an online application. So they go to the page and they have 2 fields for Age. They want all data between 0 and 10 days old. The table that joins for age has to be a left join because there are sometimes no records but we want to include all records from the base table. So I need to figure out the aged dates like Getdate() & Getdate() - 10. Then I have to say give me all the records that between 0 & 10. That works fine, but if you don't enter an Age you should get all records including those with a Null in the date column. So I have to set a range and then say, "OR IS NULL". Or I have to use a function in the where clause to replace the null - no!!, or I should be able to use a case statement. I am not sure what the best way is to handle this. If I use a case statement it runs in 8 seconds but it does not include the Nulls. If I use an "OR". It more than doubles the run time.
Please see my example.
Well you get the idea. Should I make another thread?
Please see my example.
Code:
Create Table DateTest1 (ID int, name varchar(10), datetest datetime ) Create Table DateTest2 ( ID int, Descripttion varchar(35) ) Insert into DateTest1 Values (1,'Joe',Getdate() -1) , (2,'Jim',NULL), (3,'Jake',Getdate() -7), (4,'John',NULL), (5,'Jan',Getdate() -10), (6,'Juno',Getdate() -5) Insert into DateTest2 Values (1,'Descr 1') , (2,'Descr 2'), (3,'Descr 3'), (4,'Descr 4'), (5,'Descr 5'), (6,'Descr 6') Select a.id, a.name, a.datetest, b.descripttion from DateTest2 b Inner Join DateTest1 a on a.id = b.id where a.datetest between GETDATE()- 11 and GETDATE() or a.datetest is null --Case statement does not include the Nulls --where a.datetest = case When a.datetest is null then a.datetest -- When a.datetest between GETDATE()- 11 and -- GETDATE() then a.datetest end --Or I can use something like this. --a.datetest >= GETDATE()- 11 and a.datetest <= GETDATE() or --a.datetest is null
Comment