日期:2014-05-16  浏览次数:20448 次

db2与oracle不同的常用sql写法记录(原创)

1、查看前3行数据,列别名如果没有AS 子句,派生的列会命名为 2,这表示它是结果集中的第二列。

db2 => select name,salary+comm from staff fetch first 3 rows only
NAME????? 2????????
--------- ----------
Sanders??????????? -
Pernal????? 78783.70
Marenghi?????????? -
? 3 record(s) selected.


2、db2支持通过“,”分隔在同一个insert语句中插入多个值

db2 => insert into tt values(1),(1)
DB20000I? The SQL command completed successfully.

3、db2没有"create table TABLE_A as select ****"语句,创建表结构一致的表只能通过

db2 => create table pers like staff
DB20000I? The SQL command completed successfully.

4、UPDATE 语句用来修改表或视图中的数据。通过指定 WHERE 子句,可以修改满足条件的每一行的一个或多个列的值。

db2 => update staff set (dept,salary)=(51,70000) where id=150
DB20000I? The SQL command completed successfully.

oraclehedb2都支持下列写法

update tttt set id=3,name='c' where id=1;
5、数据修改操作(插入、更新或删除)的目标中的列变成中间结果表中的列,可以在查询的选择列表中按名称引用这些列

db2 => select salary from old table(update staff set salary=salary*0.2 where id=10)
SALARY??
---------
?19671.50
? 1 record(s) selected.

db2 => select salary from old table(update staff set salary=salary*0.2 where id=10)
SALARY??
---------
? 3934.30
? 1 record(s) selected.

6、事务处理上,db2默认进行自动提交,如需要显示创建事务,则应显示指定"+c"参数,这里应注意,如果指定了事务,即使ddl语句db2也需要提交或者回滚,db2不会显示或隐示的回滚事务。

会话1

$ db2 +c
db2 => connect to sample
?? Database Connection Information
?Database server??????? = DB2/LINUX 9.7.5
?SQL authorization ID?? = DB2INST1
?Local database alias?? = SAMPLE

db2 => create table czm_1(id int)
DB20000I? The SQL command completed successfully.
db2 => insert into czm_1 values(1)
DB20000I? The SQL command completed successfully.
db2 => savepoint savepoint1 on rollback retain cursors
DB20000I? The SQL command completed successfully.
db2 => insert into czm_1 values(2)
DB20000I? The SQL command completed successfully.
db2 => savepoint savepoint2 on rollback retain cursors
DB20000I? The SQL command completed successfully.
db2 => select * from czm_1
ID????????
-----------
????????? 1
????????? 2
? 2 record(s) selected.


会话2,执行下面语句无法查询czm_1,hang住不能继续执行

db2 => connect to sample
?? Database Connection Information
?Database server??????? = DB2/LINUX 9.7.5
?SQL authorization ID?? = DB2INST1
?Local database alias?? = SAMPLE

db2 => select * From czm_1

会话1
db2 => rollback to savepoint savepoint1
DB20000I? The