views:

1421

answers:

3

I am attempting to insert a copy of a row from one table into another table with the same schema, with the addition of one column (a timestamp) to provide a "history" of the first table in MS Sql Server 2005.

So, my query, without the additional column would be:

"SELECT INTO [WebsiteHistory] FROM [Website]"

I want to populate the timestamp column as well, but am not sure how to best do this. I'd like to do something like:

"SELECT Website.*, '" + DateTime.Now.ToShortDateString() + "' INTO [WebsiteHistory] FROM [Website]"

But that shouldn't work, especially if the timestamp column is not the last one. Is there any way to do this?

+12  A: 

Be warned. This works, but it is neither nice nor recommendable:

INSERT
  WebsiteHistory
SELECT
  *,
  GETDATE()
FROM
  Website
WHERE
  Id = @WebsiteId

This assumes WebsiteHistory has the same structure as Website (you said it has), plus there is one additional DATETIME field.

Better is this, because it is much more fail-safe (at the expense of being more verbose):

INSERT
  WebsiteHistory
  (
  Id,
  Field1,
  Field2,
  Field3,
  Field4,
  ModifiedDate
  )
SELECT
  Id,
  Field1,
  Field2,
  Field3,
  Field4,
  GETDATE()
FROM
  Website
WHERE
  Id = @WebsiteId
Tomalak
Since when is being verbose bad?
Dining Philanderer
Hm... Did I say it was?
Tomalak
Wouldn't it be better to create a timestamp column with a default constraint on it to automatically populate it when a row is added to the table?
Si Keep
That would be another way to do it, maybe even more elegant. But I would have needed to go into more detail to explain something that would not have made the solution *more correct* than it is right now.
Tomalak
While the auto-populated timestamp column would certainly work, I was as interested in the best way to address this general scenario (needing to copy all the columns but with some arbitrary additions) as I was with this specific case (needing a timestamp column).
sgibbons
Please stop referring to it as a timestamp column, in SQL Server a timestamp column does not store dates and times. It is a datetime column you need. Yes a constraint would be the best way to ensure the data alawys got populated in this case.
HLGEM
A: 

Look at the accepted answer for this question: Dynamically look up column names for a table while in an sql query

It fetches the names of all the fields in the table to create a query customized to that table. You should be able to simply adapt the exact same technique to generate the right fields names here.

Oddthinking
+1  A: 

Can't you set a default constraint on the column that would automatically populate the timestamp column when a row is inserted to the table?

Si Keep