title: Add a column if it doesn't exist to all tables?
body: <p>I'm using SQL Server 2005/2008.  I need to add a column to a table if it does not yet exist. This will apply to all tables in a given database.  I hoped I was close, but I'm having issues with this solution.</p>
  
  <p>How can this be done?</p>
  
  <p>Here's what I have:</p>
  
  <pre><code>EXEC sp_MSforeachtable '
      declare @tblname varchar(255);
      SET @tblname =  PARSENAME("?",1);
  
      if not exists (select column_name from INFORMATION_SCHEMA.columns 
                     where table_name = @tblname and column_name = ''CreatedOn'') 
      begin
          ALTER TABLE @tblname ADD CreatedOn datetime NOT NULL DEFAULT getdate();
      end
  '
  </code></pre>
  
  <p>But I get errors:</p>
  
  <blockquote>
    <p>Error 102: Incorrect syntax near '@tblname'.
        Incorrect syntax near 'CreatedOn'.
        Incorrect syntax near '@tblname'.
        Incorrect syntax near 'CreatedOn'.
        ... and so on, for each table.</p>
  </blockquote>