title: How can I store/retrieve a timestamp in SQL Server?
body: <p>I have a table where each row needs a timestamp marking the time it has been inserted. I don't have a lot of database experience, but something tells me that this would best be handled automatically on the database side, for example through a stored procedure.</p>
  
  <p>There is a timestamp datatype in MS SQL, but reading about it, it is treated as a series of numbers and not as a DateTime object in C#. So couldn't it just be a NVARCHAR datatype if I have to do the conversion anyway?</p>
  
  <p>So simply put, what is the easiest way to (automatically?) put a timestamp on a row when it is inserted into a table?</p>
  
  <p><strong>Edit:</strong> the table definition is very simple. It only has two columns at the moment and still lacking the timestamp column.</p>
  
  <pre><code>        SqlCommand command = con.CreateCommand();
          command.CommandText = "INSERT INTO Bio VALUES (" +
              "@ID, @Name)";
  
          command.Parameters.AddWithValue("ID",number);
          command.Parameters.AddWithValue("Name", name);
  
          try
          {
              SqlDataReader thisReader = command.ExecuteReader();
              thisReader.Close();
          }
          catch { // Do something };
  </code></pre>
  
  <p><strong>Solution</strong> Okay, it works now. I first tried adding the new column through the Server Explorer window in Visual Studio 2008. Finding my database, right click and selecting "New Query". Then typing something like</p>
  
  <pre><code>ALTER TABLE dbo.MyTable ADD CreatedDate datetime NOT NULL DEFAULT (GetUtcDate())
  </code></pre>
  
  <p>But I got the message that</p>
  
  <blockquote>
    <p>The ALTER TABLE SQL construct is not supported
    The query cannot be represented graphically in the Diagram and Criteria Pane.</p>
  </blockquote>
  
  <p>So instead I added it graphically. First "Open table definition" and adding CreatedDate under Column Name and datetime under Data Type. Removing the Allow Nulls check. Then in the Column Properties I added</p>
  
  <pre><code>getutcdate()
  </code></pre>
  
  <p>under the General section in the row called "Default Value or Binding". Whenever a new row is inserted, the database automatically gives it the current date and time as a timestamp.</p>