Try changing to an in-line table valued function.this code assumes a table called subscriptionTable with a primary key of subscriptionID--select statement:select st.[subscriptionid] ,sl.[SubscriptionLength]from SubscriptionTable stjoin tvf_SubscriptionLength() sl on sl.subscriptionid = st.subscriptionidwhere ...--function:gocreate function tvf_SubscriptionLength()returns tableas return (select SD.SubscriptionID ,case when convert(int, round(datediff(dd, SD.SubscriptionStartDate,SD.SubscriptionEndDate) /30.0,0)) < 12 then convert(int, round(datediff(dd, SD.SubscriptionStartDate,SD.SubscriptionEndDate) /30.0,0)) when convert(int, round(datediff(dd, SD.SubscriptionStartDate,SD.SubscriptionEndDate) /30.0,0)) < 24 then 12 when convert(int, round(datediff(dd, SD.SubscriptionStartDate,SD.SubscriptionEndDate) /30.0,0)) < 36 then 24 else 36 end as [SubscriptionLength]from SubscriptionTable SD)go
Be One with the OptimizerTG