Reputation: 3641
i recently imported some old data to a new SQL table and forgot to set the ID column to auto increment.
Now i have several "NULL"s in the column named ID.
Is there a way I can update all ID columns with an unique ID automatically? sadly i have no clue how
After that I will be able to set the column to INT and Auto Increment.
Thank you for your help.
Upvotes: 7
Views: 26377
Reputation: 1396
Without using of sequences and manual setting of starting value:
declare @MaxId int
select @MaxId = max(id) from [TableA]
update [TableA]
set @MaxId = id = @MaxId +1
where id is null
Works fine with all versions of SQL Server starting from 2008. Sqlfiddle
Upvotes: 2
Reputation: 5989
If the current ID column is not important and the value assigned to the ID column is not relevant you could try the following:
A sample script could look like this:
// Create a new identity column
ALTER TABLE dbo.YourTable
ADD NewID INT IDENTITY(1,1);
GO
// Drop the old ID column
ALTER TABLE dbo.YourTable
DROP COLUMN OldID;
GO
// Rename the new column from 'NewID' to 'OldID'
EXEC sp_rename 'YourDataBase.YourTable.NewID', 'OldID', 'COLUMN';
GO
This will not work when you have tables that have a relationship based on the values in the old ID column.
Upvotes: 1
Reputation:
You can do it using a CTE (common table expression):
;WITH cte AS
(
SELECT ROW_NUMBER() OVER (ORDER BY ColA) AS RN,
ID,
ColA
FROM dbo.YourTable
)
UPDATE cte
SET ID = RN
in this example the new id gets generated by ordering by ColA
- but you can order by any column(s) you want.
Upvotes: 2
Reputation: 2379
Try using Sequence Object for Sql Server 2012
create Sequence Sq as int
minvalue 1
cycle;
update table set Column=NEXT VALUE FOR Sq where Column is null
Upvotes: 11
Reputation: 461
The easiest way is to remove your old ID Column and add a new column ID with :
ALTER TABLE [dbo].[myTable] DROP COLUMN ID
ALTER TABLE [dbo].[myTable] ADD ID int IDENTITY
Upvotes: 5