ALTER TABLE on dependent column

前端 未结 3 1840
抹茶落季
抹茶落季 2021-02-01 01:03

I am trying to alter column datatype of a primary key to tinyint from int.This column is a foreign key in other tables.So,I get the following error:


相关标签:
3条回答
  • 2021-02-01 01:43

    If your constraint is on a user type, then don't forget to see if there is a Default Constraint, usually something like DF__TableName__ColumnName__6BAEFA67, if so then you will need to drop the Default Constraint, like this:

    ALTER TABLE TableName DROP CONSTRAINT [DF__TableName__ColumnName__6BAEFA67]
    

    For more info see the comments by the brilliant Aaron Bertrand on this answer.

    0 讨论(0)
  • 2021-02-01 01:44

    I believe that you will have to drop the foreign key constraints first. Then update all of the appropriate tables and remap them as they were.

    ALTER TABLE [dbo.Details_tbl] DROP CONSTRAINT [FK_Details_tbl_User_tbl];
    -- Perform more appropriate alters
    ALTER TABLE [dbo.Details_tbl] ADD FOREIGN KEY (FK_Details_tbl_User_tbl) 
        REFERENCES User_tbl(appId);
    -- Perform all appropriate alters to bring the key constraints back
    

    However, unless memory is a really big issue, I would keep the identity as an INT. Unless you are 100% positive that your keys will never grow past the TINYINT restraints. Just a word of caution :)

    0 讨论(0)
  • 2021-02-01 02:00

    you can drop the Constraint which is restricting you. If the column has access to other table. suppose a view is accessing the column which you are altering then it wont let you alter the column unless you drop the view. and after making changes you can recreate the view.

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