简体   繁体   中英

SQL Error on Audit Trail Insert after Scope_Identity()

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

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)
Insert InputAuditTrail Select * From Input Where RecID = @vRecID

This returning aa 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM