Adding column with primary key in existing table

后端 未结 5 1935
感动是毒
感动是毒 2021-02-02 12:29

I am trying to add primary key to newly added column in existing table name Product_Details.

New Column added: Product_Detail_ID (int

相关标签:
5条回答
  • 2021-02-02 12:57

    If you want SQL Server to automatically provide values for the new column, make it an identity.

    ALTER TABLE Product_Details DROP COLUMN Product_Detail_ID
    GO
    ALTER TABLE Product_Details ADD Product_Detail_ID int identity(1,1) not null
    GO
    ALTER TABLE Product_Details
    add CONSTRAINT pk_Product_Detils_Product_Detail_ID primary key(Product_Detail_ID)
    GO
    
    0 讨论(0)
  • 2021-02-02 12:58
    ALTER TABLE Jaya 
      ADD CONSTRAINT no primary key(No);
    

    here Jaya is table name,

    no is column name,

    ADD CONSTRAINT is we giving the primary key keyword

    0 讨论(0)
  • 2021-02-02 13:05

    k. friend command: sql> alter table tablename add primary key(col_name);

    ex: alter table pk_Product_Detils add primary key(Product_Detail_ID);

    0 讨论(0)
  • 2021-02-02 13:08

    You are getting the error because you have existing data that does not fullfill the constraint.

    There are 2 ways to fix it:

    • clean up the existing data before adding the constraint
    • add the constraint with the "WITH NOCHECK" option, this will stop sql server checking existing data, only new data will be checked
    0 讨论(0)
  • 2021-02-02 13:10

    In mysql, I was able to achieve with following query

    ALTER TABLE table_name ADD new_column int NOT NULL AUTO_INCREMENT primary key

    0 讨论(0)
提交回复
热议问题