数据库oracle

--建表
create table test(
name varchar2(20));
--测试数据
insert into test values('name1');
insert into test values('name2');
insert into test values('name3');
--加列
alter table test add id integer;
--创建含主键表,用于更新
create table temprt(
rd varchar2(18) primary key,
id int
);
--将目的表的值插入到创建的表
insert into temprt select rowid,rownum from test;
--更新列值
update (select A.id Aid,A.rowid Ard,B.rd,B.id Bid from test A,temprt B where A.rowid=B.rd)
set Aid=Bid;
--设置不空
alter table test modify id int not null;
--设置主键
alter table test add constraint pk_test primary key(id);


image.png

①.添加主键
一.建表前添加主键
1.表创建的同时,添加主键约束
语法:
create table "表名"
(
"列名1" 数据类型及长度 constraint "主键名称"(一般主键名称为”PK_”开头) primary key,
"列名2" 数据类型及长度 not null,——-not null 约束该列不为空,不写表示可以为空
"列名3" 数据类型及长度
)

例:
create table "Meeting"
("name" VARCHAR2(20) constraint "pk_name" primary key,
"RoomNum" VARCHAR2(20) not null,
"username" VARCHAR2(50)
)

复合主键
create table "Meeting"
("name" VARCHAR2(20) ,
"RoomNum" VARCHAR2(20) not null,
"username" VARCHAR2(50)
constraint "pk_name" primary key(name,RoomNum)
)

————注意————-
CREATE TABLE T_cardInfo –银行卡信息表
(
cardID varchar2(19) primary key,
—— 未命名主键
);

二.表创建后,添加主键约束
语法:
alter table "表名"
add constraint "主键名称"(一般主键名称为”PK_”开头) primary key(要设为主键的列名);
例:
alter table "Meeting"
add constraint "pk_name" primary key ("name");

②.删除主键
1.alter table "表名" drop constraint "主键名"
2.alter table "表名" drop primary key
如果主键未命名也可以 以下操作
查出表名所带主键
1.select * from user_cons_columns where TABLE_NAME="表名";
例如 表名是 DEPT

image.png

那么CONSTRAINT_NAME 字段 PK_DEPT 就是你的主键
alter table "表名" drop constraint "主键名"

③.禁用主键
1.alter table "表名" desable constraint "主键名"
④.启用主键
1.alter table "表名" enable constraint "主键名"


①.添加外键
1创建表格时添加
create table "表1-表名"
(
"列名" 数据类型及长度,
constraint "外键名"(一般外键名称为”fK_”开头) foreign key ("要设为外键的列名") references "表2-表名"(与哪个表有关联) ("表2中该列列名")

)
例如
create table "Meeting"(
"username" varchar2(30),
constraint "fk_username" foreign key ("username") references "User"("username")
)

2创建外之后添加--注意 建立外键的时候 要保证和关联主键的表的数据一致 不能有主键表没有的数据

alter table "表1-表名"
add constraint "外键名称"(一般外键名称为”fK_”开头) foreign key ("要设为外键的列名")
references "表2-表名"(与哪个表有关联) ("表2中该列列名");

例如

alter table "Meeting"
add constraint "fk_RoomNum" foreign key ("RoomNum")
references "MeetingRoom" ("RoomNum")

②.删除外键
alter table "表名" drop constraint "外键名"

image.png

[https://www.cnblogs.com/xielong/p/9121680.html]

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。