SQL之資料更新
阿新 • • 發佈:2022-04-18
資料更新:INSERT,DELETE,UPDATE
1.插入元組
格式1:insert into 表名 [(列名1[,列名2]…)] values (值1 [,值2]…);功能:一次插入一條指定的元組。
insert into student values ('201215127','王大明','男', 19, 'CS'); insert into sc (sno, cno) values ('200215127','1');格式2:insert into 表名 [(列名1[, 列名2]…)]
values (值11 [, 值21]…),
(值21 [, 值22]…),
…
(值n1 [, 值n2]…);
功能:一次插入多條指定的元組(注:SQL Server 2008新增)。
insertinto course values(2,'數學',null,2), (3,'資訊系統',1,4), (4,'作業系統',6,3), (5,'資料結構',7,4), (6,'資料處理',null,2), (7,'PASCAL語言',6,4);
2.插入子查詢結果
格式1: insert into 表名 [(列名1[, 列名2]…)]
(子查詢)功能: 向指定表中追加子查詢結果中的多個元組(指定表必須存在)。
insert into dept_CS select * from student where sdept='CS';
格式2:select 列1, 列2,… into 表2 from 表1 [where 條件];
功能:要求目標表2不存在,因為在插入時會自動建立表2,並將表1中指定欄位資料複製到表2中。
select * into dept_CS2 from student where sdept='CS';
3.刪除元組
格式: delete from 表名 [where 條件表示式]
功能:從表中刪除符合條件的元組,如果沒有where語句,則刪除所有元組。
注:只能對一個關係起作用,若要從多個關係中刪除元組,則對每個關係分別執行刪除命令,也可以用級聯(cascade)刪除
delete from SC; delete from SC where sno in (select sno from student where sname = '王明');
4.更新元組
格式: update 表名
set 列名1 = 表示式 1| 子查詢[, 列名2 =表示式2 | 子查詢]…[where 條件表示式];
功能:對滿足條件元組的指定列進行更新, 預設where子句,則包含所有元組。
update student set sage = 22 where sno='201215121'; update sc set grade = grade * 1.05; update sc set grade = 0 where sno in( select sno from student where sdept='IS');