Drop Foreign Key without knowing the name of the constraint?

后端 未结 7 1164
遇见更好的自我
遇见更好的自我 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:31

    A SQL Server option:

    DECLARE @foreignkey varchar(100)
    DECLARE @tablename varchar(100)
    DECLARE @command nvarchar(1000)
    
    DECLARE db_cursor CURSOR FOR
    SELECT fk.name, t.name
    FROM sys.foreign_keys fk
    JOIN sys.tables t ON t.object_id = fk.parent_object_id
    WHERE t.name IN (
        'table_1_name_here',
        'table_2_name_here'
    )
    
    OPEN db_cursor
    FETCH NEXT FROM db_cursor INTO @foreignkey, @tablename
    WHILE @@FETCH_STATUS = 0
    BEGIN
        SELECT @command = 'ALTER TABLE ' + @tablename + ' DROP CONSTRAINT ' + @foreignkey
        EXECUTE(@command)
        FETCH NEXT FROM db_cursor INTO @foreignkey, @tablename
    END
    CLOSE db_cursor
    DEALLOCATE db_cursor
    

    The SQL selects all the constraints for the tables you care about into a cursor and drops them one by one. All you need to know are the names of the tables you want them dropped from.

提交回复
热议问题