SQL Server数据库笔记整理(一)

  • 数据库:持久化存储,优化读写,保证数据的有效性。 关系型数据库是基于E-R模型(即实体-模型),使用SQL语言进行操作。
  • 数据库分类:文档型数据库、服务型数据库(使用居多) (移动端即手机都是使用sqlite文档型数据库)
  • 三范式:列不可拆分、唯一标识、引用主键
  • 关系及储存:
1对1 1对多 多对多
1个A对1个B 1个A对几个B 1个A对几个B
1个B对1个A 1个B对1个A 1个B对几个A
关系存A或B 关系存B 关系存新建表C
  • 数据库文件:1.主数据文件.mdf(包含数据库启动信息,并存储数据) 2.辅助数据文件 即日志文件.ldf
  • 一个数据库有且只有一个主文件
  • 至少有一个日志文件
  • 数据库分为:用户数据库(自定义)、系统数据库(含5个,即master、Model、tempdb、msdb、resource(不显示在软件框中))
  • 数据库对象:表、数据类型、视图、索引、约束、默认值、存储过程、触发器
  • 约束:主键、非空、唯一、默认、检查、外键
  • 外键:A表决定B表,则A表为主键表,B表为外键表,外键在外键表上
T-SQL操作数据库
  • 创建数据库
create database student
on
(
name="student",	//主文件的逻辑名
filename="C:/student.mdf",	//存储数据库主文件的地址
size=5mb,//数据库主文件大小
maxsize=80mb,//最大容量
filegrowth=10% //增长值,以原大小的10%增长
)
log on 
(
name="student_log",//日志文件的逻辑名
filename="C:/student.ldf",//日志文件的存放地址
size=2mb,//日志文件的大小
maxsize=5mb,//日志文件的容量最大值
filegrowth=1mb//增长值,以1mb为单位增长
);
  • 删除数据库
drop database student
  • 分离数据库
sp_detach_db student
  • 附加数据库
create database student
on
(
filename="C:\Student.mdf"
)
for attach
  • 查看数据库信息、存储过程
exec sp_helpdb student
  • 创建表
use student//打开数据库
创建学生表
create table stuifo//表名
(
stuid int primary key,//学号,设为主键,int型
stuname varchar(10) not null,//姓名,非空,varchar(10)型
cid int    //班级,int型(做外键)
)

 - 创建班级表

create table classifo//表名
(
cid int primary key       //班级序号,设为主键,int型
)
  • 建立外键
alter table stuifo
add constraint stuclassifo(外键名) 
foreign key(cid) references classifo (cid)
  • 删除表
drop table stuifo
  • 添加列
alter table stuifo
add stusex bit
  • 删除列
alter table stuifo
drop column stusex
  • 修改列的数据类型
alter table student
alter column stuname char(10)//要修改的类型
  • 插入行(数据(记录))
use student
insert stuifo values(1,'小红',2)
或
insert into stuifo values(1),('小红'),(2)
  • 修改行(数据)
use student
update stuifo set stuid=1,cid=3 
where stuname='小红'//条件,当姓名为小红时执行
  • 删除行(数据)
删除学号为1的数据
delete stuifo 
where stuid=1
  • 清空行(数据)
truncate table stuifo(含有外键不可执行)
数据库——数据类型
char(n) varchar(n) varchar(max) text
nchar(n) nvarchar(n) nvarchar(max) ntext
bit binary varbinary varbinary(max)
tinyint smallint int bigint
numeric demical(p,s) smallmoney money
float(n) real datetime datetime2
smalldatetime date time
datetimeoffset timestamp sql_variant uniqueidentifier
xml cursor table
  • demical(p,s):p为位数,s为小数位
  • 带n的数据类型表示unicode编码,每一个字符占一个字节,若无n表非unicode编码,英文数字占一个字符,汉字占两个字节。
  • 带var的数据类型表示为可变长度,如若存"abc",char(5)存为"abc (后面用两个空格补位)",varchar(5)存为"abc"(不补位)。

我的公众号:德秀笔记
公众号用来总结一些学习笔记。

在这里插入图片描述
我的 github博客:
憨秀清 https://oydq.github.io

发布了5 篇原创文章 · 获赞 5 · 访问量 346

猜你喜欢

转载自blog.csdn.net/m0_46652631/article/details/105213161