How to create nonclustered index with online if available

风格不统一 提交于 2020-12-08 07:03:29

问题


I'm adding a new index to a SQL Azure database as recommended by the query insights blade in the Azure portal, which uses the ONLINE=ON flag. The SQL looks something like this:

CREATE NONCLUSTERED INDEX [IX_MyIndex] ON 
       [Customers].[Activities] ([CustomerId]) 
   INCLUDE ([AccessBitmask], [ActivityCode], [DetailsJson], 
       [OrderId], [OperationGuid], [PropertiesJson], [TimeStamp]) 
   WITH (ONLINE = ON)"

However, we also need to add this same index to our local development databases, which are just localdb instances that don't support the ONLINE=ON option, resulting in the following error.

Online index operations can only be performed in Enterprise edition of SQL Server.

My question is - is there a way to write this SQL index creation statement that will use ONLINE=ON if available, but still succeed on databases that don't support it?


回答1:


You can use something like this:

DECLARE @Edition NVARCHAR(128);
DECLARE @SQL NVARCHAR(MAX);

SET @Edition = (SELECT SERVERPROPERTY ('Edition'));

SET @SQL = N'
CREATE NONCLUSTERED INDEX [IX_MyIndex] ON 
       [Customers].[Activities] ([CustomerId]) 
   INCLUDE ([AccessBitmask], [ActivityCode], [DetailsJson], 
       [OrderId], [OperationGuid], [PropertiesJson], [TimeStamp]) 
'

IF @Edition LIKE 'Enterprise Edition%' OR @Edition LIKE 'SQL Azure%' BEGIN
    SET  @SQL = @SQL + N' WITH (ONLINE = ON)';
END; 

EXEC sp_executesql @SQL;


来源:https://stackoverflow.com/questions/50407490/how-to-create-nonclustered-index-with-online-if-available

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