sql server
命令建立主键:
1.建表时建立主键
create table Course(
Cno Char(1) primary key,--课程号 建立唯一主键
);
create table Cj(
Sno Char(7),--学号
Cno Char(1),--课程号
Grade Decimal(4,1),--成绩
primary key(Sno,Cno) --建立Sno、Cno联合主键
);
2.建表后插入主键(前提设为主键的属性必须not null)
create table test(
id int,
name char(10),
age smallint
);
alter table test alter column id int not null; --设置为not null
alter table test add primary key(id); --不起名字 系统自动为该主键起个名字 不利于用命令删除
alter table test add constraint PK_test primary key(id);--设置主键并用constraint为主键起个名字
3.删除主键
alter table test drop [constraint] PK_test;--PK_test为主键名 自己起的 自动生成不知道 用可视化工具查看最方便
4.查询表的主键
select * from sysobjects where parent_obj in (select id from sysobjects where name='表名')
and xtype='pk' --可以看到主键名 方便命令删除
可视化工具插入删除查看修改主键
https://blog.csdn.net/hza419763578/article/details/82918915
mysql
1.命令创建主键
create table pk01(
id int,
username varchar(20),
primary key (id)
)
2.命令添加主键
alter table pk02 add primary key(id,username); -- 联合主键
3.命令删除主键
alter table 表名 drop primary key; -- 主键唯一 这样即可 不用主键名