3

I wish to drop all the constraints of tables I have. Since this is not possible in SQL Server, I've created a script (based on something found online) that is creating dynamically the drop statements as a result of a Select:

SELECT 'ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + '] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']'
    FROM information_schema.table_constraints
    WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
    AND TABLE_NAME LIKE 'Old_%''

This done, I can't find how to parse it and execute that in a loop.

My attempt is to create a cursor like this, but I have no clue then to make it executing each line:

DECLARE @AlterTables nvarchar(2000)
SET @AlterTables = 'DECLARE Dyn_cursor CURSOR
FOR SELECT ''ALTER TABLE '' + TABLE_SCHEMA + ''.['' + TABLE_NAME + ''] DROP CONSTRAINT ['' + CONSTRAINT_NAME + '']''
FROM information_schema.table_constraints
WHERE CONSTRAINT_TYPE = ''FOREIGN KEY''
AND TABLE_NAME LIKE ''Old_%'''
Exec(@AlterTables)

Open Dyn_Cursor 
    FETCH NEXT FROM Dyn_Cursor INTO @name   
    WHILE @@FETCH_STATUS = 0   
BEGIN 
END

Close Dyn_cursor
Deallocate Dyn_cursor

Thank you in advance to whom would have a solution for that!

cheers

J.

2 Answers 2

2

Thank you jzd, however it wasn't working the way you recommended. I think it is required to declare the selection you are working on before opening the cursor. In order to do so, I've updated the code like this (that I've found on the web):

declare @str varchar(max)
declare cur cursor for
    SELECT 'ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + '] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']'
    FROM information_schema.table_constraints
    WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
    AND TABLE_NAME LIKE 'Old_%'
    open cur
        FETCH NEXT FROM cur INTO @str
        WHILE (@@fetch_status = 0)
            BEGIN
                EXEC (@str)
                FETCH NEXT FROM cur INTO @str
            END
    close cur
deallocate cur 
Sign up to request clarification or add additional context in comments.

Comments

0

You are close. Your cursor needs to not be dynamic and needs to just select the table constraints. Then you need to execute the update inside the loop, take your code here:

Open Dyn_Cursor 
    FETCH NEXT FROM Dyn_Cursor INTO @name   
    WHILE @@FETCH_STATUS = 0   
BEGIN 
--Add Here
END

And add in something like this between the Begin and End statements:

SET @AlterTable = 'ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + '] 
DROP CONSTRAINT ['' + @name + '']'
FROM information_schema.table_constraints
WHERE CONSTRAINT_TYPE = ''FOREIGN KEY''
AND TABLE_NAME LIKE ''Old_%'''
Exec(@AlterTable )
FETCH NEXT FROM Dyn_Cursor INTO @name

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.