Add values to key field

bfuchs
bfuchs used Ask the Experts™
on
Hi All,
Just wanted to confirm that is safe to do an append query into an existing table (restoring records mistakenly deleted from a backup database to its original place), and would prefer the ID should get their original value, the ID is defined as PK and has identity property set to yes, identity increment 1.
I know in access if I do that it would mess up the columns AutoNumber and its a kind of a hassle to get rid of all problems that come along, however wondering if SQL is handling it properly?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Yes you should be able to do that safely.
If scripting the query use the syntax
SET IDENTITY_INSERT yourtablename ON
prior to running the append sql and
SET IDENTITY_INSERT yourtablename OFF
after. This will allow you to insert into the identity fields and not affect your overall numbering.


Kelvin
Distinguished Expert 2017

Commented:
I know in access if I do that it would mess up the columns AutoNumber and its a kind of a hassle to get rid of all problems that come along, however wondering if SQL is handling it properly?
Not true.  

Access does allow you to do this and it may work against linked tables also.  I haven't had to restore records in SQL server tables recently.  I would try running the append query from the GUI to see what happens.  However, I do know that if you run the append query from VBA, you do have to follow Kelvin's directions and set the identity insert value before and after.
@kelvinsparks,
just wonder why do I need set to on/off, what happens if I leave this on all the time?

@PatHartman,
What I meant by access causing trouble is when this would be an access based table back end, not sure about the latest versions but the old versions I still use (2000/2003) definitely don't like when people interfere with their counters..In my experience they would take the last number appended as the next id to generate and would throw an error for users trying to add new record that "It would create duplicate value on Primary key or index..", Sometimes I can get this fixed by adding a higher number and compacting the database, but I had a case where none of this helped..
It worked, thank you!
You have to set on and off, as only one table at any one time can have this setting.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial