Differences between “foreign key” and “constraint foreign key”

前端 未结 3 728
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 18:13

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 foreig         


        
相关标签:
3条回答
  • 2020-12-05 18:22

    Apart from controlling the name, nothing really. SQL Server will supply a name if you omit it. FYI, you only need this syntax (SQL Fiddle):

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

    Here's a fuller example.

    0 讨论(0)
  • 2020-12-05 18:30

    The first option is purely for naming the constraint.

    From SQL FOREIGN KEY Constraint

    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)
    )
    

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

    0 讨论(0)
  • 2020-12-05 18:38

    The first one assigns a user-defined name to the foreign key, the second one will assign a system-generated name to the foreign key.

    User-defined foreign key names can be useful for subsequent statements like these:

    ALTER TABLE XTable DROP    CONSTRAINT fk_idq;
    ALTER TABLE XTable ENABLE  CONSTRAINT fk_idq;
    ALTER TABLE XTable DISABLE CONSTRAINT fk_idq;
    

    It's harder to alter constraints with system-generated names, as you have to discover those names first.

    0 讨论(0)
提交回复
热议问题