Hello everyone,
I am using SQL Server 2008. One int column I used as primary key but not identity column (whose value will be increased by 1 automatically). I want to convert this column to identity column. Any solutions?
thanks in advance, George
Hello everyone,
I am using SQL Server 2008. One int column I used as primary key but not identity column (whose value will be increased by 1 automatically). I want to convert this column to identity column. Any solutions?
thanks in advance, George
Go to your table object in object explorer in sql server right click on a table say modify, than click on a field which is primary key that you want to convert to identity, than below you'll see column properties , there you need to change as (Is Identity) Yes and Idendity Increment 1.
Unfortunately, you cannot change a field to IDENTITY
on an existing table.
You should:
IDENTITY
fieldSET IDENTITY_INSERT ON
for the new tableSET IDENTITY_INSERT OFF
for the new tableYou can use SSMS
to change the field type, it will do all this for you behind the scenes.
Here's a sample table:
CREATE TABLE plain (id INT NOT NULL PRIMARY KEY)
INSERT
INTO plain
VALUES (1000)
and the script generated by SSMS
:
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_plain
(
id int NOT NULL IDENTITY (1, 1)
) ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_plain SET (LOCK_ESCALATION = TABLE)
GO
SET IDENTITY_INSERT dbo.Tmp_plain ON
GO
IF EXISTS(SELECT * FROM dbo.plain)
EXEC('INSERT INTO dbo.Tmp_plain (id)
SELECT id FROM dbo.plain WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT dbo.Tmp_plain OFF
GO
DROP TABLE dbo.plain
GO
EXECUTE sp_rename N'dbo.Tmp_plain', N'plain', 'OBJECT'
GO
ALTER TABLE dbo.plain ADD CONSTRAINT
PK__plain__3213E83F1A609306 PRIMARY KEY CLUSTERED
(
id
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
COMMIT