我找不到任何讨论可以用来备份FK约束的多个可能索引的情况.
从下面的测试看来,在FK创建时FK被绑定到特定索引,这将始终用于验证FK约束,而不管以后是否添加新的更好的索引.
任何人都可以指出任何确认或否认这一点的资源吗?
CREATE TABLE T1(
T1_Id INT IDENTITY(1,1) PRIMARY KEY CLUSTERED NOT NULL,
Filler CHAR(4000) NULL,
)
INSERT INTO T1 VALUES ('');
CREATE TABLE T2(
T2_Id INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
T1_Id INT NOT NULL CONSTRAINT FK REFERENCES T1 (T1_Id),
Filler CHAR(4000) NULL,
)
/*Execution Plan uses clustered index - There is no NCI*/
INSERT INTO T2 VALUES (1,1)
ALTER TABLE T1 ADD CONSTRAINT
UQ_T1 UNIQUE NONCLUSTERED(T1_Id)
/*Execution Plan still use clustered index even after NCI created*/
INSERT INTO T2 VALUES (1,1)
SELECT fk.name,
ix.name,
ix.type_desc
FROM sys.foreign_keys fk
JOIN sys.indexes ix ON ix.object_id = fk.referenced_object_id
AND ix.index_id = fk.key_index_id
WHERE fk.name = 'FK'
ALTER TABLE T2 DROP CONSTRAINT FK
ALTER TABLE T2 WITH CHECK ADD CONSTRAINT FK FOREIGN KEY(T1_Id)
REFERENCES T1 (T1_Id)
/*Now Execution Plan now uses non clustered index*/
INSERT INTO T2 VALUES (1,1)
SELECT fk.name,
ix.name,
ix.type_desc
FROM sys.foreign_keys fk
JOIN sys.indexes ix ON ix.object_id = fk.referenced_object_id
AND ix.index_id = fk.key_index_id
WHERE fk.name = 'FK'
DROP TABLE T2
DROP TABLE T1
最佳答案 马丁,我道歉,这不是一个很好的答案,但既然你让我好奇,我做了一些挖掘.我可以分享的信息是:
目前的版本,包括Denali,不太可能在这种情况下考虑替代方案.