How to drop all Foreign Key constraints in all tables?

后端 未结 7 1207
难免孤独
难免孤独 2020-12-08 10:03

I want to write sql command to drop all constraints in all tables. I searched on the internet and found the following which works fine if the database is small and not compl

7条回答
  •  时光说笑
    2020-12-08 10:40

    Most simple variant:

    DECLARE @sql nvarchar(MAX) 
    SET @sql = N'' 
    
    SELECT @sql = @sql + N'ALTER TABLE ' + QUOTENAME(KCU1.TABLE_SCHEMA) 
        + N'.' + QUOTENAME(KCU1.TABLE_NAME) 
        + N' DROP CONSTRAINT ' -- + QUOTENAME(rc.CONSTRAINT_SCHEMA)  + N'.'  -- not in MS-SQL
        + QUOTENAME(rc.CONSTRAINT_NAME) + N'; ' + CHAR(13) + CHAR(10) 
    FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC 
    
    INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU1 
        ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG  
        AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA 
        AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME 
    
    
    -- PRINT @sql 
    EXECUTE(@sql) 
    

提交回复
热议问题