DB2經常使用SQL的寫法(未整理)

UPDATE FROM
update   a   set   aa   =(select   bb   from   b   where   a.cc   =   b.cc)  
  where   exists   (select   b.cc   from   a.cc   =b.cc)  node

 

1. 創建數據庫DB2_GCBsql

CREATE DATABASE DB2_GCB ON G: ALIAS DB2_GCB

USING CODESET GBK TERRITORY CN COLLATE USING SYSTEM DFT_EXTENT_SZ 32數據庫

2. 鏈接數據庫編程

connect to sample1 user db2admin using 8301206session

3. 創建別名oracle

create alias db2admin.tables for sysstat.tables;

CREATE ALIAS DB2ADMIN.VIEWS FOR SYSCAT.VIEWS

create alias db2admin.columns for syscat.columns;

create alias guest.columns for syscat.columns;app

4. 創建表tcp

create table zjt_tables as

(select * from tables) definition only;

create table zjt_views as

(select * from views) definition only;ide

5. 插入記錄函數

insert into zjt_tables select * from tables;

insert into zjt_views select * from views;

6. 創建視圖

create view V_zjt_tables as select tabschema,tabname from zjt_tables;

7. 創建觸發器

CREATE TRIGGER zjt_tables_del

AFTER DELETE ON zjt_tables

REFERENCING OLD AS O

FOR EACH ROW MODE DB2SQL

Insert into zjt_tables1 values(substr(o.tabschema,1,8),substr(o.tabname,1,10))

8. 創建惟一性索引

CREATE UNIQUE INDEX I_ztables_tabname

[size=3]ON zjt_tables(tabname);

9. 查看錶

select tabname from tables

where tabname='ZJT_TABLES';

10. 查看列

select SUBSTR(COLNAME,1,20) as 列名,TYPENAME as 類型,LENGTH as 長度

from columns

where tabname='ZJT_TABLES';

11. 查看錶結構

db2 describe table user1.department

db2 describe select * from user.tables

12. 查看錶的索引

db2 describe indexes for table user1.department

13. 查看視圖

select viewname from views

where viewname='V_ZJT_TABLES';

14. 查看索引

select indname from indexes

where indname='I_ZTABLES_TABNAME';

15. 查看存貯過程

SELECT SUBSTR(PROCSCHEMA,1,15),SUBSTR(PROCNAME,1,15)

FROM SYSCAT.PROCEDURES;

16. 類型轉換(cast)

ip datatype:varchar

select cast(ip as integer)+50 from log_comm_failed

17. 從新鏈接

connect reset

18. 中斷數據庫鏈接

disconnect db2_gcb

19. view application

LIST APPLICATION;

20. kill application

FORCE APPLICATION(0);

db2 force applications all (強迫全部應用程序從數據庫斷開)

21. lock table

lock table test in exclusive mode

22. 共享

lock table test in share mode

23. 顯示當前用戶全部表

list tables

24. 列出全部的系統表

list tables for system

25. 顯示當前活動數據庫

list active databases

26. 查看命令選項

list command options

27. 系統數據庫目錄

LIST DATABASE DIRECTORY

28. 表空間

list tablespaces

29. 表空間容器

LIST TABLESPACE CONTAINERS FOR

Example: LIST TABLESPACE CONTAINERS FOR 1

30. 顯示用戶數據庫的存取權限

GET AUTHORIZATIONS



 

1. 啓動實例(db2inst1):

db2start

2. 中止實例(db2inst1):

db2stop

3. 列出全部實例(db2inst1)

db2ilist

5.列出當前實例:

db2 get instance

4. 察看示例配置文件:

db2 get dbm cfg|more

5. 更新數據庫管理器參數信息:

db2 update dbm cfg using para_name para_value

6. 建立數據庫:

db2 create db test

7. 察看數據庫配置參數信息

db2 get db cfg for test|more

8. 更新數據庫參數配置信息

db2 update db cfg for test using para_name para_value

10.刪除數據庫:

db2 drop db test

11.鏈接數據庫

db2 connect to test

12.列出全部表空間的詳細信息。

db2 list tablespaces show detail

13.查詢數據:

db2 select * from tb1

14.數據:

db2 delete from tb1 where id=1

15.建立索引:

db2 create index idx1 on tb1(id);

16.建立視圖:

db2 create view view1 as select id from tb1

17.查詢視圖:

db2 select * from view1

18.節點編目

db2 catalog tcp node node_name remote server_ip server server_port

