How to execute dynamically created sql statement

I want to abandon all the table restrictions that I have. Since this is not possible in SQL Server, I created a script (based on something found on the network) that dynamically creates reset instructions as a result of the selection:

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 is done; I cannot find how to parse it and execute it in a loop.

My attempt is to create such a cursor, but I have no hint for it to execute 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 for having a solution for this!

amuses

J.

+3
source share
2 answers

jzd, , . , , , , . , ( ):

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 
+2

. . , :

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

- Begin End:

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
0

Source: https://habr.com/ru/post/1794072/


All Articles