資料庫 主鍵的增刪改查 sql server 與mysql
阿新 • • 發佈:2018-12-15
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' --可以看到主鍵名 方便命令刪除