Link to home
Start Free TrialLog in
Avatar of bfuchs
bfuchsFlag for United States of America

asked on

Insert SQL statement help needed.

Hi Experts,

I am trying to recover a record accidentally deleted in a table, from a backup table (with the same structure).

when trying to  execute the below I am getting the following error.

 set IDENTITY_INSERT  patients on
 
insert into HomeCare.dbo.Patients
select * from backup_homecare.dbo.Patients 
where ID not in
(select id from HomeCare.dbo.Patients)

 set IDENTITY_INSERT  patients off

Open in new window

Msg 8101, Level 16, State 1, Line 5
An explicit value for the identity column in table 'HomeCare.dbo.Patients' can only be specified when a column list is used and IDENTITY_INSERT is ON.

What is the correct SQL or what am I missing here?
Avatar of Nathan Riley
Nathan Riley
Flag of United States of America image

select * 
into HomeCare.dbo.Patients
from backup_homecare.dbo.Patients 
where ID not in
(select id from HomeCare.dbo.Patients)

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of PortletPaul
PortletPaul
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bfuchs

ASKER

@Nathan,
I got the below when executing yours..
There is already an object named 'Patients' in the database.

@PortletPaul,
I missed that, however why is it like that, if both tables have the same structure shouldn't it be straight forward?
You could drop the existing table if there is no new data and just bring in the backup with my query above.  That will depend if this is dev or live environment.
Avatar of bfuchs

ASKER

Thanks PortletPaul!

@Nathan,
No, I am restoring a single record after a day of work, while that would cause all my new records to be deleted..
" if both tables have the same structure shouldn't it be straight forward?"
why doesn't it think like us? I don't know :)

It is always a good idea to be explicit I'm afraid - I know it will be frustrating particularly if there are lots of fields, but usually It's possible to get a list of fields pretty easy and with a bit of copy/paste etc. whip up an insert

seems that for this particular case, when overriding an auto-incrementing field, it just insists on know what you really absolutely and explicitly want.

cheers.