Error dropping index on SQL Azure database: Incorrect syntax near the keyword 'ON' (user context = dbo)

。_饼干妹妹 提交于 2019-12-11 16:48:34

问题


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:


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;


来源:https://stackoverflow.com/questions/46182973/error-dropping-index-on-sql-azure-database-incorrect-syntax-near-the-keyword-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!