Problem: You need to add an identity column to a SQL Server table that already contains data. Directly altering an existing column to become an identity is not supported.
Solutions: Two methods exist to achieve this:
Method 1: Create a New Table
This method preserves existing data. A new table is created with the identity column, data is copied, and the old table is replaced.
T-SQL:
CREATE TABLE dbo.Tmp_Names ( Id INT NOT NULL IDENTITY(1, 1), Name VARCHAR(50) NULL ) ON [PRIMARY] GO SET IDENTITY_INSERT dbo.Tmp_Names ON GO IF EXISTS (SELECT * FROM dbo.Names) INSERT INTO dbo.Tmp_Names (Id, Name) SELECT Id, Name FROM dbo.Names TABLOCKX GO SET IDENTITY_INSERT dbo.Tmp_Names OFF GO DROP TABLE dbo.Names GO EXEC sp_rename 'Tmp_Names', 'Names'
Method 2: Add a New Identity Column
This approach adds a new identity column, removes the old primary key, and renames the new column. Note: Existing data in the original primary key column will not be preserved.
T-SQL:
ALTER TABLE Names ADD Id_new INT IDENTITY(1, 1) GO ALTER TABLE Names DROP COLUMN ID GO EXEC sp_rename 'Names.Id_new', 'ID', 'COLUMN'
Important Considerations:
This information provides a more concise and streamlined explanation of the original text, while maintaining the core meaning and preserving the image.
The above is the detailed content of How Can I Add an Identity Column to an Existing SQL Server Table with Data?. For more information, please follow other related articles on the PHP Chinese website!