“外键"与“外键"之间的区别在于:和“约束外键";

问题描述:

我的意思是,例如,我可以创建表

I mean for example I can create table like

create table XTable
( 
  idt int not null primary key,
  value nvarchar(50),
  idq int,
  constraint fk_idq foreign key(idq) references YTable(idq)
)

我可以这样创建它

create table XTable
(
  idt int not null primary key,
  value nvarchar(50),
  idq int,
  foreign key(idq) references YTable(idq)
)

我通常像第二个示例中那样创建表,但是现在我对第一个示例感到好奇.有什么区别?

I usually create table like in the second example but now I'm curious about the first example. What is the difference?

第一个选择纯粹是为了命名约束.

The first option is purely for naming the constraint.

来自 SQL外键约束

要允许命名FOREIGN KEY约束并在多个列上定义FOREIGN KEY约束,请使用以下SQL语法

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax

CREATE TABLE Orders
(
  O_Id int NOT NULL,
  OrderNo int NOT NULL,
  P_Id int,
  PRIMARY KEY (O_Id),
  CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)
  REFERENCES Persons(P_Id)
)

此外,来自创建表(交易记录-SQL)可以看到[ CONSTRAINT constraint_name ]是可选的.

Also, from CREATE TABLE (Transact-SQL) one can see that [ CONSTRAINT constraint_name ] is optional.