Error dropping index on SQL Azure database: Incorr

2019-08-21 10:30发布

I have a database in SQL Azure and I am wanting to use a script to drop all the column store indexes.

I am connecting using SSMS using the SQL admin login of the SQL Server.

I am using this script:

declare @sql nvarchar(max);
set @sql = N'';
select @sql = @sql + N'DROP INDEX ' + OBJECT_SCHEMA_NAME(i.OBJECT_ID) + '.' + i.name + N' ON ' + OBJECT_SCHEMA_NAME(i.OBJECT_ID) + '.' + o.name + ';
'
FROM sys.indexes AS i INNER JOIN sys.tables AS o ON i.[object_id] = o.[object_id]
where i.name is not null and o.name is not null and i.type_desc like '%COLUMN%'
PRINT @sql;
EXEC sp_executesql @sql;

An example statement:

DROP INDEX [dbo].[CCI_MyTable] ON [dbo].[MyTable];  

When run, this generates error:

Incorrect syntax near the keyword 'ON'.

If I try just:

 DROP INDEX [dbo].[CCI_MyTable]  

This generates error:

Cannot drop the index 'dbo.CCI_MyTable', because it does not exist or you do not have permission.**

In SSMS, I can see the SQL SERVER admin user exists in the [master] database, but does not exist in the DATABASE I am working in.

Within this DATABASE, I am running as 'dbo':

SELECT USER_NAME()      -- DBO  
SELECT CURRENT_USER;    -- DBO  

Shouldn't dbo have permissions to drop indexes?

ASK:
What is the proper way to go about this? Do I need to add the admin user to this database? If that user existed, and I connect with SSMS, would user_name() then be that user rather than dbo?

1条回答
Fickle 薄情
2楼-- · 2019-08-21 10:54

It seems the problem was preceding the index name with the schema (although, I swear many examples I've read do just that).

So the correct script syntax is:

declare @sql nvarchar(max);
set @sql = N'';
select @sql = @sql + N'DROP INDEX ' + i.name + N' ON ' + OBJECT_SCHEMA_NAME(i.OBJECT_ID) + '.' + o.name + ';
'
FROM sys.indexes AS i INNER JOIN sys.tables AS o ON i.[object_id] = o.[object_id]
where i.name is not null and o.name is not null and i.type_desc like '%COLUMN%'
PRINT @sql;
EXEC sp_executesql @sql;
查看更多
登录 后发表回答