db2 sql 语句

 

weiruan85

db2 常用 语句

将某个表导出为IXF档:

Sql代码
CONNECT TO CSI;  
EXPORT TO "C:\T_R_FORM.ixf" OF IXF MESSAGES "aa" SELECT * FROM CSIDDBD3.T_REFERRAL_FORM;  
CONNECT RESET;  
 
CONNECT TO CSI;  
EXPORT TO "C:\T_R_FORM_FLAG.ixf" OF IXF MESSAGES "bb"   
SELECT * FROM CSIDDBD3.T_REFERRAL_FORM_FLAG;  
CONNECT RESET; 

CONNECT TO CSI;
EXPORT TO "C:\T_R_FORM.ixf" OF IXF MESSAGES "aa" SELECT * FROM CSIDDBD3.T_REFERRAL_FORM;
CONNECT RESET;

CONNECT TO CSI;
EXPORT TO "C:\T_R_FORM_FLAG.ixf" OF IXF MESSAGES "bb"
SELECT * FROM CSIDDBD3.T_REFERRAL_FORM_FLAG;
CONNECT RESET;

2、日期类型(Date)作为查询条件:

Sql代码
SELECT * FROM CSIDDBD3.T_ID_MSGPOP WHERE BEG_DATE > '2007-01-01'; 

SELECT * FROM CSIDDBD3.T_ID_MSGPOP WHERE BEG_DATE > '2007-01-01';

3、时间类型(TimeStamp)作为查询条件:

Sql代码
SELECT * FROM CSIDDBD3.T_ID_MSGPOP WHERE INPUT_DATE > '2007-01-01 00:00:00'; 

SELECT * FROM CSIDDBD3.T_ID_MSGPOP WHERE INPUT_DATE > '2007-01-01 00:00:00';

4、取前N条记录

Sql代码
SELECT * FROM CSIDDBD3.T_ID_MSGPOP FETCH FIRST 1000 ROWS ONLY; 

SELECT * FROM CSIDDBD3.T_ID_MSGPOP FETCH FIRST 1000 ROWS ONLY;

5、如何利用表的NOT LOGGED INITIALLY特性清空表中的数据

Sql代码
alter  table table_name activate not logged initially with empty table  

alter  table table_name activate not logged initially with empty table 参考资料



6、批量更新某一查询结果集的第N条到第M条的记录的SQL(DB2)

Sql代码
update tableName b  
set b.A=2 ,b.B=current date  --B字段为日期类型  
where exists (  
   select 1 from (  
      select a.id,row_number()over(order by a.id) req --以tableName表的主键id字段进行排序  
         from tableName a where a.C =22 and a.D=1) c --加上查询结果集的限制条件  
  where b.id=c.id and c.req>=1 and c.req<=3);--将要更新查询结果集的第1到第3条记录 

update tableName b
set b.A=2 ,b.B=current date  --B字段为日期类型
where exists (
   select 1 from (
      select a.id,row_number()over(order by a.id) req --以tableName表的主键id字段进行排序
         from tableName a where a.C =22 and a.D=1) c --加上查询结果集的限制条件
  where b.id=c.id and c.req>=1 and c.req<=3);--将要更新查询结果集的第1到第3条记录

7、DB2 如何设置最大连接数?

Sql代码
db2 connect to dbname user username  using  passwd  
db2 update db cfg using MAXAPPLS  number 

db2 connect to dbname user username  using  passwd
db2 update db cfg using MAXAPPLS  number 
8、SUBSTR()函数的使用

函数原型:

Sql代码
SUBSTR(string-expression,start,length) 

SUBSTR(string-expression,start,length)【 示例】Sample table DSN8810.PROJ contains column PROJNAME, which is defined as VARCHAR(24). Select all rows from that table for which the string in PROJNAME begins with 'W L PROGRAM '.

Sql代码
SELECT * FROM DSN8810.PROJ WHERE SUBSTR(PROJNAME,1,12) = 'W L PROGRAM '; 

SELECT * FROM DSN8810.PROJ WHERE SUBSTR(PROJNAME,1,12) = 'W L PROGRAM ';

【示例2】DB2函数substr分析

错误SQL:

Java代码
select pk_invcl from bd_invcl   
where length (invclasscode) <= length ('501')   
and substr ('501', 1, length (invclasscode)) = invclasscode   
order by invclasscode 

select pk_invcl from bd_invcl
where length (invclasscode) <= length ('501')
and substr ('501', 1, length (invclasscode)) = invclasscode
order by invclasscode

