开发者

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 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