views:

24

answers:

1

Hi,

I have SQL 2005 databases.

I have deleted a row from one of them and want to get it back from another database that was a backup of the row.

How do isnert it while preserving its id primary key identity field?

Can you give TSQL to do this assume databases are called "tbrPdata" and "tbr0910" which is the backup?

Malcolm

+3  A: 

Use SET IDENTITY_INSERT:

SET IDENTITY_INSERT tbrPdata.dbo.TABLE ON
GO

 INSERT INTO tbrPdata.dbo.TABLE
   (col1, col2, col3,...)
 SELECT t.col1, t.col2, t.col3,...
   FROM tbr0910.dbo.TABLE t
  WHERE t.id = ?

SET IDENTITY_INSERT tbrPdata.dbo.TABLE OFF
GO
OMG Ponies
I get this error "An explicit value for the identity column in table 'tbrPdata.dbo.Employees' can only be specified when a column list is used and IDENTITY_INSERT is ON."
Malcolm
Add the list of fields between INSERT INTO and SELECT * in the format (COL1, Col2, Col3)...Also swap out the * with the actual field names.
JohnFx
@Malcolm: Updated - see JohnFx's comment for explanation, because you didn't provide the list of columns for the table.
OMG Ponies
ok because there are 100 or so fields I used Access query builder to drag all fields into a query and then copy the sql. Also you can't have timestamp columns in the column list.
Malcolm
@Malcolm: I use the Script To options in Management Studio, thx for the note about timestamp columns.
OMG Ponies