title: Passing a date parameter to an in-line Table-Valued-Function is sloooww
body: <p>I'm having a strange scenario with the performance of a table valued function.  Basically, I have an inline table-valued-function that takes a DATETIME as a parameter.</p>
  
  <p>It sort of looks like this (not exactly this):</p>
  
  <pre><code>  CREATE FUNCTION fn_MyFunction(@StartDate DATETIME)
    RETURNS TABLE
    AS
    RETURN (
      SELECT COUNT(*), CustomerID, SUM(PAID)
      FROM Orders   
      WHERE OrderDate &gt; @StartDate
      GROUP BY CustomerID
    )
  </code></pre>
  
  <p>Now, I'm trying to investigate an issue where this query is running for >1 minute.  It turns out that if I call the query this way:</p>
  
  <pre><code>SELECT * FROM fn_MyFunction('7/1/2011')
  </code></pre>
  
  <p>It runs for > 1 minute.</p>
  
  <p>However, if I call the query this way:</p>
  
  <pre><code>DECLARE @startDate DATETIME = '7/1/2011'
  SELECT * FROM fn_MyFunction(@startDate)
  </code></pre>
  
  <p>It runs in under a second.  SQL Server is using entirely different explain plans for both calls.</p>
  
  <p>Obviously, I want it to do the second method all the time, unfortunately, I'm calling this Table Valued Function through LINQ 2 SQL, which won't declare an interim variable.</p>
  
  <p>Is there a way I can use an interim variable in the in-line table valued function?  I don't really want to convert this to a multi-line table valued function.  Other ideas would be welcome as well.  I'm a little stumped.</p>