zoukankan      html  css  js  c++  java
  • SQL Server外键约束

    SQL Server中主外键的定义:

    1.

    create table dept
    (
    dept_no int primary key,
    dept_name nvarchar(50) not null
    )
    insert into dept values(10,'IT'),(20,'Finance'),(30,'Engneer')
    
    create table employee ( employee_id int primary key, employee_name nvarchar(50) not null, dept_no int foreign key references dept(dept_no) )
    上面的写法,是列级定义,直接定义列字段的时候定义foreign key

    2.

    create table dept
    (
    dept_no int primary key,
    dept_name nvarchar(50) not null
    prmary key (dept_no)
    )
    insert into dept values(10,'IT'),(20,'Finance'),(30,'Engneer')
    
    create table employee
    (
    employee_id int primary key,
    employee_name nvarchar(50) not null,
    dept_no int,
    constraint dept_no_fk foreign key(dept_no) references dept(dept_no)
    )
    这是表级的定义

    3.已经创建了没有定义主外键的表,可以使用alter table修改

    alter table employee 
    add foreign key (dept_no) references dept(dept_no)
    
    
    alter table employee
    add constraint dept_no_fk foreign key (dept_no)
    references dept(dept_no)

    添加主键

    alter table dept
    add constraint dept_no_pk primary key(dept_no)

    4.去除主键

    alter table dept drop constraint dept_no_pk 

    去除外键

    alter table employee 
    drop constraint dept_no_fk
     

    建了删,删了建的,手疼原本打算把MySQL的语句也写上的,原因是昨晚看了关于MySQL的视频,关于check不起作用,而且自己外键约束也模糊,不知道怎么写,原来是两种写法,这也是看MySQL视频看到的。只好改天再写MySQL的了

     
  • 相关阅读:
    [leetcode]Insert Interval @ Python
    [leetcode]Merge Intervals @ Python
    [leetcode]Maximum Subarray @ Python
    [leetcode]Jump Game II @ Python
    [leetcode]Jump Game @ Python
    [leetcode]Wildcard Matching @ Python
    tomcat 配置https 外部链接显示证书不安全 原因找到为其他地方的链接用的ip地址,证书是发给域名的所以报错
    netstat -tanp ss -lntup |grep
    https://www.pstips.net/ powershell
    awk之getline()函数运用
  • 原文地址:https://www.cnblogs.com/cnmarkao/p/3848760.html
Copyright © 2011-2022 走看看