Home [SQL筆記] 表結構和約束的維護
Post
Cancel

[SQL筆記] 表結構和約束的維護

修改表結構

設計表格要考慮周全,儘量不要後期做修改。

  • 新增列 alter table 表名 add 新列名 數據類型
  • 刪除列 alter table 表名 drop column 列名
  • 修改列 alter table 表名 alter column 列名 數據類型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/** 修改表結構 **/
--新增列
--alter table 表名 add 新列名 數據類型
--給員工表添加一列email
alter table Employee add EmployeeEmail varchar(200)

--刪除列
--alter table 表名 drop column 列名
--刪除Email這一列
alter table Employee drop column EmployeeEmail

--修改列
--alter table 表名 alter column 列名 數據類型
--修改地址varcher(300) -> varchqr(200)
alter table Employee alter column EmployeeAddress varchar(200)
--如果裡面已經有記錄是201個字,它會報錯

維護約束(刪除、新增)

知道有這個東西就好了。

  • 刪除添加約束 alter table 表名 drop constraint 約束名
  • 新增約束(check約束) alter table 表名 add constraint 約束名 check(表達式)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
--維護約束(刪除、新增)
--刪除約束
--alter table 表名 drop constraint 約束名
--刪除月薪約束
alter table Employee drop constraint CK__Employee__Employ__37A5467C

--新增約束(check約束)
--alter table 表名 add constraint 約束名 check(表達式)
--新增工資欄位的約束,工資必須介於1000-1000000之間
alter table Employee add constraint CK__Employee__EmployeeSalary check(EmployeeSalary>=1000 and EmployeeSalary<=1000000)

--新增約束(check約束)
--alter table 表名 add constraint 約束名 check(表達式)
--新增約束(主鍵 primary key)
alter table 表名 add constraint 約束名 primary key(列名)
--新增約束(唯一的 unique)
alter table 表名 add constraint 約束名 unique(列名)
--新增約束(默認值 default)
alter table 表名 add constraint 約束名 default 默認值 for 列名
--新增約束(外來鍵 foreign key references)
alter table 表名 add constraint 約束名 foreign key (列名) references 關聯表名(列名(主鍵))
This post is licensed under CC BY 4.0 by the author.