1、取前N条记录
Oracle:SELECT * FROM TableName WHERE rownum <= N;
DB2:SELECT * FROM TableName fetch first N rows only;
2、取得系统日期
Oracle:SELECT sysdate FROM dual;
DB2:SELECT current timestamp FROM sysibm.sysdummy1;
3、空值转换
Oracle:SELECT productid,loginname,nvl(cur_rate,'0') FROM TableName ;
DB2:SELECT productid,loginname,value(cur_rate,'0') FROM TableName;
Coalesce(cur_rate,'0')
4、类型转换(8版有了to_char,to_date,9版新增了to_number)
Oracle:SELECT to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') FROM dual;
DB2:SELECT varchar(current timestamp) FROM sysibm.sysdummy1;
Oracle数据类型改变函数:to_char()、to_date()、to_number()等;如果仅仅取年,月,日等,可以用to_char(sysdate, 'YYYY'),to_char('MM') ,to_char('DD')取得。只取年月日TRUNC(SYSDATE),取时分秒TO_CHAR(SYSDATE,'HH24:MI:SS')。
DB2数据类型改变函数:char()、varchar()、int()、date()、time()等;取得年,月,日等的写法:YEAR(current timestamp),MONTH(current timestamp),DAY(current timestamp),HOUR(current timestamp),MINUTE(current timestamp),SECOND(current timestamp),MICROSECOND(current timestamp),只取年月日可以用DATE(current timestamp),取时分秒TIME(current timestamp)。Char()是定长字符串(1-255),varchar()为非定长字符串(1-32672)日期,时间形态变为字符形态: char(current date),char(current time)将字符串转换成日期或时间形态:TIMESTAMP('2002-10-2012:00:00'),DATE('2002-10-20'),DATE('10/20/2002'),TIME('12:00:00')
目前DB2 V8也支持to_char和to_date
5、快速清空大表
Oracle:TRUNCATE TABLE TableName ;
DB2:ALTER TABLE TableName active NOT logged initially WITH empty TABLE;
6、关于ROWID
Oracle它是由数据库唯一产生的,在程序里可以获得DB2 v8也有此功能。
7、To_Number
Oracle:SELECT to_number('123') FROM dual;
DB2:SELECT cast('123' AS integer) FROM sysibm.sysdummy1;
SELECT CAST ( current time AS char(8)) FROMsysibm.sysdummy1
8、创建类似表
Oracle:CREATE TABLE a AS SELECT * FROM b ;
DB2:CREATE TABLE a LIKE b ;
CREATE TABLE tab_newAS SELECT col1,col2…FROMtab_old DEFINITION ONLY (8版有效,9版无效)
9、decode方法
Oracle:decode方法(DECODE(条件,值1,翻译值1,值2,翻译值2,...值n,翻译值n,缺省值))或者case语句DB2中只有CASE表达式SELECT id ,name ,CASE WHEN integer(flag)=0 THEN ‘假’ WHEN integer(flag)=1 THEN ‘真’ ELSE ‘异常’END FROM TEST或者SELECT id ,name , CASE integer(flag) WHEN 0 THEN ‘假’ WHEN 1 THEN ‘真’ELSE ‘异常’END FROM TEST
10、子查询(8版,9版也支持子查询)
Oracle:直接用子查询
Db2:WITH语句WITH a1 AS(SELECT max(id) AS aa1 FROM test ) SELECT id ,aa1 FROM test ,a1
11、数据类型
比较大的差别:
Oracle:char 2000
DB2: char 254
Oracle: date datetime
Db2: DATE:日期TIME:时间TIMESTAMP:日期时间
12、递归查询
Oracle语法简单,CONNECT BY PRIOR ... START WITH ...:
SELECT DISTINCT parent
FROM (SELECT T.parent FROM TABLE1 T
CONNECT BY PRIOR T.parent = T.child --递归的方向为从子向父
START WITH T.child = 'xxx' )
DB2较难理解,要WITH一个虚拟表:
WITH PAR_CH(child, parent) AS
( SELECT child, parent FROM
TABLE1
WHERE
child = 'xxx' --设置递归起点
UNION ALL
SELECT
T.child, T.parent
FROM
PAR_CH VT, TABLE1 T
WHERE VT.parent = T.child --递归的方向为从子向父
)
SELECT DISTINCT parent
FROM PAR_CH
如上图,从grandchild开始查询其所有的父节点,首先设定虚拟表起点,即左边第四行;依次往上推,其父亲是son = 上一行的child,即VT.parent = T.child...
最后查询结果为:
---------------------------
son
father
grandpa
---------------------------