网课地址:
https://www.bilibili.com/video/BV1XV411C7TP?p=2&vd_source=5dc01f9735b9f8ed4310f9c5db7357a6
创建数据库
使用脚本创建数据库,并初始化数据库的大小与位置
删除数据库
创建数据库的简写
创建数据表:创建表必须在相对应的数据库下创建
切换数据库
创建表的基本语法
删除表
--创建数据库
if EXISTS (select * from sys.databases where name = 'DBTEST')
drop database DBTEST
create database DBTEST
on --数据文件
(
name = 'DBTEST',
filename = 'D:\program1\database\DBTEST.mdf',
size = 5MB,
filegrowth = 2MB
)
log on
(
name = 'DBTEST_log',
filename = 'D:\program1\database\DBTEST_log.ldf',
size = 5MB,
filegrowth = 2MB
)
--切换数据库
use DBTEST
--判断表是否存在
if exists (select * from sys.objects where name = 'Department' and type='U')
drop table Department
--创建表
create table Department
(
DepartmentID int primary key identity(1,1),
DepartmentName nvarchar(50) not null,
DepartmentRemark text
)
create table People
(
PeopleID int primary key identity(1,1),
DepartmentID int references Department(DepartmentID) not null,
PeopleName nvarchar(50) not null,
PeopleSex nvarchar(1) default('男') check(PeopleSex='男' or PeopleSex = '女') not null,
PeopleBrith smalldatetime not null,
PeopleSalary decimal(12,2) check(PeopleSalary>=1000 and PeopleSalary<=100000)not null,
PeoplePhone varchar(20) unique not null,
PeopleAddress nvarchar(300),
PeopleAddTime smalldatetime default(getdate())
)
sqlserver字符串数据类型
当表名是关键字时
创建字段、类型及约束
设置外键关联,引用外键,并添加约束,添加的数据必须要在外键所在的表格中存在时才能存入数据库
表结构和约束的维护
表结构:增加、删除、修改列,在现实中如果数据库中已经有数据,在修改列名或者列属性的时候有可能会报错,尽量减少表结构的修改
维护约束
删除约束
第一种
第二种
添加约束
插入数据
第一种
第二种:一般不使用简写的方式,选择第一种
第三种:一次性插入多行