Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment (or reserve) IDENTITY value in SQL Server without inserting into table

Is there a way to reserve or skip or increment value of identity column?

I Have two tables joined in one-to-one relation ship. First one has IDENTITY PK column, and second one int PK (not IDENTITY). I used to insert in first, get ID and insert in second. And it works ok.

Now I need to insert values in second table without inserting into first.

Now, how to increment IDENTITY seed, so I can insert it into second table, but leave "hole" in ID's of first table?

EDIT: More info

This works:

-- I need new seed number, but not table row 
-- so i will insert foo row, get id, and delete it
INSERT INTO TABLE1 (SomeRequiredField) VALUES ('foo'); 
SET @NewID = SCOPE_IDENTITY(); 
DELETE FROM TABLE1 WHERE ID=@NewID;

-- Then I can insert in TABLE2  
INSERT INTO (ID, Field, Field) VALUES (@NewID, 'Value', 'Value'); 

Once again - this works.

Question is can I get ID without inserting into table?

DBCC needs owner rights; is there a clean user callable SQL to do that?

like image 259
dmajkic Avatar asked Jan 26 '09 16:01

dmajkic


People also ask

How do I reseed IDENTITY value in SQL Server?

Reset the Identity Value Using the DBCC CHECKIDENT Method : Here, to reset the Identity column in SQL Server you can use DBCC CHECKIDENT method. Syntax : DBCC CHECKIDENT ('table_name', RESEED, new_value); Note : If we reset the existing records in the table and insert new records, then it will show an error.

How can get auto increment value in SQL Server?

The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5) .

What is the difference between IDENTITY and auto increment in SQL?

The IDENTITY keyword causes the columns to be automatically incremental, meaning that each successive insert into the table will automatically assign a value greater than any previous row of the table. These columns are often referred to as "autoincrement columns".


1 Answers

This situation will make your overall data structure very hard to understand. If there is not a relationship between the values, then break the relationship.

There are ways to get around this to do what you are looking for, but typically it is in a distributed environment and not done because of what appears to be a data model change.

like image 157
Mitchel Sellers Avatar answered Sep 20 '22 01:09

Mitchel Sellers