Click here to Skip to main content
15,884,629 members
Articles / Programming Languages / SQL
Tip/Trick

Auto Increment Column Value is Not Part of Transaction

Rate me:
Please Sign up or sign in to vote.
4.20/5 (3 votes)
25 Jun 2018CPOL 7.7K   4   2
Auto increment column value is not part of transaction

Introduction

Most of us think when we make some changes and rollback the transaction, everything is rolled back, but here's the catch - transaction does not roll back the auto increment field.

This concept will help you to solve some of your problems and will also help you to extract the required information in some cases like how many records were part of a particular transaction.

Using the Code

Here, I created a table Test with a primary key column and another auto increment column.

SQL
CREATE TABLE [dbo].[test](
    [id] [int] NOT NULL,
    [sno] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_test] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, _
       ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Test 1

SQL
begin transaction
insert into test(id)
values(1)
rollback transaction

GO

Expected Result

Since we have rolled back the transaction, so expectation is that auto increment column is also rolled back.
Well, here is the difference.

Test 2

SQL
insert into test(id)
values(1)
insert into test(id)
values(2)

GO

Expected Result

Since we have rolled back the transaction, the expectation is that auto increment column is also rolled back. Well, here is the difference - auto increment value is set to 1 after the transaction even it is rolled back.

select * from test
id   sno
1    2
2    3

Points of Interest

Hope this will help you while solving problems where transaction is involved and your point of interest is the identity column value after the transaction whether it is commit or rollback.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader STPL
India India
I am having 11+ years of experience in architecture, development of enterprise scale application developed in Microsoft .Net technology stack with SQL server.
Having good domain knowledge of Business Accounting, Social Networking and Point of Sale domains.

Comments and Discussions

 
QuestionWhy should an auto-numbered field be transactional? Pin
Wendelius25-Jun-18 10:10
mentorWendelius25-Jun-18 10:10 
AnswerRe: Why should an auto-numbered field be transactional? Pin
connect ashish yadav25-Jun-18 18:12
professionalconnect ashish yadav25-Jun-18 18:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.