If you wanted to try it just to see how performance is then your best bet might be a in inline, single statement, table valued UDF. This code makes an assumption that [WholeSaleCriteria] only has one row where isActive=1. also, use an explicit column list in the SELECT clause and make sure your column names are unique.obviously this is untested:create function UnqualifiedWholesalers()returns table asreturn select u.userid ,u.isactive as isActiveUser ,w.isactive as isActivewholesaler ,u.iswholesaler ,w.IsValidationRequiredfrom users u inner join Wholesalers w on u.userid = w.useridinner join WholesaleCriteria wc on wc.isActive = 1where w.isactive = 1 -- select active wholesaers onlyand u.isactive = 1 -- select active users onlyand u.iswholesaler = 1 -- select wholesalers onlyand w.IsValidationRequired = 1 -- temporary Wholesalers who must meet wholesalecriteriaand datediff(day,w.wholesalestartdate,getdate()) >= wc.duration -- difference od wholesalestartdate and today >= @durationand u.userid in ( -- select all customers who have purchased more than minamount between their wholesalestartdate and today select O.Customerid from orders o inner join orderdetails od on o.Orderid = od.Orderid inner join wholesalers w on w.userid = o.customerid inner join WholesaleCriteria wc on wc.isActive = 1 where o.DateCreated between w.wholesalestartdate and getdate() and datediff(day,w.wholesalestartdate,getdate()) >= wc.duration and w.ReminderSentOn >= DATEADD(DAY, 1 , GETDATE()) group by O.customerid having sum(od.subtotal) < max(wc.minAmount) --min/max doesn't matter - only one value )goselect * from UnqualifiedWholesalers() where isValidationRequired = 0
Be One with the OptimizerTG