Question

I am trying to add a primary key/auto increment to an existing table in Sql Server using Sql Server Management Studio. In MySql clients this is very easy, SSMS is being uncooperative; I can only add Nullable Fields and if I try to make a nullable field Primary it won't let me.

Était-ce utile?

La solution

You can add an identity column, which automatically assigns a value:

-- Create test table without primary key
CREATE TABLE dbo.Person
(
  Name varchar(30) null
)
INSERT INTO dbo.Person (Name)
    SELECT 'Abe One'
    UNION ALL 
    SELECT 'Bee Two'
GO  

-- Add new identity column
ALTER TABLE dbo.Person ADD
    ID int NOT NULL IDENTITY (1, 1)
GO

-- Make it the primary key
ALTER TABLE dbo.Person ADD CONSTRAINT
    PK_Person PRIMARY KEY CLUSTERED 
    (
    ID
    ) 
GO

Or you can use the Management Studio visual designer. Right click on the table name, then select 'Design' from the menu. For more details see: http://technet.microsoft.com/en-us/library/ms190634(v=sql.105).aspx

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top