19.察看端口號

db2 get dbm cfg|grep SVCENAME

20.測試節點的附接

db2 attach to node_name

21.察看本地節點

db2 list node direcotry

22.節點反編目

db2 uncatalog node node_name

23.數據庫編目

db2 catalog db db_name as db_alias at node node_name

24.察看數據庫的編目

db2 list db directory

25.鏈接數據庫

db2 connect to db_alias user user_name using user_password

26.數據庫反編目

db2 uncatalog db db_alias

27.導出數據

db2 export to myfile of ixf messages msg select * from tb1

28.導入數據

db2 import from myfile of ixf messages msg replace into tb1

29.導出數據庫的全部表數據

db2move test export

30.生成數據庫的定義

db2look -d db_alias -a -e -m -l -x -f -o db2look.sql

31.建立數據庫

db2 create db test1

32.生成定義

db2 -tvf db2look.sql

33.導入數據庫全部的數據

db2move db_alias import

34.重組檢查

db2 reorgchk

35.重組表tb1

db2 reorg table tb1

36.更新統計信息

db2 runstats on table tb1

37.備份數據庫test

db2 backup db test

38.恢復數據庫test

db2 restore db test

399\.列出容器的信息

db2 list tablespace containers for tbs_id show detail

40.建立表:

db2 ceate table tb1(id integer not null,name char(10))

41.列出全部表

db2 list tables

42.插入數據:

db2 insert into tb1 values(1,’sam’);

db2 insert into tb2 values(2,’smitty’);

 

-- 建立一個自定義單值類型
create   distinct type var_newtype
as decimal(5,2) with comparisons;

-- var_newtype 類型名
-- decimal(5,2) 實際的類型

-- 刪除一個自定義單值類型
drop distinct type var_newtype;


-- 建立一個自定義結構數據類型
create type my_type as(
username varchar(20),
department integer,
salary decimal(10,2))
not final
mode db2sql;


-- 修改自定義結構數據類型,我目前尚未發現刪除屬性的方法.
alter type my_type
add attribute hiredate date;


-- 刪除自定義結構數據類型

drop type my_type;


-- 獲取系統當前日期
select current date from sysibm.sysdummy1;
select current time from sysibm.sysdummy1;
select current timestamp from sysibm.sysdummy1;


--sysibm.sysdummy1表是一個特殊的內存中的表,用它能夠發現如上面演示的 DB2 寄存器的值。您也可使用關鍵字 VALUES 來對寄存器或表達式求值。
VALUES current date;
VALUES current time;
VALUES current timestamp;

-- VALUES的更多用法

VALUES 2+5;

VALUES 'hello lavasoft!';

values 56
union all
values 45;

values 1,2,3,4,5,6
union all
values 7,8,9,10,11,12
order by 1;

-- 更多變態級DB2 SQL寫法,AnyOneTable表示任意一個存在的表

select 234 from AnyOneTable;
select distinct 234 from AnyOneTable;
select distinct 234 as 1 from AnyOneTable;

select 'DB2變態級的SQL哈哈' from AnyOneTable;
select distinct 'DB2變態級的SQL哈哈' from AnyOneTable;
select distinct 'DB2變態級的SQL哈哈' as 1 from AnyOneTable;

     --(嘿嘿,好玩吧,你能夠用任意一個表來當sysibm.sysdummy1用.不過不推薦這麼作,除非你不記得sysibm.sysdummy1怎麼寫了,Oracle中(對應dual)也同樣!哈哈哈哈!)


-- 定義變量,還能夠設定默認值,給變量賦值

declare var1 char(2);
declare var2 int default 0;

set var1 = 'aa';
set var2 =23;


--建立一個動態遊標變量
declare d_cur integer;


-- 給變量賦值的另外一種方法

values expr1, expr2, expr3 into a, b, c;
-- 至關於
set a = expr1;
set b = expr2;
set c = expr3;

-- 還有一種賦值方式

set prodname = (case
                   when (name is not null) then name
                   when (namestr is not null) then namestr
                   else   defaultname
                 end);
-- 至關於
set prodname = coalesce(name, namestr, defaultname);
--這個相似oracle的decode()和nvl()函數的合併.


-- 定義一個遊標
declare cur1 cursor with return to client for select * from dm_hy;
declare cur2 cursor for select * from dm_hy; -- 靜態遊標


