An explicit DROP INDEX is not allowed even when th

2019-08-05 02:17发布

问题:

Like the tittle suggests, I'm trying to drop a index, but it doesn't work, even when removing the constraint. The code used was the following:

OPEN cursor_drop_indexes 

FETCH next FROM cursor_drop_indexes INTO @Indexes_SchemaName, @Indexes_TableName, @Indexes_TableId, 
@Indexes_IndexName, @Indexes_IndexId, @Indexes_FileGroupName, @Indexes_FillFactor 

WHILE ( @@Fetch_Status = 0 ) 
  BEGIN 
      -- Used to remove UNIQUE KEY constraint enforcements
      IF @Indexes_IndexName NOT LIKE '%missing%' BEGIN
          SET @sql_index = ' ALTER TABLE [' + @Indexes_TableName + '] DROP CONSTRAINT [' 
                           + @Indexes_IndexName + ']'
          PRINT( @sql_index )
          EXEC sp_executesql @sql_index
      END
      -- Remove Index  
          SET @sql_index = ' DROP INDEX [' + @Indexes_IndexName + '] ON [' 
                           + @Indexes_SchemaName + '].[' + @Indexes_TableName + ']'

      PRINT( @sql_index )
      EXEC sp_executesql @sql_index

      FETCH next FROM cursor_drop_indexes INTO @Indexes_SchemaName, @Indexes_TableName, @Indexes_TableId
       , 
      @Indexes_IndexName, @Indexes_IndexId, @Indexes_FileGroupName, @Indexes_FillFactor 
  END 

CLOSE cursor_drop_indexes 

And the error messages are:

ALTER TABLE [TB_CARTAO_CREDITO] DROP CONSTRAINT [IX_TB_CARTAO_CREDITO_UNIQUE] DROP INDEX [IX_TB_CARTAO_CREDITO_UNIQUE] ON [dbo].[TB_CARTAO_CREDITO] Msg 3701, Level 11, State 7, Line 1 Cannot drop the index 'dbo.TB_CARTAO_CREDITO.IX_TB_CARTAO_CREDITO_UNIQUE', because it does not exist or you do not have permission.

Thanks and regards.

Edit:

So, these are the changes I made to the code after Hamlet Hakobyan helped me with the obvious

IF (SELECT is_unique FROM SYS.indexes WHERE name = @Indexes_IndexName ) = 1 BEGIN
    SET @sql_index = ' ALTER TABLE [' + @Indexes_TableName + '] DROP CONSTRAINT [' 
                 + @Indexes_IndexName + ']'
END
ELSE
-- Remove Index  
SET @sql_index = ' DROP INDEX [' + @Indexes_IndexName + '] ON [' 
                 + @Indexes_SchemaName + '].[' + @Indexes_TableName + ']'

PRINT( @sql_index )
EXEC sp_executesql @sql_index

回答1:

Error message is very clear. When you drop the constraint the corresponding objects(i.e. index) will be dropped also.