title: SQL get first available date before 'xxxx-xx-xx'
body: <p>I need a query to get the first available date moving backwards excluding unavailable dates. <br/>
  <strong>Example:</strong><br/>
  Date must be before <code>2016-05-20</code>(this date is a variable). Best choice is <code>2016-05-19</code>(first day before). If this is not available, then get day earlier.<br/>
  Unavailable dates are saved in a table and can be selected like this<br/> <code>SELECT blockedDate FROM tbl_BlockedDates</code></p>
  
  <p>EDIT:<br/>
  I have seen that something like this would work but I can't figure out how to set it up correctly for my situation</p>
  
  <pre><code> SELECT TOP 1 [Date]
              FROM (
          SELECT TOP (DATEDIFF(DAY, @Date1, @Date2)+1)
          [Date] = dateadd(DAY, ROW_NUMBER() OVER(ORDER BY c1.name), @Date1)
          FROM  [master].[dbo].[spt_values] c1 
              ) D 
              WHERE D.Date NOT IN (SELECT ClosingDate FROM ClosingDays WHERE IsClosedAllDay = 1) 
              and Date not in (SELECT blockedDate FROM tbl_BlockedDates )
  </code></pre>
  
  <p>How can I get the date that I need?</p>