Click here to Skip to main content
15,923,006 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to use auto generate number for my ID field....I am already use [ID] [int] IDENTITY(1,1) NOT NULL, for auto generate..But when i try to delete some datas in table then that deleted id not used again........I need to use that deleted id again ...How can i do that?
Posted

I have used Stored Procedure For this : This method can be used to create a automatic id, and if id is deleted by user,then that id can be reused...

Create procedure [dbo].[Add_Articles]

@catid int,
@subid int,
@title varchar(200),
@desc varchar(max),
@tags varchar(50),
@dop date,
@userid varchar(100),
@active bit

as
begin

Declare @Id int

Select @id=ISNULL(Max(ArticleID),0) from ArticleTB

Set @Id = @Id +1


Insert into ArticleTB(ArticleID,CategoryID,SubcategoryID,Title,Description,Tags,DOP,UserID,IsActive)values(@Id,@catid,@subid,@title,@desc,@tags,@dop,@userid,@active)

select 1

end
 
Share this answer
 
Two Methods

1. DBCC CHECKIDENT (Transact-SQL)[^]
Refer - Reuse identity value after deleting rows[^].
Quote:
You can use the following to set the IDENTITY value:

SQL
DBCC CHECKIDENT (orders, RESEED, 999)


That means you'll have to run the statement based on every DELETE. That should start to highlight why this is a bad idea...

The database doesn't care about sequential values - that's for presentation only.

2. SET IDENTITY_INSERT[^].
Quote:

SQL
-- SET IDENTITY_INSERT to ON.
SET IDENTITY_INSERT products ON

-- Attempt to insert an explicit ID value of 3
INSERT INTO products (id, product) VALUES(3, 'garden shovel').

-- SET IDENTITY_INSERT to OFF again.
SET IDENTITY_INSERT products OFF

 
Share this answer
 
v3
Comments
_Amy 28-May-13 1:01am    
+5!
Thanks a lot @_Amy... :)

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900