答案取决于索引是创建主键时自动创建的,还是创建主键前手工创建的。
测试如下:--建表create
table
hqy_test(id
integer)
--建索引create
(unique)index
idx_hqy_id
on
hqy_test(id)
--加主键alter
table
hqy_test
add
constraint
pk_hqy_id
primary
key
(id)
select
index_name
from
user_indexes
where
index_name='IDX_HQY_ID'IDX_HQY_ID
---删除主键
alter
table
hqy_test
drop
constraint
pk_hqy_id或者:alter
table
hqy_test
drop
primary
key
也是行的。
select
index_name
from
user_indexes
where
index_name='IDX_HQY_ID'
IDX_HQY_ID
==没有删除索引
--删除索引,增加主键并自动创建索引
drop
index
idx_hqy_id
alter
talbe
hqy_test
add
constraint
pk_hqy_id
primary
key(id)
using
index
select
index_name
from
user_indexes
where
index_name='PK_HQY_ID'
PK_HQY_ID
==自动创建了索引
--删除主键约束
alter
table
hqy_test
drop
primary
key
select
index_name
from
user_indexes
where
index_name='PK_HQY_ID'
无
==索引被删除了
如果删除主键时,希望同时删掉索引,则应该增加drop
index选项,从而不管索引是否是创建主键时自动创建的,即:alter
table
hqy_test
drop
primary
key
drop
index
这是数据库主键自增的固然性质所决定的,数据删除后,主键还是会继续增加的,即主键使用过一次将不会再次使用。
例如:这个表中有10条数据,主键为1-10不间断的数字,那删除第十条数据,继续插入的话,id则会变成11,而不是10。通俗的说就是主键使用过一次将不会再次使用。
每次插入则不需要为主键设置参数,数据库会根据设置的递增条件,自动给出主键值。则第一次插入后主键为1,第二次为2,依次递增。
扩展资料:
Mysql、SqlServer主键自动增长的设置方法:
1、在mysql中把主键定义为自动增长标识符类型
如果把表的主键设为auto_increment类型,数据库就会自动为主键赋值。例如:
createtablecustomers(idintauto_incrementprimarykeynotnull,namevarchar(15))insertintocustomers(name)values("name1"),("name2")
2、在MSSQLServer中,如果把表的主键设为identity类型,数据库就会自动为主键赋值。例如:
createtablecustomers(idintidentity(1,1)primarykeynotnull,namevarchar(15))insertintocustomers(name)values("name1"),("name2")identity包含两个参数,第一个参数表示起始值,第二个参数表示增量。
参考资料来源:百度百科-主键约束
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)