外键是在SQL Server中自动索引的吗? [英] Are foreign keys indexed automatically in SQL Server?

查看:120
本文介绍了外键是在SQL Server中自动索引的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的SQL语句会自动在Table1.Table1Column上创建一个索引,还是必须显式地创建一个索引?

数据库引擎是SQL Server 2000

  CREATE TABLE [Table1](
...
CONSTRAINT [FK_Table1_Table2] FOREIGN KEY

[Table1Column]
)参考[Table2](
[Table2ID]



解决方案

SQL Server不会自动在外键上创建索引。另外从MSDN:


一个FOREIGN KEY约束没有
只能链接到一个PRIMARY KEY
约束在另一张桌子上;也可以定义
来引用另一个表
中的UNIQUE约束的
列。 FOREIGN KEY
约束可以包含空值;
但是,如果组合
FOREIGN KEY约束中的任何列包含空值
值,则会跳过组成FOREIGN KEY
约束的所有值
的验证。为了确保
复合FOREIGN
KEY约束的所有值都已验证,请在所有参与的
列中指定
NOT NULL。
blockquote>

Would the following SQL statement automatically create an index on Table1.Table1Column, or must one be explicitly created?

Database engine is SQL Server 2000

       CREATE TABLE [Table1] (
. . .
            CONSTRAINT [FK_Table1_Table2] FOREIGN KEY 
            (
                [Table1Column]
            ) REFERENCES [Table2] (
                [Table2ID]
            )

        )

解决方案

SQL Server will not automatically create an index on a foreign key. Also from MSDN:

A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table. A FOREIGN KEY constraint can contain null values; however, if any column of a composite FOREIGN KEY constraint contains null values, verification of all values that make up the FOREIGN KEY constraint is skipped. To make sure that all values of a composite FOREIGN KEY constraint are verified, specify NOT NULL on all the participating columns.

这篇关于外键是在SQL Server中自动索引的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