DML语句
DML(数据操纵语言):用于操纵表和视图的数据,分为SELECT、INSERT、UPDATE、DELETE。
1、DELETE
格式:DELETE FROM <table|view> [WHERE Conditions];
①截断表:TRUNCATE TABLE 表名称
适用情况:如果用户确定要删除表的所有数据,要么使用TRUNCATE TABLE 表名称 语句速度较快。
注:DELETE语句的操作可以回退,但TRUNCATE TABLE语句的操作不能回退。
②使用子查询删除数据 优点:可以降低网络开销、效率更高。
例1:
--删除前查询
SQL> SELECT * FROM DEPT_TEMP;
DEPTNO DNAME LOC
------ -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
--使用子查询删除
SQL> DELETE FROM DEPT_TEMP WHERE DNAME=(SELECT DNAME FROM DEPT_TEMP WHERE DEPTNO=10);
1 row deleted
--删除后查询
SQL> SELECT * FROM DEPT_TEMP;
DEPTNO DNAME LOC
------ -------------- -------------
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
2、UPDATE
格式:UPDATE <table|view>
SET <column=valun>[,<column=valun>,...]
[WHERE conditions];
①使用default选项更新数据:如果列存在默认值,则使用默认值。否则使用NULL。
例1:
SQL> update emp_temp set hiredate=default where empno=7369;
1 row updated
更新后:
SQL> SELECT * FROM EMP_TEMP;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
----- ---------- --------- ----- ----------- --------- --------- ------
7369 SMITH CLERK 7902 800.00 20
7499 ALLEN SALESMAN 7698 1981-2-20 1600.00 300.00 30
7521 WARD SALESMAN 7698 1981-2-22 1250.00 500.00 30
7566 JONES MANAGER 7839 1981-4-2 2975.00 20
7654 MARTIN SALESMAN 7698 1981-9-28 1250.00 1400.00 30
7698 BLAKE MANAGER 7839 1981-5-1 2850.00 30
7782 CLARK MANAGER 7839 1981-6-9 2450.00 10
7788 SCOTT ANALYST 7566 1987-4-19 3000.00 20
7839 KING PRESIDENT 1981-11-17 5000.00 10
7844 TURNER SALESMAN 7698 1981-9-8 1500.00 0.00 30
7876 ADAMS CLERK 7788 1987-5-23 1100.00 20
7900 JAMES CLERK 7698 1981-12-3 950.00 30
7902 FORD ANALYST 7566 1981-12-3 3000.00 20
7934 MILLER CLERK 7782 1982-1-23 1300.00 10
14 rows selected
②使用子查询更新数据 优点:可以降低网络开销、效率更高。
例1:
SQL> UPDATE EMP_TEMP SET (JOB,MGR,HIREDATE)=(SELECT JOB,MGR,HIREDATE FROM EMP_TEMP WHERE ENAME=upper('allen')) WHERE EMPNO=7369;
1 row updated
更新后:
SQL> SELECT * FROM EMP_TEMP;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
----- ---------- --------- ----- ----------- --------- --------- ------
7369 SMITH SALESMAN 7698 1981-2-20 800.00 20
7499 ALLEN SALESMAN 7698 1981-2-20 1600.00 300.00 30
7521 WARD SALESMAN 7698 1981-2-22 1250.00 500.00 30
7566 JONES MANAGER 7839 1981-4-2 2975.00 20
7654 MARTIN SALESMAN 7698 1981-9-28 1250.00 1400.00 30
7698 BLAKE MANAGER 7839 1981-5-1 2850.00 30
7782 CLARK MANAGER 7839 1981-6-9 2450.00 10
7788 SCOTT ANALYST 7566 1987-4-19 3000.00 20
7839 KING PRESIDENT 1981-11-17 5000.00 10
7844 TURNER SALESMAN 7698 1981-9-8 1500.00 0.00 30
7876 ADAMS CLERK 7788 1987-5-23 1100.00 20
7900 JAMES CLERK 7698 1981-12-3 950.00 30
7902 FORD ANALYST 7566 1981-12-3 3000.00 20
7934 MILLER CLERK 7782 1982-1-23 1300.00 10
14 rows selected
3、INSERT
①插入单行数据
格式:INSERT INTO <table|view> [<column1[,....,columnN]>]
VALUES(value1[,...,valueN]);