错误日志:

Xml代码
2007-01-18 19:10:13 SO|java.sql.SQLException: [IBM][CLI Driver][DB2/AIX64] SQL0138N   
The second or third argument of the SUBSTR function is out of range. SQLSTATE=22011 

2007-01-18 19:10:13 SO|java.sql.SQLException: [IBM][CLI Driver][DB2/AIX64] SQL0138N
The second or third argument of the SUBSTR function is out of range. SQLSTATE=22011

分析:虽然第一个条件已经限制length (invclasscode) <= length ('501') ,但是不满足第一个条件时,DB2第二个条件还会执行。
但是以下SQL却可以执行,并且以下两个SQL返回结果相同

Sql代码
select count(*) from bd_invcl   
where substr (invclasscode, 1,length(invclasscode)+2) = invclasscode  
select count(*) from bd_invcl 

select count(*) from bd_invcl
where substr (invclasscode, 1,length(invclasscode)+2) = invclasscode
select count(*) from bd_invcl

修正后:

Sql代码
select pk_invcl from bd_invcl   
where length (invclasscode) < length ('501')   
and substr ('501', 1,   case   
                  when length (invclasscode)>length ('501')   
                  then length ('501')   
                  else length (invclasscode) end   )   
= invclasscode order by invclasscode 

select pk_invcl from bd_invcl
where length (invclasscode) < length ('501')
and substr ('501', 1,   case
                  when length (invclasscode)>length ('501')
                  then length ('501')
                  else length (invclasscode) end   )
= invclasscode order by invclasscode 
9、自动增长列

    A、包含生成列的 DB2 表上的数据移入和移出 — 入门

    B、在 DB2 通用数据库中自动生成数值序列

    C、DB2自动增长主键的方法。

    D、急,DB2 9中自动增长列如何返回(在线等)



《Understanding DB2® Learning Visually with Examples》



7.8.6. Identity Columns
An identity column is a numeric column in a table that automatically generates a unique numeric value in sequence for each row inserted. A unique identifier is often used in applications to identify a specific row. Unlike sequence objects, which we discuss in section 7.16 , Sequences, identity columns are bound to the table they are defined on. There can be only one identity column per table. DB2 can generate the identity column values in two ways.

Generated always : The values are always generated by DB2. Applications are not allowed to provide an explicit value.

Generated by default : The values can be explicitly provided by an application; if no value is given, DB2 generates one. In this case, however, DB2 cannot guarantee the uniqueness of the value generated.

To create an identity column, use the CREATE TABLE statement with the GENERATED clause and make sure it contains the IDENTITY keyword because GENERATED can also be used to generate other values automatically that are not identity columns. Here is an example.

Sql代码
CREATE TABLE product (  
       productno   INTEGER GENERATED ALWAYS AS 
                           IDENTITY (START WITH 200 INCREMENT BY 1),  
       description VARCHAR(50) )  

CREATE TABLE product (
       productno   INTEGER GENERATED ALWAYS AS
                           IDENTITY (START WITH 200 INCREMENT BY 1),
       description VARCHAR(50) ) 

The column productno is an INTEGER defined as an identity column that is always generated. The value generated will start from 200, and it will be incremented by 1. Let's perform a few INSERT statements and see the results obtained.


INSERT INTO product VALUES (DEFAULT,'banana');         --->inserts 200,banana
INSERT INTO product (description) VALUES ('apple');    --->inserts 201,apple
INSERT INTO product VALUES (300,'pear');               --->error SQL0798N
COMMIT;

INSERT INTO product (description) VALUES ('orange');   --->inserts 202,orange
ROLLBACK;

INSERT INTO product (description) VALUES ('plum');     --->inserts 203,plum
COMMIT ;

The following query shows the final result.

Sql代码
SELECT * FROM product;  
 
PRODUCTNO   DESCRIPTION  
----------- ------------  
        200 banana  
        201 apple  
        203 plum 

SELECT * FROM product;

PRODUCTNO   DESCRIPTION
----------- ------------
        200 banana
        201 apple
        203 plum

The first two INSERT statements show that two identity column values were generated: 200 and 201. The third INSERT statement returns an error because you cannot explicitly insert a value for an identity column generated as ALWAYS . After the third INSERT statement, we issue a COMMIT to guarantee these rows are stored in the database. The fourth INSERT statement causes another identity column value, 202, to be generated; however, we issue a ROLLBACK statement right after, so this row is not stored in the database. Note that the final INSERT statement, which inserts the product plum, generates a value of 203, not 202. (COMMIT and ROLLBACK statements are explained in more detail in Chapter 13 , Developing Database Backup and Recovery Solutions.)



