IF EXISTS (SELECT * FROM sysobjects WHERE xtype = 'U' AND name = 'AKG111') BEGIN DROP TABLE AKG111; PRINT 'Table, AKG111 is dropped'; END GO IF EXISTS (SELECT * FROM sysobjects WHERE xtype = 'U' AND name = 'AKG222') BEGIN DROP TABLE AKG222; PRINT 'Table, AKG222 is dropped'; END GO BEGIN CREATE TABLE AKG111 ( NAME NVARCHAR(100) NOT NULL , TYPE NVARCHAR(100) NOT NULL); PRINT 'Table, AKG111 is Created'; CREATE TABLE AKG222 ( NAME NVARCHAR(100) NOT NULL , TYPE NVARCHAR(100) NOT NULL); PRINT 'Table, AKG222 is Created'; ALTER TABLE AKG111 ADD CONSTRAINT AKG111_PK PRIMARY KEY (NAME, TYPE) WITH (FILLFACTOR = 80, PAD_INDEX = ON); PRINT 'Created PK, AKG111_PK on Table, AKG111'; ALTER TABLE AKG222 ADD CONSTRAINT AKG222_PK PRIMARY KEY (NAME, TYPE) WITH (FILLFACTOR = 80, PAD_INDEX = ON); PRINT 'Created PK, AKG222_PK on Table, AKG222'; END GO BEGIN DECLARE @parent_table VARCHAR(80), @cons_name VARCHAR(80); DECLARE drop_prmy_keys CURSOR FOR SELECT s2.name ,s1.name FROM sys.objects s1 ,sys.objects s2 WHERE s1.type = 'PK' AND s1.parent_object_id = s2.object_id AND s1.name NOT IN (SELECT NAME FROM AKG111 WHERE TYPE = 'constraint') AND s2.name IN ('AKG111','AKG222') ORDER BY s2.name; OPEN drop_prmy_keys; FETCH NEXT FROM drop_prmy_keys INTO @parent_table, @cons_name; WHILE(@@FETCH_STATUS=0) BEGIN PRINT 'Alter Table ' + @parent_table + ' To Drop Constraint ' + @cons_name; EXEC('ALTER TABLE ' + @parent_table + ' DROP CONSTRAINT ' + @cons_name); PRINT 'Constraint, '+ @cons_name + ' on Table ' + @parent_table + ' is Dropped.' ; FETCH NEXT FROM drop_prmy_keys INTO @parent_table, @cons_name; END CLOSE drop_prmy_keys; DEALLOCATE drop_prmy_keys; END GO
The above code fails with the error mentioned in the subject line. However if I comment the NOT IN condition in the cursor declaration it executes successfully.
It leads to the conclusion that a "table being altered in the cursor loop can not be used in the cursor declaration" or a "table used in the cursor declaration can not be altered in the cursor loop iteration".
However I could not find any microsoft mssql documentation stating this restriction.
Can anyone please explain this behavior and any pointer to any documentation which mentions about this restriction?