title: Using Table-Valued Parameter's column in stored proc -
body: <p>I'm passing a TVP with 2 fields (a <code>datetime</code> and a <code>varchar(3)</code>) into a stored proc, and I'm trying to return all the table rows where the table's datetime column is either equal to one of the TVP datetimes or up to a couple of minutes earlier (I don't mind duplicates but would prefer without).</p>
  
  <p>This is what I've come up with - it's currently very slow (~5 seconds!) and I'm not sure what to do to improve it. Index the table? Which column? <code>AtTime</code>?</p>
  
  <p>I know it's a fiddly query as it needs to compute a range to look for before trying to match a row, so if there's an entirely different but preferable way to do this please let me know. Plus the input TVP has ~300 rows and the table itself has over 200k, so there's a lot of data to match and search.</p>
  
  <pre><code>CREATE PROCEDURE [dbo].[spGetPricesForDates]
      @tvp tvpType READONLY
  AS
  BEGIN
      SET NOCOUNT ON;
  
      SELECT S.AtTime, S.Underlying, S.Price
      FROM SourceTable S, @tvp T
      WHERE S.Underlying = T.Underlying   
      AND S.AtTime in (select AtTime
                      from SourceTable 
                      where AtTime 
                      between DATEADD(mi, -2, T.MyDate)
                      and T.MyDate)
  END
  </code></pre>
  
  <p><strong>edit</strong> I just realised my <code>in</code> query won't do what I want - I want to return the <em>latest
  matching table date/price row per tvp row within a 2 minute range</em>, whereas at the moment it'll give me everything that matches in that <code>between</code> set. I tried using <code>MAX(AtTime)</code> but that limits it to one possible match so I'm back to square 1.</p>