title: Convert datetime to string/varchar in SQL Server
body: <p>I have a view in SQL Server which uses dates to determine which tables to access data from. The problem is it only seems to work when given the date as a <code>varchar</code> like <code>'20120423'</code>. </p>
  
  <p>So I am trying to dynamically create this date with <code>GETDATE()</code> instead of having to use the typed out version. When I run the top <code>SELECT</code> statement it returns <code>'20120423'</code> like I would expect but when I try to compare the two values they are not equal and the <code>IF</code> statement prints <code>'VALUES ARE NOT THE SAME'</code>.</p>
  
  <pre><code>SELECT 
      '''' +CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) +'''' 
  
  IF '''' +CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) +''''  = '20120423' 
  BEGIN
      PRINT 'VALUES ARE THE SAME'
  END
  ELSE
  BEGIN
     PRINT 'VALUES ARE NOT THE SAME'
  END
  </code></pre>
  
  <p>I'm kind of lost as to where to go from here. Thanks for any help.</p>
  
  <p><strong>EDIT</strong>:<br>
  With the answers given then these two queries should be the same even though they are treated differently by my view.</p>
  
  <pre><code>SELECT * 
  FROM DatesView 
  WHERE Timestamp &gt; CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112)
  
  SELECT * 
  FROM DatesView 
  WHERE Timestamp &gt; '20120423'
  </code></pre>
  
  <p>The top one looks through all tables where the bottom one correctly only searches the necessary tables.</p>