这两种定义外键的方式有什么不同吗?
在下面的表定义中,这两个列定义有什么区别,或者第二个只是创建一个自动命名的外键索引?
CREATE TABLE dbo.Employee
(
dept_id int NOT NULL
CONSTRAINT fk_employee_deptid FOREIGN KEY REFERENCES Department(dept_id),
empType_id int NOT NULL REFERENCES EmployeeType(empType_id)
/* ... other columns ... */
);
In the following table definition, what is the difference between these two column definitions, or does the second just create an automatically named foreign key index?
CREATE TABLE dbo.Employee
(
dept_id int NOT NULL
CONSTRAINT fk_employee_deptid FOREIGN KEY REFERENCES Department(dept_id),
empType_id int NOT NULL REFERENCES EmployeeType(empType_id)
/* ... other columns ... */
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
唯一的区别是,第二个名称将被赋予一个系统生成的名称,该名称可能比您自己分配的名称更神秘。
如果存在明确的可能性,则列名称也是可选的。
还可以工作。最终结果同样没有区别。 FK 声明的完整语法是
可选的,包含在方括号中。
The only difference is that the second one will be given a system generated name that will likely be more cryptic than one you allocate yourself.
The column name is also optional where there is an unambiguous possibility.
can also work. Again no difference in the end result. The full grammar for the FK declaration is
Optional items are enclosed in square brackets.
唯一真正的区别是后者将获得系统定义的名称。前者是推荐的方法,尽管我承认我很懒,偶尔会使用后者。
如果您仔细观察,您会注意到的另一个区别是,如果您自己不指定名称,则
sys.foreign_keys.is_system_named
列将设置为 1。The only real difference is that the latter one will get a system-defined name. The former is the recommended method, though I will admit I am lazy and use the latter occasionally.
One other difference you will notice, if you're looking closely, is that the column
sys.foreign_keys.is_system_named
is set to 1 if you don't specify the name yourself.在回答你的第二个问题时,两者都没有创建索引。如果您希望对 FK 字段建立索引(大多数情况下您都会这样做),那么您需要在该字段上创建索引。
And in answer to your second question, neither creates an index. If you want the FK field to be indexed (and most of the time you do) then you need to create an index on the field.