NOTE

An identity column value is generated only once. Once the value has been generated, even if a ROLLBACK statement is performed, it will not be generated again.



Now let's review another example, this time creating the same table product with the GENERATED BY DEFAULT clause.

Sql代码
CREATE TABLE product (  
       productno   INTEGER GENERATED BY DEFAULT AS 
                           IDENTITY (START WITH 200 INCREMENT BY 1),  
       description VARCHAR(50) ) 

CREATE TABLE product (
       productno   INTEGER GENERATED BY DEFAULT AS
                           IDENTITY (START WITH 200 INCREMENT BY 1),
       description VARCHAR(50) ) 
Next, we insert a few rows.

Sql代码
INSERT INTO product VALUES (DEFAULT,'banana');         --->inserts 200,banana  
INSERT INTO product (description) VALUES ('apple');    --->inserts 201,apple  
INSERT INTO product VALUES (300,'pear');               --->inserts 300,pear  
INSERT INTO product VALUES (201,'orange');             --->inserts 201,orange  
COMMIT;  
INSERT INTO product (description) VALUES ('papaya');   --->inserts 202,papaya  
ROLLBACK;  
INSERT INTO product (description) VALUES ('plum');      --->inserts 203,plum  
COMMIT;  

INSERT INTO product VALUES (DEFAULT,'banana');         --->inserts 200,banana
INSERT INTO product (description) VALUES ('apple');    --->inserts 201,apple
INSERT INTO product VALUES (300,'pear');               --->inserts 300,pear
INSERT INTO product VALUES (201,'orange');             --->inserts 201,orange
COMMIT;
INSERT INTO product (description) VALUES ('papaya');   --->inserts 202,papaya
ROLLBACK;
INSERT INTO product (description) VALUES ('plum');      --->inserts 203,plum
COMMIT; 


The following query shows the final result.

Sql代码
SELECT * FROM product  
 
PRODUCTNO   DESCRIPTION  
----------- ---------------------  
        200 banana  
        201 apple  
        300 pear  
        201 orange  
        203 plum 

SELECT * FROM product

PRODUCTNO   DESCRIPTION
----------- ---------------------
        200 banana
        201 apple
        300 pear
        201 orange
        203 plum

The first two INSERT statements show that two identity column values were generated: 200 and 201. For the third and fourth INSERT statements, we explicitly provided the values 300 and 201, respectively, for the identity column. Note that DB2 did not return an error as in the previous example because we defined the identity column as GENERATED BY DEFAULT . After the fourth INSERT statement, we issue a COMMIT to guarantee these rows are stored in the database. The fifth INSERT statement causes another identity column value, 202, to be generated; however, we issue a ROLLBACK statement right after, so this row is not stored in the database. Note that the final INSERT statement, which inserts the product plum, generates a value of 203, not 202.

The following final example illustrates a GENERATED value, which is not an identity column. The example uses GENERATED ALWAYS , but you can also use GENERATED BY DEFAULT .

