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

DB2 常用SQL语句
1. 创建从1开始,自增为1的序列:
CREATE SEQUENCE "MySchema"."MySeq" AS INTEGER START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE
NO CYCLE CACHE 20 NO ORDER


2. 将t_a中除ID外的字段值拷贝到t_b中,t_b的ID为主键,由seq生成:
INSERT
INTO
    t_b
    (
        ID, NAME, AGE
    )
SELECT
    MySeq.nextVal, NAME, AGE
FROM
    t_a;


3. 批量插入:
INSERT
INTO
    t_b
    (
        ID, NAME, AGE
    )
    VALUES
    (
        MySeq.nextVal,'Lilei',22
    )
    ,
    (
        MySeq.nextVal,'Lucy',18
    );


4. 分页查询:
SELECT
    *
FROM
    (
        SELECT
            ROW_NUMBER() OVER(ORDER BY NAME ASC, AGE DESC) AS row_num, NAME, AGE
        FROM
            t_b) t
WHERE
    t.row_num >= 21
AND t.row_num <= 30


注:
OVER()的参数指定按什么字段来排序,可以为空。
可以用BETWEEN 21 AND 30来替换上面的分页条件。