简体   繁体   中英

SQL manual update Incremental number while Insert

Manually generate a number counter in SQL Server.

I have a table with quotes. The columns are ID which is primary key and identity, Title Nvarchar , Des Nvarchar , UpdateNumber .

I want to add a number like an index which should increase by 1 whenever new record is inserted.

I cannot use identity in SQL for the same as it leaves gaps in between.

I have used the following code in stored procedure whenever new record is inserted.

INSERT INTO [mps] ([Title], [Des], UpdateNumber) 
VALUES(@title, @des, (select (max(id) + 1) from mps))

My concern is that there shouldn't be any duplicate, what if two people insert the records at the very same time. How will SQL handles this? Or is there any other better method of doing this?

I'm using a similar numbering in another project where I want an incremental number whenever new record is inserted. There cannot be gaps in these as I'm printing the same as document number for collating and gaps might create confusion after printing. So should the below method work in that solution

You can use Count function

INSERT INTO [mps] ([Title],[Des],UpdateNumber) VALUES(@title,@des,(select (count(*)+1) from mps))

or you can use Max

INSERT INTO [mps] ([Title],[Des],UpdateNumber) VALUES(@title,@des,(select (max(isnull(UpdateNumber, 0))+1) from mps))

with these there will be no duplicates

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