Home [SQL筆記] Update Set 修改和刪除數據
Post
Cancel

[SQL筆記] Update Set 修改和刪除數據

R

  • update 表名 set 欄位1=值1,欄位2=值2 where 條件
  • drop刪掉整張表
  • truncate清空數據,不能帶條件。自動編號-清0
  • delete清空數據,能帶條件。自動編號-續寫

修改數據

update 表名 set 欄位1=值1,欄位2=值2 where 條件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
--修改
--語法
--update 表名 set 欄位1=值1,欄位2=值2 where 條件
--工資調整,每個人加薪$1000
update Employee set EmployeeSalary= EmployeeSalary+1000
--將員工編號為7的人加薪$500
update Employee set EmployeeSalary= EmployeeSalary+500
where EmployeeID=7
--將軟體部(id=2)員工工資低於30000的調整成30000
update Employee set EmployeeSalary=30000
where DepartmentId=2 and EmployeeSalary<30000
--修改張三的工資是以前的2倍,並且把地址改成上海
update Employee 
set EmployeeSalary=EmployeeSalary*2,EmployeeAddress='上海'
where EmployeeName='張三'

刪除數據

  • drop刪掉整張表
  • truncate清空數據,不能帶條件。自動編號-清0
  • delete清空數據,能帶條件。自動編號-續寫
1
2
3
4
5
6
7
8
9
10
11
12
--刪除
--語法:
--delete from 表名 where 條件
--刪除員工表所有記錄
delete from Employee
--刪除市場部(id=1)中,工資大於50000的人
delete from Employee where DepartmentId = 1 and EmployeeSalary > 50000

--關於刪除(drop, truncate,delete)
drop table Employee --刪除表對象
delete table Employee --刪除所有數據。可以帶條件,刪除符合條件的數據
truncate table Employee --刪除數據(清空數據),不能帶條

truncate & delete 區別

  • truncate 清空所有數據,不能有條件
  • delete 可以刪除所有的數據,可以帶條件,刪除符合條件的數據

自動編號(truncate & delete)

假設表中自動編號:1, 2, 3, 4, 5

  • 使用 truncate 清空數據後,編號清0,重新加入數據,編號仍然是:1,2,3,4,5
  • 使用 delete 清空數據後,編號續寫,重新加入數據,編號是:6,7,8,9,10

  • 如果自動編號:1, 2, 3, 4, 5,用delete刪除編號5,再新增一筆會是6,不會從5開始,被delete刪掉5,這個表就再也不會有5。

https://www.bilibili.com/video/BV1XV411C7TP?p=6

This post is licensed under CC BY 4.0 by the author.