DB2 自动递增字段实现方法
https://www.yqxbc.com win10系统 发布时间:2015-03-03 00:00 来源:未知 浏览:加载中

DB2提供了当有一行插入的时候自动在某一列添加值的功能,可以使用所谓identity rules,简单点的比如某个数值的递增填入该列中,当然也有很复杂的。

使用这个一般是用作识别码的,当做定义表格的主键。generated语法则可以自定义你想怎么产生这个值的策略。 

语法如下: 
column definition generated {always | by default} 
as {identity identity rules | using your rules} 
我们先删掉上次我们建立的表格: 
db2 => drop table nomination 
然后再创建一个表格: 
代码如下:

Create table nomination 

nominationID BIGINT Not Null Primary Key generated always as identity, 
nominee char(6) Not Null, 
nominator char(6) Not Null, 
reason VARCHAR(250), 
nomdate date Not Null, 
categoryid INTEGER Not Null, 
check (nominee != nominator) not enforced enable query optimization, 
Foreign Key CategoryExists (categoryid) 
references category (categoryid) on delete restrict 

注意黑体字,以后我们就不能使用insert或者update来显式的指定它的值了。 
而DB2中的identity也提供了多种策略,具体的可以去查DB2手册,我们举例如下: 
我们先删掉上次我们建立的表格: 
db2 => drop table category 
然后建立表单 
代码如下:

Create table category 

CategoryID INTEGER Primary Key Generated Always as Identity 
(Start With 1 Increment by 1 minvalue 0 maxvalue 999999999 
no cycle cache 5 no order), 
CateogryName VARCHAR(50) Not Null, 
Eligibility VARCHAR(250) 

黑体字中identity中的语句你都能在DB2的手册中查到,都是自然语言一看就懂了。 
有时候你并不只想去做数字的填充,你可能还想处理一些字母,那么下边这个转换大写的例子就是给你的: 
db2 => alter table category add column 
UpperCatName VARCHAR(50) generated always as (upper(CategoryName)) 
关于这些在DB2的文档里都有具体说明。