-- 建立數據表,並添加註釋,插入數據.
CREATE TABLE tbr_catalog (
   id bigint   not null   generated by default as identity,
   type smallint not null,
   name varchar(255),
   parentid bigint,
   cataloglevel bigint,
   description varchar(255),
   PRIMARY KEY   (id)
);
comment on table tbr_catalog is 'Birt報表目錄表';
comment on column tbr_catalog.ID is '標識';
comment on column tbr_catalog.type is '目錄類型';
comment on column tbr_catalog.name is '目錄名稱';
comment on column tbr_catalog.parentid is '目錄父標識';
comment on column tbr_catalog.cataloglevel is '目錄層次';
comment on column tbr_catalog.description is '目錄描述';

-- 給數據表插入數據
insert into tbr_catalog(id, type, name, parentid, cataloglevel, description)
values (1, 0, '系統報表', 0, 0, '');
insert into tbr_catalog(id, type, name, parentid, cataloglevel, description)
values (2, 1, '用戶報表', 0, 0, '');

-- 建立外鍵
alter table tbr_storage
add constraint fk_tbr_storage
foreign key (catalogid)
references tbr_catalog(id);

-- 更改表,添加列
alter table aaa add sex varchar(1);


-- 更改表,刪除列
alter table aaa drop column sex;

-- 去掉參數先後的空格
rtrim(dm_hy.mc);


-- 定義臨時表,經過已有person表來建立
declare global temporary table gbl_temp
like person
on commit delete rows --提交時刪除數據
not logged -- 不在日誌中紀錄
in usr_tbsp -- 選用表空間
-- 此語句建立一個名爲 gbl_temp 的用戶臨時表。定義此用戶臨時表 所使用的列的名稱和說明與 person 的列的名稱和說明徹底相同。

-- 建立有兩個字段的臨時表  
     -- 定義一個全局臨時表tmp_hy
declare global temporary table session.tmp_hy
     (
        dm varchar(10),
        mc varchar(10)         
     )
      with replace -- 若是存在此臨時表,則替換
      not logged;   -- 不在日誌裏紀錄

     -- 給臨時表插入三條數據
     insert into session.tmp_hy values('1','1');
     insert into session.tmp_hy values('1','1');
     insert into session.tmp_hy values('1','1');

-- 經過查詢批量插入數據

inster into tab_bk(select code,name from table book);

-- select ... into的用法

select * into :h1, :h2, :h3, :h4
      from emp
      where empno = '528671';


-- 語句的流程控制

if() then
open cur1
fetch cur1 into t_equipid;
while(at_end<>1)do
   ......
set t_temp=0;                                                            
end while;
close cur1;
else
......
end if;


-- 外鏈接

select empno,deptname,projname
   from (emplyoee
   left outer join project
   on respemp=empon)
   left outer join department
   on mgrno=empno;


-- in、like、order by(... ASC|DESC)的用法
select * from book t
where t.name like '%J_編程%'
and t.code in('J565333','J565222');

order by t.name asc


-- 彙總表(概念複雜,難以理解,不經常使用)

create summary table sumy_stable1
   as (select workdept,
     count(*) as reccount,
     sum(salary) as salary,
     sum(bonus) as bonus
   from employee group by workdept)
data initially deferred
refresh immediate;


-- 使用SQL一次處理一個集合語義
-- (優化前) select語句中每行的過程層和數據流層之間都有一個上下文切換
declare cur1 cursor for col1,col2 from tab_comp;
open cur1;
fetch cur1 into v1,v2;
while SQLCODE<> 100 do
if (v1>20) then
   insert into tab_sel values(20,v1);
else
   insert into tab_sel values(v1,v2);
end if;
fetch cur1 into v1,v2;
end while;

-- (優化後)沒有過程層和數據流層之間的上下文切換
declare cur1 cursor for col1,col2 from tab_comp;
open cur1;
fetch cur1 into v1,v2;
while SQLCODE<> 100 do
insert into tab_sel(select (case
          when col1>20 then 20
             else col1
         end),
         col2
       from tab_comp);
fetch cur1 into v1,v2;
end while;


-- DB2函數分三類:列函數、標量函數、表函數
-- 列函數輸入一組數據,輸出單一結果。
-- 標量函數接收一個值,返回另一個值。
-- 表函數只能用於SQL語句的from字句中,它返回一個表的列,相似於一個已建立的常規表。


-- 下面是個標量函數的例子。
create function (salary int,bonus_percent int)
returns int
language SQL contains SQL
return(
salary * bonus_percent/100
)


