DB2 自动递增字段实现方法
http://www.zftb.cn  发布时间:2015-03-03 11:06 来源:未知 浏览:加载中次

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的文档里都有具体说明。
如果你有好的win10资讯或者win10教程,以及win10相关的问题想要获得win10系统下载的关注与报道。
欢迎加入发送邮件到657025171#qq.com(#替换为@)。期待你的好消息!