• 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的了

     
  • 相关阅读:
    python内置的魔术命令(builtin magic commands)
    绘制ROC曲线
    python with语句中的变量有作用域吗?
    Visual Studio上编译ncnn
    loss函数学习笔记
    Install zeal on ubuntu16.04
    cmake方式使用vlfeat
    整理读研期间用过、改进过、写过的代码
    ubuntu下使用matplotlib绘图无法显示中文label
    error: each element of 'ext_modules' option must be an Extension instance or 2-tuple
  • 原文地址:https://www.cnblogs.com/cnmarkao/p/3848760.html
Copyright © 2020-2023  润新知