Sql代码
CREATE TABLE income (  
empno     INTEGER,  
salary    INTEGER,  
taxRate   DECIMAL(5,2),  
netSalary DECIMAL(7,2) GENERATED ALWAYS AS (salary * (1 - taxRate))  


CREATE TABLE income (
empno     INTEGER,
salary    INTEGER,
taxRate   DECIMAL(5,2),
netSalary DECIMAL(7,2) GENERATED ALWAYS AS (salary * (1 - taxRate))

If you insert the following row:

Sql代码
INSERT INTO income (empno, salary, taxRate) VALUES (111, 50000, 0.3)  

INSERT INTO income (empno, salary, taxRate) VALUES (111, 50000, 0.3) 

The result is:

Sql代码
EMPNO       SALARY      TAXRATE NETSALARY  
----------- ----------- ------- ---------  
        111       50000    0.30  35000.00 

EMPNO       SALARY      TAXRATE NETSALARY
----------- ----------- ------- ---------
        111       50000    0.30  35000.00

DB2 generates the value of the last column NETSALARY based on the SALARY and TAXRATE columns

 

 

关于Java连接db2 的问题

这个问题比较多,等我闲了再好好总结一下。

//驱动的问题
    Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:db2://133.64.37.1:50000/CHURNDB", "test", "test");


DB2有几种jdbc驱动,jdbc-url分别如下:
jdbc:db2:localhost:db2test                              COM.ibm.db2.jdbc.net.DB2Driver         type3  db2java.zip
jdbc:db2:db2test                                                COM.ibm.db2.jdbc.app.DB2Driver        type2  db2java.zip
jdbc:db2://localhost:50000/db2test               com.ibm.db2.jcc.DB2Driver                     type4 db2jcc.jar

另外用type4时 数据库必须将codeset设置成utf-8
否则查询时会抛出com.ibm.db2.jcc.b.DisconnectException: encoding not supported!!异常

今天犯了错误,弄混了写法,希望没人再犯同样的错。
我的版本是 udb8.1。



----------------------------------------------------------------------

/**了解基础情况**/
对于Java程序员而言,DB2 提供了两种应用程序编程接口(API):JDBC 和 SQLJ。

JDBC:
  JDBC 驱动程序分为旧的/CLI 驱动程序<db2java.zip>和新的通用 JDBC 驱动程序(Universal JDBC Driver)<db2jcc.jar>。
  JDBC 是一个与供应商无关的动态 SQL 接口,该接口通过标准化的 Java 方法向您的应用程序提供数据访问。
  JDBC 类似于 DB2 CLI,因为您无须预编译应用程序代码,也无须将软件包绑定到 DB2 数据库。
  作为一个与供应商无关的标准,JDBC 应用程序提供了更多的可移植性—这是当今异构业务基础设施所必需的优点。
  在执行 JDBC 应用程序期间,驱动程序将针对当前连接的 DB2 数据库服务器验证 SQL 语句。
  访问期间的任何问题都会作为 Java 异常与相应的 SQLSTATE 和 SQLCODE 一起报告给应用程序。
SQLJ:
  SQLJ 是一个用于从 Java 应用程序进行数据访问的标准开发模型。
  SQLJ API 是在 SQL 1999 规范中定义的。
 
新的通用 JDBC 驱动程序在一个实现中同时为 JDBC 和 SQLJ API 提供了支持。
JDBC 和 SQLJ 可以在同一个应用程序中互操作。
SQLJ 提供了独特的使用静态 SQL 语句进行开发以及在 DB2 包级别控制访问的能力。

/**JDBC连接方式分析**/
JDBC 驱动程序体系结构分为四种类型:Type1,Type2,Type3,Type4。

Type1:
  驱动程序基于 JDBC-ODBC 桥。
  因此 ODBC 驱动程序可以与此类 JDBC 驱动程序(由 Sun 提供)结合起来使用。
  IBM 不支持 Type 1 驱动程序,因此它不是推荐的环境。


Type2:
   驱动程序依靠特定于操作系统的库(共享库)来与 RDBMS 通信。
   应用程序将装入这种 JDBC 驱动程序,而驱动程序将使用共享库来与 DB2 服务器通信。
   DB2 UDB for Linux, UNIX和 WindowsV8.1 提供了两种不同的 Type 2 驱动程序:
   <1> 旧的/CLI JDBC 驱动程序在文件db2java.zip中提供。
     其实现包名称为COM.ibm.db2.jdbc.app.DB2Driver。
     该驱动程序目前已被用于进行 J2EE 认证。
     其别名“app 驱动程序”源自于一种观念及其包名称,
     这种观念就是:此驱动程序将通过远程数据库的本地 DB2 UDB 客户机执行本地连接。
   <2> 通用 JDBC 驱动程序在文件db2jcc.jar中提供。
     其实现包名称为com.ibm.db2.jcc.DB2Driver。
     此驱动程序是 DB2 UDB for Linux, UNIX 和 Windows V8.1 中的新功能。
     在最初的实现(V8.1)中,此驱动程序用于使用 Type 4 驱动程序体系结构与 DB2 服务器进行直接的 Java 连接。
     在 DB2 V8.1.2 中,您可以在 Type 2 体系结构中使用此驱动程序。
     在 Type 2 体系结构中使用此驱动程序的一个主要原因是为了本地应用程序性能和分布式事务支持。
     通用 JDBC Type 2 驱动程序分别使用com.ibm.db2.jcc.DB2XADataSource和com.ibm.db2.jcc.DB2ConnectionPoolDataSource来支持分布式事务和连接池。

  注:在将来的版本中不会对旧的/CLI Type 2 驱动程序进行增强。


Type3:
   驱动程序是一种纯 Java 实现,它必须与 DB2 JDBC Applet 服务器(DB2 JDBC Applet Server)通信才能访问 DB2 数据。
   此类驱动程序旨在使 Java applet 能访问 DB2 数据源。
   常被称作“网络(net)驱动程序”,它是根据其包名COM.ibm.db2.jdbc.net命名的。DB2 V8.1 支持网络驱动程序,可以将其用于 JDBC 应用程序。
   要求db2java.zip驱动程序总是处于与 DB2 Applet 服务器相同的维护级别。
   如果驱动程序在 applet 内使用,这就不是一个问题,因为浏览器会在应用程序执行期间下载相应的db2java.zip文件。
   许多客户使用 Type3 驱动程序而不是 Type2 驱动程序,以避免必需的 DB2 客户机安装和必需的DB2 CATALOG DATABASE命令,后者用于创建使用旧的/CLI 驱动程序进行 Type 2 连接所必需的数据库目录信息。
   目前,WebSphere Application Server 和其它 J2EE 服务器不支持 IBM Type 3 驱动程序,因为该驱动程序不支持分布式事务(JTA)。
   将来的版本不会对 Type 3 驱动程序进行增强。

   鼓励使用通用 JDBC Type 4 驱动程序来替代 Type 3 驱动程序。


Type4:
  驱动程序是仅用于 Java 的 JDBC 驱动程序,它直接连接到数据库服务器。
  DB2 UDB for Linux, UNIX 和 Windows V8.1 引入了称为“通用 JDBC 驱动程序(Universal JDBC driver)”的 Type 4 驱动程序。
  通用 JDBC 驱动程序在文件db2jcc.jar中提供。
  其实现包名为com.ibm.db2.jcc.DB2Driver。
  请注意,通用 Type 2 和通用 Type 4 驱动程序具有相同的实现类名称。
  有两种方法可以区别 DB2 在内部将实例化哪个驱动程序:
  使用连接特性来确定连接是否使用共享库(Type2),或者驱动程序是否会启动来自 Java 应用程序的直接连接(Type4)。


重要:就 DB2 UDB V8.1.2 而言,通用 JDBC 驱动程序要求 CLASSPATH 中有许可证 JAR 文件和db2jcc.jar文件。
以下是所需的许可证 JAR 文件:
  Cloudscape Network Server V5.1:db2jcc_license_c.jar
  DB2 UDB V8 for Linux, UNIX 和 Windows 服务器:db2jcc_license_su.jar
  DB2 UDB for iSeries and z/OS 服务器(与 DB2 Connect 和 DB2 Enterprise Server Edition 一起提供):db2jcc_license_cisuz.jar



驱动程序类型:db2java.zip, db2jcc.jar
注意:假如你使用db2java.zip,且web服务器使用Tomcat的话,请将db2java.zip改名为db2java.jar,最好将zip解压再用jar命令打包,直接改文件类型也行(呵呵,按照jar文件严格意义上来讲这是不符合文法的<少了描述性文件:MANIFEST.MF>,能用就行)
   还有一般情况下:就是使用 db2java.zip的话需要安装db2客户端, 使用db2jcc.jar是通过网络直接来连接的无需安装db2客户端(假如用在type2上还是要装客户端的)

type2:
使用<db2java.zip>:
  jdbc.driverClassName=COM.ibm.db2.jdbc.app.DB2Driver
    jdbc.url=jdbc:db2:dataBaseName
   

   假如你的工具使用的是myeclipse且使用的是tomcat plugin的话,请将db2jdbc.dll 拷贝到 %JAVA_HOME%/bin下,否则不行地啦
   <是不是其他类型的使用db2java.zip驱动也有这个问题呢,不知道,没试过,有空试一下>
  
  使用<db2jcc.jar>:
   jdbc.driverClassName=com.ibm.db2.jcc.DB2Driver
   jdbc.url=jdbc:db2:dataBaseName
 
type3:
驱动:db2java.zip
jdbc.driverClassName=COM.ibm.db2.jdbc.net.DB2Driver
  jdbc.url=jdbc:db2://ip:6789/DBNAME
  注意:要在数据库上执行 db2jstrt 6789 (这句启动了db2jd进程,6789是默认的服务器侦听jdbc2连接的端口,也可以设置成另外的任意不冲突的端口。)
 
type4:
驱动:db2jcc.jar
数据库字符集必须设置为utf-8
  jdbc.driverClassName=com.ibm.db2.jcc.DB2Driver
  jdbc.url=jdbc:db2://ip:port/DBNAME

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值