Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server : set primary key without dropping table and content [duplicate]

Tags:

sql

sql-server

Is it possible to set the primary key and auto increment on a SQL Server table without dropping and recreating the table, and losing all it's data?

like image 342
PeteTheGreek Avatar asked Apr 23 '26 06:04

PeteTheGreek


2 Answers

Yes of course! You just add a new column, and it an INT IDENTITY and add a primary key constraint to it:

 ALTER TABLE dbo.YourTable
 ADD ID INT IDENTITY(1,1) NOT NULL

 ALTER TABLE dbo.YourTable
 ADD CONSTRAINT PK_YourTable PRIMARY KEY (ID)
like image 93
marc_s Avatar answered Apr 24 '26 21:04

marc_s


If there is an existing primary key, you must first drop it:

IF EXISTS (SELECT * FROM sys.key_constraints
           WHERE type = 'PK' AND parent_object_id = OBJECT_ID('MyTable')
           AND Name = 'PK_MyTable')
    ALTER TABLE MyTable DROP CONSTRAINT PK_MyTable

If you are adding a column to be used as a primary key, then you can simply add it:

ALTER TABLE MyTable ADD MyKey INT IDENTITY

Then, you can set this column as your table's primary key:

ALTER TABLE MyTable ADD CONSTRAINT PK_MyTable PRIMARY KEY(MyKey)
like image 22
Paul Williams Avatar answered Apr 24 '26 20:04

Paul Williams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!