-- SQL deletes the Foreign keys of all user data tables in the database
-- Query all constraints of the current database before deletion
Select * From information_schema.key_column_usage
Declare @ tablename nvarchar (250)
-- Declare that the cursor mycursor1 is used to read all data tables in the database
Declare mycursor1 cursor for select name from DBO. sysobjects where objectproperty (ID, 'isusertable') = 1
-- Open the cursor
Open mycursor1
-- Retrieve the data value from the cursor and assign it to the data table name variable we just declared.
Fetch next from mycursor1 into @ tablename
-- If the cursor is successfully executed
While (@ fetch_status = 0)
Begin
-- Defines the current foreign key constraint variable
Declare @ constraintname varchar (200)
-- Delete all foreign key constraints of the current data table
-- Declare to read all foreign key constraint names of the data table cursor mycursor2
Declare mycursor2 cursor for select name from DBO. sysobjects where xtype = 'F' and parent_obj = (select [ID] From DBO. sysobjects where id = object_id (n' ['+ @ tablename +'] ') and objectproperty (ID, n'isusertable') = 1)
-- Open the cursor
Open mycursor2
-- Values the data from the cursor to the foreign key constraint name variable
Fetch next from mycursor2 into @ constraintname
-- If the cursor is successfully executed
While (@ fetch_status = 0)
Begin
-- Delete the foreign key currently found
Exec ('alter table' + @ tablename + 'drop Constraint
'+ @ Constraintname)
-- Print 'alter table' + @ tablename + 'drop Constraint
'+ @ Constraintname
-- Use a cursor to retrieve the next record
Fetch next from mycursor2 into @ constraintname
End
-- Close the cursor
Close mycursor2
-- Undo cursor
Deallocate mycursor2
-- Use a cursor to retrieve the next record
Fetch next from mycursor1 into @ tablename
End
-- Close the cursor
Close mycursor1
-- Undo cursor
Deallocate mycursor1
-- Query all constraints of the deleted Database
Select * From information_schema.key_column_usage