Change Column to PK

  • Hi all I am trying to change a column that is a int to a PK

    this is what I have tried but it never sets it as a PK

    command.CommandText = "ALTER TABLE EngineersTB ADD CONSTRAINT EmpNumber PRIMARY KEY (id)";

    I am creating a patch for a app I have

    Jay

  • Yes, that is how you create a primary key.

    Check what error it's failing with if it doesn't set the PK (my guess, the column is nullable)

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass
  • In case, you want to create a new primary key, you should check existing PK and drop it then create a new.

    IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[tablename]') AND name = N'[PrimaryKey name]')

    ALTER TABLE [tablename] DROP CONSTRAINT [PrimaryKey name]

    GO

  • Yes, that is how you create a primary key.

    Check what error it's failing with if it doesn't set the PK (my guess, the column is nullable)

    Spot on mate thank you

    Jay

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply