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)
1. 建立数据库DB2_GCB
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 8301206
3. 建立别名
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;
4. 建立表
create table zjt_tables as
(select * from tables) definition only;
create table zjt_views as
(select * from views) definition only;
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;
-- 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;
union all
values 45;
union all
values 7,8,9,10,11,12
order by 1;
select distinct 234 from AnyOneTable;
select distinct 234 as 1 from AnyOneTable;
select distinct 'DB2变态级的SQL哈哈' from AnyOneTable;
select distinct 'DB2变态级的SQL哈哈' as 1 from AnyOneTable;
-- 定义变量,还可以设定默认值,给变量赋值
declare var1 char(2);
declare var2 int default 0;
set var2 =23;
--创建一个动态游标变量
declare d_cur integer;
-- 给变量赋值的另一种方法
values expr1, expr2, expr3 into a, b, c;
-- 相当于
set a = expr1;
set b = expr2;
set c = expr3;
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');
from emp
where empno = '528671';
-- 语句的流程控制
open cur1
fetch cur1 into t_equipid;
while(at_end<>1)do
......
set t_temp=0;
end while;
close cur1;
else
......
end if;
-- 外连接
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');
-- 汇总表(概念复杂,难以理解,不常用)
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)
returns double
language sql
contains sql
no external action
deterministic
return sin(x)/cos(x)
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)
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
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
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循环语句的用法
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的用法
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
(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的用法
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的用法
...
goto fail
...
success: return 0
fail: return -200
end