Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add primary key column in SQL table

Tags:

I am student of RDBMS.

I have very basic question let say I have one existing Table in SQL server. What will be script to alter table.

  • Drop Column 'RowId' if exist.
  • Drop contraint if exist.
  • Add one new column 'RowId' into table.
  • Make this column as primary key.
  • Autoincrement type int.
like image 362
SOF User Avatar asked Feb 06 '12 10:02

SOF User


1 Answers

In SQL Server 2005 or newer, you could use this script:

-- drop PK constraint if it exists IF EXISTS (SELECT * FROM sys.key_constraints WHERE type = 'PK' AND parent_object_id = OBJECT_ID('dbo.YourTable') AND Name = 'PK_YourTable')    ALTER TABLE dbo.YourTable    DROP CONSTRAINT PK_YourTable GO  -- drop column if it already exists IF EXISTS (SELECT * FROM sys.columns WHERE Name = 'RowId' AND object_id = OBJECT_ID('dbo.YourTable'))     ALTER TABLE dbo.YourTable DROP COLUMN RowId GO  -- add new "RowId" column, make it IDENTITY (= auto-incrementing) ALTER TABLE dbo.YourTable  ADD RowId INT IDENTITY(1,1) GO  -- add new primary key constraint on new column    ALTER TABLE dbo.YourTable  ADD CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED (RowId) GO 

Of course, this script may still fail, if other tables are referencing this dbo.YourTable using foreign key constraints onto the pre-existing RowId column...

Update: and of course, anywhere I use dbo.YourTable or PK_YourTable, you have to replace those placeholder with the actual table / constraint names from your own database (you didn't mention what they were, in your question.....)

like image 58
marc_s Avatar answered Sep 28 '22 05:09

marc_s