How to reseed/replace identity columns on existing data - sql

Hey all I want to reseed my IDENTITY COLUMN values starting from 1 I know how to do this with DBCC CHECKIDENT, however, I would like to replace the value in all existing rows.. This table has a little over 2 million rows.
What is the best approach for this task?

You can simply add a new identity column, a la How to add a new identity column to a table in SQL Server?. Just delete the old column and re-add it. This will break any foreign keys, of course, but I assume since you are re-numbering everything I am guessing that's ok.

See this example how to replace values, but RESEED is something else:
CREATE TABLE t (id INT IDENTITY)
GO
INSERT t DEFAULT VALUES
GO 25
SET IDENTITY_INSERT t ON
delete t
OUTPUT DELETED.Id+100 INTO T(Id)
SET IDENTITY_INSERT t Off
SELECT * FROM t
DROP TABLE t
An example of reseed:
DBCC CHECKIDENT('YourTableName', 150, reseed)
AND
If you have to replace the value - with 2M rows it definitely have to take time

Related

Identity specification

I have a problem with identity specification when I create a table in SQL Server 2016.
In column Id I set Identity Increment and Identity Seed equal 1.
Next I add new record to new table.
In column Id show up 2 value. Why? Why not 1 value?
Next drop the first record and add new. In column Id show up 3 value. Why? Why not 1 value.
Next I use command ' update nametable set id=1' and receive answer cannot update identity column Id. Why?
This is probably easier to explain with some code:
CREATE TABLE YourTable (ID int IDENTITY(1,1),
SomeCol varchar(5));
INSERT INTO dbo.YourTable (SomeCol)
VALUES('abc'); --Will get ID 1
INSERT INTO dbo.YourTable (SomeCol)
VALUES('def'),('ghi'); --Will get 2 and 3.
SELECT *
FROM dbo.YourTable;
DELETE FROM dbo.YourTable;
INSERT INTO dbo.YourTable (SomeCol)
VALUES('abc'); --Will get ID 4, because 1-3 have been used. Deleting doesn't let you reuse values.
SELECT *
FROM dbo.YourTable;
DELETE FROM dbo.YourTable;
DBCC CHECKIDENT ('dbo.YourTable', RESEED, 1);
INSERT INTO dbo.YourTable (SomeCol)
VALUES('abc'); --Will get ID 2, as you seeded back to 1; so the NEXT ID is used.
SELECT *
FROM dbo.YourTable;
TRUNCATE TABLE dbo.YourTable;
INSERT INTO dbo.YourTable (SomeCol)
VALUES('abc'); --Will get ID 4, because 1-3 have been used.
SELECT *
FROM dbo.YourTable; --Will get ID 1, as the column was reseed with the TRUNCATE
DROP TABLE dbo.YourTable;
For your specific question on reseeding, the next value after the seed your define is use. The seed you define is the one you are saying was last used. This is covered in the documentation Forcing the current identity value to a new value:
Because the table has existing rows, the next row inserted will use 11
as the value – the new current identity value defined for the column
plus 1 (which is the column's increment value).
The only way to define a table doesn't have existing rows is the TRUNCATE it, which is what I do later on in the above batch (and why 1 is reused).
At the end of the day, the value of your IDENTITY is meaningless other than to provide the row with a single use value (which is not guarenteed to be unique on it's own). Combined with the Primary key/Unique constraints, it makes a good Clustered index candidate, as the next value is always greater than the last used, and values aren't reused.
If having sequential values is important, then what you need to use is a SEQUENCE, not the IDENTITY property. The latter doesn't guarantee uniqueness, or sequential values on it's own (as they could be skipped due to deletes, failed inserts, an unexpected shutdown, etc), but it does guarantee it will not reuse values once they have been (without a RESEED): IDENTITY (Transact-SQL) - Remarks. A SEQUENCE can be used to ensure the values are indeed sequential (apart from due to a DELETE).
Welcome to the forum :)
If you created the table using
Id INT IDENTITY(1,1)
Then the first record inserted will have Id = 1, however, if the insert statement fails or the transaction is rolled back the consumed identity be marked as used (or lost) and the next insert statement will proceed from Id = 2.
Have a look at Microsoft documentation on this topic:
https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property?view=sql-server-2017
When deleting inserted rows (which also happens when those inserts are rolled-back in a transaction, by the way), the identity value is not automatically reset. The identity functionality "remembers" its last value.
Gaps in the identity values will also NOT be filled when older records are deleted from the table and new records are inserted into the table.
That's just how identity works. It's a simple and safe mechanism.
If you (occasionally!) want to reset the identity value, you can take a look at DBCC CHECKIDENT. I personally tend to use it like this:
DBCC CHECKIDENT (MyTable, RESEED, 0) WITH NO_INFOMSGS;
DBCC CHECKIDENT (MyTable, RESEED) WITH NO_INFOMSGS;
(I execute both lines, in this order.)
I would advice against this practice in production environments, however.

how to Reset AutoIncrement in SQL Server after all data Deleted

i got a function in sql that generate sequential series of alphanumeric
no.like (c000,c0001 .......) , which is working good . but when i deleted all data in table , it starts from last generated no. i want it to reset its value from "c0000" .
code is as follows :-
create table Customers
(
dbID int identity not null primary key,
CustomerName varchar(100)
)
create function CustomerNumber (#id int)
returns char(5)
as
begin
return 'C' + right('0000' + convert(varchar(10), #id), 4)
end
alter table Customers add CustomerNumber as dbo.CustomerNumber(dbID)
thanks in advance....
EDIT 1 -
how to update it to increment based on last value . means if last entry having no. c0053 , and i deleted this record , so when next entry added it should have value "C0053" not "C0054".
thanks
Truncate Table Command is good way to reset Identity, but there is other command also to reset Identity after deletion of records.
DBCC CHECKIDENT (TableName, RESEED, 0)
After Deleting you can use this command to reset Identity to 0.
TRUNCATE TABLE
Removes all rows from a table or specified partitions of a table, without logging the individual row deletions. TRUNCATE TABLE is similar to the DELETE statement with no WHERE clause; however, TRUNCATE TABLE is faster and uses fewer system and transaction log resources.
TRUNCATE TABLE Customers
or remove your in build function.
My suggestion is instead of deleting all rows of data why dont you truncate the table.
If you are truncate the table it automatically reset your auto increment to 0
TRUNCATE TABLE your_table_name;
This example would truncate the table and remove all records from that table. and rest your auto increment too.
The SQL TRUNCATE TABLE command is used to delete complete data from an existing table
Try this way. May help you.

Updating Identity Column of a table with consecutive numbers through SQL Stored Procedure

After deleting the duplicate records from the table,
I want to update Identity column of a table with consecutive numbering starting with 1. Here is my table details
id(identity(1,1)),
EmployeeID(int),
Punch_Time(datetime),
Deviceid(int)
I need to perform this action through a stored procedure.
When i tried following statement in stored procedure
DECLARE #myVar int
SET #myVar = 0
set identity_insert TempTrans_Raw# ON
UPDATE TempTrans_Raw# SET #myvar = Id = #myVar + 1
set identity_insert TempTrans_Raw# off
gave error like...Cannot update identity column 'Id'
Anyone please suggest how to update Identity column of that table with consecutive numbering starting with 1.
--before running this make sure Foreign key constraints have been removed that reference the ID.
--insert everything into a temp table
SELECT (ColumnList) --except identity column
INTO #tmpYourTable
FROM yourTable
--clear your table
DELETE FROM yourTable
-- reseed identity
DBCC CHECKIDENT('table', RESEED, new reseed value)
--insert back all the values
INSERT INTO yourTable (ColumnList)
SELECT OtherCols FROM #tmpYourTable
--drop the temp table
DROP TABLE #tmpYourTable
GO
The IDENTITY keword is used to generate a key which can be used in combination with the PRIMARY KEY constraint to get a technical key. Such keys are technical, they are used to link table records. They should have no other meaning (such as a sort order). SQL Server does not guarantee the generated IDs to be consecutive. They do guarantee however that you get them in order. (So you might get 1, 2, 4, ..., but never 1, 4, 2, ...)
Here is the documentation for IDENTITY: https://msdn.microsoft.com/de-de/library/ms186775.aspx.
Personally I don't like it to be guaranteed that the generated IDs are in order. A technical ID is supposed to have no meaning other then offering a reference to a record. You can rely on the order, but if order is information you are interested in, you should store that information in my opinion (in form of a timestamp for example).
If you want to have a number telling you that a record is the fifth or sixteenth or whatever record in order, you can get always get that number on the fly using the ROW_NUMBER function. So there is no need to generate and store such consecutive value (which could also be quite troublesome when it comes to concurrent transactions on the table). Here is how to get that number:
select
row_number() over(order by id),
employeeid,
punch_time,
deviceid
from mytable;
Having said all this; it should never be necessary to change an ID. It is a sign for inappropriate table design, if you feel that need.
If you really need sequential numbers, may I suggest that you create a table ("OrderNumbers") with valid numbers, and then make you program pick one row from OrderNumbers when you add a row to yourTable.
If you everything in one transaction (i.e. with Begin Tran and Commit) then you can get one number for one row with no gabs.
You should have either Primary Keys or Unique Keys on both tables on this column to protect against duplicates.
HIH,
Henrik
Check this function: DBCC CHECKIDENT('table', RESEED, new reseed value)

Instead Insert Trigger

Can someone give me the skeleton body of an Instead of Insert Trigger for MSSQL. I am trying to test the largest value in an Purchase Order Column (which is an integer) and on insert it grabs the largest value increments that by one and inserts that as the Purchase Order ID. The column was not setup with an Auto Increment option so I am getting around that with a Trigger.
Thanks.
Here's how to change your table to include an identity column.
Create a new table with the same structure, but with an identity column on Purchase Order ID. You can use "script table as" and just change the line for Purchase Order Id, like:
[Purchase Order Id] int identity primary key,
Turn on identity insert on the new table:
SET IDENTITY INSERT NewTable ON
Copy over the data:
INSERT INTO NewTable (Columns) SELECT * FROM CurrentTable
Turn identity insert off:
SET IDENTITY INSERT NewTable OFF
Rename (or drop) the old table so it is no longer used:
EXEC sp_rename 'CurrentTable', 'BackupTable';
Move the new table in:
EXEC sp_rename 'NewTable', 'CurrentTable';
Now you have a nice identity column, which is much better than nasty triggers.
As described by Andomar, creating a new table to support your specifc requirements appropriately would be the ideal course of action in my view.
That said, should you however wish to go down the Instead of Insert Trigger route, then the following Microsoft reference provides a detailed example.
http://msdn.microsoft.com/en-us/library/ms175089.aspx

SQL-How to Insert Row Without Auto incrementing a ID Column?

I have a table that has a forced auto increment column and this column is a very valuable ID that is retained through out the entire app. Sorry to say it was poor development on my part to have this be the auto incrementing column.
So, here is the problem. I have to insert into this table an ID for the column that has already been created and removed from the table. Kind of like resurrecting this ID and putting it back into the table.
So how can I do this programatically do this without turning the column increment off. Correct me if I am wrong, if I turn it off programatically, It will restart at 0 or 1 and I don't want that to happen...
If you are in Microsoft SQL Server, you can "turn off" the autoIncrementing feature by issuing the statement Set Identity_Insert [TableName] On, as in:
Set Identity_Insert [TableName] On
-- --------------------------------------------
Insert TableName (pkCol, [OtherColumns])
Values(pkValue, [OtherValues])
-- ---- Don't forget to turn it back off ------
Set Identity_Insert [TableName] Off
In addition to Charles' answer (which is now 100% correct :-) and which preserves the current value of the IDENTITY on the table), you might also want to check the current value of an IDENTITY on a table - you can do this with this command here:
DBCC CHECKIDENT('YourTableName')
If you ever need to actually change it, you can do so by using this command here:
DBCC CHECKIDENT ('YourTableName', RESEED, (new value for IDENTITY) )
Actually, the code above for INDENTITY_INSERT is correct - turning it ON tells the server you want to insert the values yourself. It allows you to insert values into an IDENTITY column. You then want to turn it back off (allowing the server to generate and insert the values) when you are done.
bulk insert tablename from 'C:\test.csv' with (rowterminator = '\n',fieldterminator = ',',KEEPIDENTITY)