How do I drop a foreign key in SQL Server?

前端 未结 8 1783
别那么骄傲
别那么骄傲 2020-12-04 10:53

I have created a foreign key (in SQL Server) by:

alter table company add CountryID varchar(3);
alter table company add constraint Company_CountryID_FK foreig         


        
相关标签:
8条回答
  • 2020-12-04 11:01

    I think this will helpful to you...

    DECLARE @ConstraintName nvarchar(200)
    SELECT 
        @ConstraintName = KCU.CONSTRAINT_NAME
    FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC 
    INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU
        ON KCU.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG  
        AND KCU.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA 
        AND KCU.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
    WHERE
        KCU.TABLE_NAME = 'TABLE_NAME' AND
        KCU.COLUMN_NAME = 'TABLE_COLUMN_NAME'
    IF @ConstraintName IS NOT NULL EXEC('alter table TABLE_NAME drop  CONSTRAINT ' + @ConstraintName)
    

    It will delete foreign Key Constraint based on specific table and column.

    0 讨论(0)
  • 2020-12-04 11:02

    I don't know MSSQL but would it not be:

    alter table company drop **constraint** Company_CountryID_FK;
    
    0 讨论(0)
  • 2020-12-04 11:07

    This will work:

    ALTER TABLE [dbo].[company] DROP CONSTRAINT [Company_CountryID_FK]
    
    0 讨论(0)
  • 2020-12-04 11:12

    First check of existence of the constraint then drop it.

    if exists (select 1 from sys.objects where name = 'Company_CountryID_FK' and type='F')
    begin
    alter table company drop constraint  Company_CountryID_FK
    end
    
    0 讨论(0)
  • 2020-12-04 11:15
    alter table company drop constraint Company_CountryID_FK
    
    0 讨论(0)
  • 2020-12-04 11:15

    Are you trying to drop the FK constraint or the column itself?

    To drop the constraint:

    alter table company drop constraint Company_CountryID_FK
    

    You won't be able to drop the column until you drop the constraint.

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