4

我找不到任何讨论有多个可能的索引可用于备份 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
4

1 回答 1

2

马丁,我很抱歉这不是一个很好的答案,但由于你也让我感到好奇,所以我做了一些挖掘。我可以分享的信息是:

在包括 Denali 在内的当前版本中,在这种情况下不太可能考虑替代方案。

于 2011-09-08T19:27:29.950 回答