db2 自增长列测试
1当想将表中一列修改为自动增长时,可用下面命令:
alter table
alter column set not null
alter table alter column set generated always as identity (start with 1,increment by 1)
上面命令是在改一表中列的属性时,在网上找到的很有用。2当修改表中一列自动增长的开始值时,可用下面的命令:
alter table alter column restart with 18;
测试:
create table customer_orders_t (
order_id int not null generated always as identity
(start with 1
increment by 1
minvalue 1
no maxvalue
no cycle
no cache
order),
order_date date not null,
cust_id int not null,
product_id int not null,
quantity int not null,
price decimal(10,2) not null,
status char(9) not null,
primary key (order_date, order_id))
注:该列中的以及它本身的 identity 属性并没有保证所生成的序列值是唯一的。
但是, primary key 约束保证了表中行的唯一性。
为了确保只将自动生成的值插入标识列,他们指定了 generated always 子句。
使用最后一个生成的 order_id 来确定多少数据
选项 no cache 和 order 确保了在系统故障的情况下,不废弃未使用的标识值。
测试1
插入数据
insert into customer_orders_t values (default,current date,12,12,12,10.2,'2')
--成功
insert into customer_orders_t values (1,current date,12,12,12,10.2,'2')
-- 报错 因为:identity字段不允许指定值
--解决方案
alter table customer_orders_t
alter column order_id
set generated by default
--创建orders_seq对象
create sequence orders_seq
as int
start with 1
increment by 1
minvalue 1
no maxvalue
no cycle
no cache
order
--插入数据
insert into customer_orders_t values (next value for orders_seq, current date,12,12,12,10.2,'2')
1、命令行取sequence soc.nico_qian的下一个值:
db2 values next value for soc.nico_qian
2、命令行重置sequence soc.nico_qian:
db2 alter sequence soc.nico_qian restart,重置后的值默认为创建sequence时的minvalue
3、命令行以指定值22重置sequence soc.nico_qian:
db2 alter sequence soc.nico_qian restart with 22
4、命令行重置表ks.check_condition的identity字段初始值为20:
db2 alter table ks.check_condition alter column identity_column_name restart with 20
5、如果sequence被以命令行的方式重置,那么用到这个sequence的嵌入式c程序代码的绑定包
的valid字段会被修改为n,那么在下一次这个代码被调用的时候,db2会自动重新绑定
此代码的绑定包,,这个动作会给应用程序带来不可预知的后果,比如:如果这段代码是在很
频繁的被用到的时间段内被重新绑定,那么极易造成死锁。
同样的问题会出现在identity字段上。
