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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章