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.
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.....)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With