SQL之数据更新

数据更新: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新增)。
insert into 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');

 

posted @ 2022-04-18 22:36  ADoubleLiu  阅读(506)  评论(0)    收藏  举报