views:

25

answers:

2

I'm trying to use a stored procedure to do an insert on a main table, then also insert that data into a historical data table. I don't want to use a trigger, but rather just do a simple insert of all columns into the history table. I am getting this error, however.

"An explicit value for the identity column in table 'ipaudittrail' can only be specified when a column list is used and the IDENTITY_INSERT is on."

I imagine this has to do with Scope_Identity()? but I'm not well-versed in SQL, so I'm not really sure the best way to resolve this. Any suggestions are appreciated. Thanks!

Insert Input
  (OpenedByName, Owner, Description, WorkOfDate)
Values 
  (@vOpenedByFirstName, @vOwner, @vDescription, @vWorkOfDate)

Set @vRecID = Scope_Identity()

Insert InputAuditTrail 
Select * 
  From Input 
 Where RecID = @vRecID

Select * 
  From Input     
 Where i.RecID = @vRecID
+4  A: 

Your audit trail table shouldn't have the identity property set on its RecID column as you don't want it to auto increment independently. You would need to alter the table definition to reflect that.

Having done that you could use the OUTPUT clause for this.

Insert Input(OpenedByName,Owner,Description,WorkOfDate)
OUTPUT inserted.* INTO InputAuditTrail /*Inserts to Audit Table*/
OUTPUT inserted.* /*Returns to Client*/
Values (@vOpenedByFirstName,@vOwner,@vDescription,@vWorkOfDate)
Martin Smith
+1: Leave some for me too, eh?
OMG Ponies
@OMG - That's me done for today!
Martin Smith
+1 I had no idea you can split the `OUTPUT` to go both return *and* `INTO`. Neat!
Remus Rusanu
Cool I learned something new.
HLGEM
Didn't know about Output. Thanks for sharing!
baldwingrand
+1  A: 
Insert InputAuditTrail Select * From Input Where RecID = @vRecID

This returning a a number of columns and one of them is attempting to write into InputAuditTrail's identity column.

Replace the statement with

Insert InputAuditTrail(col1, col2, ./...) Select cola, colb, .... From Input Where RecID = @vRecID
Preet Sangha