Insert data in to sql server data table

大憨熊 提交于 2020-01-17 03:48:10

问题


I have one table called customer_master that includes a column called cust_id with autoincrement set to 1.

When we try to insert records its working fine and inserted records like cust_id 1, 2, 3 and 4 are inserted, but when an error is generated in the insert command we do a transaction rollback, this means that cust_id 5 is not inserted, but when we are insert another record, cust_id generates 6. It skips cust_id 5.

I want to set it up so that if any error is generated in the insert command the identity is not incremented.

We are using c# and sql server 2005.


回答1:


The reason SQL Server does this is for efficiency. If you need a sequence number without gaps you shouldn't be using identity you would need to implement your own scheme where concurrent transactions are blocked waiting for the next value just in case the initial transaction rolls back.

The second query here could be used for that purpose. But do you really need this? If it is purely for aesthetic purposes my advice is not to worry about it!




回答2:


You can use DBCC CHECKIDENT to reseed the identity column after an insert failure.

DBCC CHECKIDENT ( table_name, NORESEED ) returns the current identity value and the current maximum value of the identity column.

DBCC CHECKIDENT ( table_name, RESEED, new_reseed_value ) sets the current identity value to the new_reseed_value.



来源:https://stackoverflow.com/questions/3845450/insert-data-in-to-sql-server-data-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!