Drop Foreign Key without knowing the name of the constraint?

后端 未结 7 1176
遇见更好的自我
遇见更好的自我 2020-12-15 03:59

I have created one table using below command:

create table Table1(
    Id int Not Null 
        Foreign key 
        references Table2(Id)  
        on delet         


        
7条回答
  •  被撕碎了的回忆
    2020-12-15 04:24

    Never mind, below is Postgres syntax. It would be better if the question had sql server in the title as I didn't notice the tag

    You could also drop and re-add the primary key on the parent table using cascade. This will remove any foreign keys that reference that table without you needing to know the foreign key names.

    ALTER TABLE parent_table
    DROP CONSTRAINT 'pk_id' CASCADE
    
    -- add back pk
    ALTER TABLE parent_table
    ADD CONSTRAINT 'pk_id' PRIMARY KEY (id)
    

    WARNING: you'd want to check all the dependencies first and if there are other tables, you'd need to add back their foreign keys. That does allow you to name the foreign keys properly when you add them back. This approach also may not be viable in a high transaction system due to the blocking transaction.

提交回复
热议问题