2016-01-23 36 views
1

作爲系統升級的一部分,我們需要能夠更新數據庫結構以符合最新版本。使用從屬索引更改表

我正在爲此寫一個工具,但我堅持正確的過程來更新索引中使用的列。

如果列是在索引中必須改變,這方法很可能是最有問題的:

1)禁用索引,變更列,重新啓用索引

2 )刪除索引,更改列,重新創建索引

有許多實例必須應用此更改,並且我希望儘可能減少總體時間,因此我偏好不選擇如果可以避免,重新創建索引。

+0

你會在更新聚集鍵以及。當你說改變你是隻改變數據類型column.will或改變整列 – TheGameiswar

+0

我不會在這個被更新的任何集羣鍵案件。有問題的列是一個varchar,將從40個字符增加到100個,並更改以防止出現空值。目前,允許使用空值,但此列中沒有行包含空值。 – Alex

+0

您需要刪除/創建索引或約束,而不是禁用索引。 –

回答

1

我做了一些測試,看來你不能改變索引列。

test data: 
create table idd 
(
id int identity(1,1), 
name char(33), 
name2 varchar(40) null 
) 

create unique clustered index nci_id on idd(id) 
create index nci_test1 on idd(name2) 

--disable index 
alter index nci_test1 on idd disable 

--alter column 
alter table idd 
alter column test1 varchar(100) not null 

below is the error: 
Msg 5074, Level 16, State 1, Line 36 
The index 'nci_test1' is dependent on column 'test1'. 
Msg 4922, Level 16, State 9, Line 36 
ALTER TABLE ALTER COLUMN test1 failed because one or more objects access this column. 

,因爲我已經聚集key.so如果我放棄聚集鍵,然後在非聚集索引鍵列做一個alter操作發生了什麼這是顯而易見的,結果是same.We只能放棄這些改變之後索引列

drop index [nci_id] on idd 

--alter column 
alter table idd 
alter column test1 varchar(100) not null 

我覺得你有什麼是影響

1.我們不得不放棄聚集鍵第一..heavy TLOG寫到,因爲非聚集鍵也改變有指針一些想法
2 。再次我們必須重建索引

您只能刪除them.Further我建議你用這種方法前進(因爲你不得不放棄聚集索引兩種方式)的

1.Drop指數
2.Alter列數據類型
3.recreate指數

進一步嘗試更改數據庫恢復模型簡單,以儘量減少在此之前操作TLOG寫入也可以增加。下面的問題有一些有趣的答案,它可以幫助你

NOCHECK選項

https://dba.stackexchange.com/questions/48872/quickly-change-null-column-to-not-null

How do you add a NOT NULL Column to a large table in SQL Server?

+0

謝謝,這正是我需要知道的。我不確定是否可以更改恢復模式(我將檢查DBA的權限),但刪除並重新創建索引似乎是正確的操作方法。 – Alex

+0

添加了一些更多的測試數據,請看看這是否對您有幫助,列名可能不準確,因爲我試圖在粘貼後進行修改 – TheGameiswar

+0

在這個例子中,我們根本不使用聚集索引,但我們創建的索引是獨特。我會在我的測試數據庫上試試這個,但是我認爲,由於關鍵不聚集,它應該稍微降低影響。 – Alex