-- 下面是表函數
create function get_marks(begin_range int,end_range int)
returns table(cid candidate_id,
        number test_id,
        score score)
language SQL reads SQL DATA
return
     select cid,number,score
     from test_taken
     where salary between (begin_range) and score(end_range)

example 1: define a scalar function that returns the tangent of a value using the existing sine and cosine functions.

    create function tan (x double)
      returns double
      language sql
      contains sql
      no external action
      deterministic
      return sin(x)/cos(x)               

example 2: define a transform function for the structured type person.

     
    create function fromperson (p person)
      returns row (name varchar(10), firstname varchar(10))
      language sql
      contains sql
      no external action
      deterministic
      return values (p..name, p..firstname)

example 3: define a table function that returns the employees in a specified department number.

     
    create function deptemployees (deptno char(3))
      returns table (empno char(6),
                     lastname varchar(15),
                     firstname varchar(12))
      language sql
      reads sql data
      no external action
      deterministic
      return
        select empno, lastname, firstnme
          from employee
          where employee.workdept = deptemployees.deptno

example 4: define a scalar function that reverses a string.

    create function reverse(instr varchar(4000))
      returns varchar(4000)
      deterministic no external action contains sql
      begin atomic
      declare revstr, reststr varchar(4000) default '';
      declare len int;
      if instr is null then
      return null;
      end if;
      set (reststr, len) = (instr, length(instr));
      while len > 0 do
      set (revstr, reststr, len)
        = (substr(reststr, 1, 1) concat revstr,
        substr(reststr, 2, len - 1),
        len - 1);
      end while;
      return revstr;
    end

example 4: define the table function from example 4 with auditing.

    create function deptemployees (deptno char(3))
      returns table (empno char(6),
                     lastname varchar(15),
                     firstname varchar(12))
      language sql
      modifies sql data
      no external action
      deterministic
      begin atomic
        insert into audit
        values (user,
                'table: employee prd: deptno = ' concat deptno);
        return
          select empno, lastname, firstnme
            from employee
            where employee.workdept = deptemployees.deptno
      end


-- for循環語句的用法

begin atomic
declare fullname char(40);
for vl as
    select firstnme, midinit, lastname from employee
   do
   set fullname = lastname concat ','
     concat firstnme concat ' ' concat midinit;
   insert into tnames values (fullname);
end for
end


-- leave的用法

create procedure leave_loop(out counter integer)
language sql
begin
    declare v_counter integer;
    declare v_firstnme varchar(12);
    declare v_midinit char(1);
    declare v_lastname varchar(15);
    declare at_end smallint default 0;
    declare not_found condition for sqlstate '02000';
    declare c1 cursor for
   select firstnme, midinit, lastname
     from employee;
    declare continue handler for not_found
   set at_end = 1;
    set v_counter = 0;
    open c1;
    fetch_loop:
    loop
   fetch c1 into v_firstnme, v_midinit, v_lastname;
   if at_end <> 0 then leave fetch_loop;
   end if;
   set v_counter = v_counter + 1;
    end loop fetch_loop;
    set counter = v_counter;
    close c1;
end

-- if語句的用法

    create procedure update_salary_if
      (in employee_number char(6), inout rating smallint)
      language sql
      begin
        declare not_found condition for sqlstate '02000';
        declare exit handler for not_found
          set rating = -1;
        if rating = 1
          then update employee
          set salary = salary * 1.10, bonus = 1000
          where empno = employee_number;
        elseif rating = 2
          then update employee
          set salary = salary * 1.05, bonus = 500
          where empno = employee_number;
        else update employee
          set salary = salary * 1.03, bonus = 0
          where empno = employee_number;
        end if;
      end


-- loop的用法

    create procedure loop_until_space(out counter integer)
      language sql
      begin
        declare v_counter integer default 0;
        declare v_firstnme varchar(12);
        declare v_midinit char(1);
        declare v_lastname varchar(15);
        declare c1 cursor for
          select firstnme, midinit, lastname
            from employee;
        declare continue handler for not found
          set counter = -1;
        open c1;
        fetch_loop:
        loop
          fetch c1 into v_firstnme, v_midinit, v_lastname;
          if v_midinit = ' ' then
            leave fetch_loop;
          end if;
          set v_counter = v_counter + 1;
        end loop fetch_loop;
        set counter = v_counter;
        close c1;
      end


-- return的用法

    begin    ...      goto fail    ...      success: return 0      fail: return -200    end

相關文章
相關標籤/搜索